[SDAG] Start plumbing an assert into SDValues that we don't form one
[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     bool recursivelyDeleteUnusedNodes(SDNode *N);
157
158     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
159                       bool AddTo = true);
160
161     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
162       return CombineTo(N, &Res, 1, AddTo);
163     }
164
165     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
166                       bool AddTo = true) {
167       SDValue To[] = { Res0, Res1 };
168       return CombineTo(N, To, 2, AddTo);
169     }
170
171     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
172
173   private:
174
175     /// SimplifyDemandedBits - Check the specified integer node value to see if
176     /// it can be simplified or if things it uses can be simplified by bit
177     /// propagation.  If so, return true.
178     bool SimplifyDemandedBits(SDValue Op) {
179       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
180       APInt Demanded = APInt::getAllOnesValue(BitWidth);
181       return SimplifyDemandedBits(Op, Demanded);
182     }
183
184     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
185
186     bool CombineToPreIndexedLoadStore(SDNode *N);
187     bool CombineToPostIndexedLoadStore(SDNode *N);
188     bool SliceUpLoad(SDNode *N);
189
190     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
191     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
192     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
193     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
194     SDValue PromoteIntBinOp(SDValue Op);
195     SDValue PromoteIntShiftOp(SDValue Op);
196     SDValue PromoteExtend(SDValue Op);
197     bool PromoteLoad(SDValue Op);
198
199     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
200                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
201                          ISD::NodeType ExtType);
202
203     /// combine - call the node-specific routine that knows how to fold each
204     /// particular type of node. If that doesn't do anything, try the
205     /// target-specific DAG combines.
206     SDValue combine(SDNode *N);
207
208     // Visitation implementation - Implement dag node combining for different
209     // node types.  The semantics are as follows:
210     // Return Value:
211     //   SDValue.getNode() == 0 - No change was made
212     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
213     //   otherwise              - N should be replaced by the returned Operand.
214     //
215     SDValue visitTokenFactor(SDNode *N);
216     SDValue visitMERGE_VALUES(SDNode *N);
217     SDValue visitADD(SDNode *N);
218     SDValue visitSUB(SDNode *N);
219     SDValue visitADDC(SDNode *N);
220     SDValue visitSUBC(SDNode *N);
221     SDValue visitADDE(SDNode *N);
222     SDValue visitSUBE(SDNode *N);
223     SDValue visitMUL(SDNode *N);
224     SDValue visitSDIV(SDNode *N);
225     SDValue visitUDIV(SDNode *N);
226     SDValue visitSREM(SDNode *N);
227     SDValue visitUREM(SDNode *N);
228     SDValue visitMULHU(SDNode *N);
229     SDValue visitMULHS(SDNode *N);
230     SDValue visitSMUL_LOHI(SDNode *N);
231     SDValue visitUMUL_LOHI(SDNode *N);
232     SDValue visitSMULO(SDNode *N);
233     SDValue visitUMULO(SDNode *N);
234     SDValue visitSDIVREM(SDNode *N);
235     SDValue visitUDIVREM(SDNode *N);
236     SDValue visitAND(SDNode *N);
237     SDValue visitOR(SDNode *N);
238     SDValue visitXOR(SDNode *N);
239     SDValue SimplifyVBinOp(SDNode *N);
240     SDValue SimplifyVUnaryOp(SDNode *N);
241     SDValue visitSHL(SDNode *N);
242     SDValue visitSRA(SDNode *N);
243     SDValue visitSRL(SDNode *N);
244     SDValue visitRotate(SDNode *N);
245     SDValue visitCTLZ(SDNode *N);
246     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
247     SDValue visitCTTZ(SDNode *N);
248     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
249     SDValue visitCTPOP(SDNode *N);
250     SDValue visitSELECT(SDNode *N);
251     SDValue visitVSELECT(SDNode *N);
252     SDValue visitSELECT_CC(SDNode *N);
253     SDValue visitSETCC(SDNode *N);
254     SDValue visitSIGN_EXTEND(SDNode *N);
255     SDValue visitZERO_EXTEND(SDNode *N);
256     SDValue visitANY_EXTEND(SDNode *N);
257     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
258     SDValue visitTRUNCATE(SDNode *N);
259     SDValue visitBITCAST(SDNode *N);
260     SDValue visitBUILD_PAIR(SDNode *N);
261     SDValue visitFADD(SDNode *N);
262     SDValue visitFSUB(SDNode *N);
263     SDValue visitFMUL(SDNode *N);
264     SDValue visitFMA(SDNode *N);
265     SDValue visitFDIV(SDNode *N);
266     SDValue visitFREM(SDNode *N);
267     SDValue visitFCOPYSIGN(SDNode *N);
268     SDValue visitSINT_TO_FP(SDNode *N);
269     SDValue visitUINT_TO_FP(SDNode *N);
270     SDValue visitFP_TO_SINT(SDNode *N);
271     SDValue visitFP_TO_UINT(SDNode *N);
272     SDValue visitFP_ROUND(SDNode *N);
273     SDValue visitFP_ROUND_INREG(SDNode *N);
274     SDValue visitFP_EXTEND(SDNode *N);
275     SDValue visitFNEG(SDNode *N);
276     SDValue visitFABS(SDNode *N);
277     SDValue visitFCEIL(SDNode *N);
278     SDValue visitFTRUNC(SDNode *N);
279     SDValue visitFFLOOR(SDNode *N);
280     SDValue visitBRCOND(SDNode *N);
281     SDValue visitBR_CC(SDNode *N);
282     SDValue visitLOAD(SDNode *N);
283     SDValue visitSTORE(SDNode *N);
284     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
285     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
286     SDValue visitBUILD_VECTOR(SDNode *N);
287     SDValue visitCONCAT_VECTORS(SDNode *N);
288     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
289     SDValue visitVECTOR_SHUFFLE(SDNode *N);
290     SDValue visitINSERT_SUBVECTOR(SDNode *N);
291
292     SDValue XformToShuffleWithZero(SDNode *N);
293     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
294
295     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
296
297     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
298     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
299     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
300     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
301                              SDValue N3, ISD::CondCode CC,
302                              bool NotExtCompare = false);
303     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
304                           SDLoc DL, bool foldBooleans = true);
305
306     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
307                            SDValue &CC) const;
308     bool isOneUseSetCC(SDValue N) const;
309
310     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
311                                          unsigned HiOp);
312     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
313     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
314     SDValue BuildSDIV(SDNode *N);
315     SDValue BuildSDIVPow2(SDNode *N);
316     SDValue BuildUDIV(SDNode *N);
317     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
318                                bool DemandHighBits = true);
319     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
320     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
321                               SDValue InnerPos, SDValue InnerNeg,
322                               unsigned PosOpcode, unsigned NegOpcode,
323                               SDLoc DL);
324     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
325     SDValue ReduceLoadWidth(SDNode *N);
326     SDValue ReduceLoadOpStoreWidth(SDNode *N);
327     SDValue TransformFPLoadStorePair(SDNode *N);
328     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
329     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
330
331     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
332
333     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
334     /// looking for aliasing nodes and adding them to the Aliases vector.
335     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
336                           SmallVectorImpl<SDValue> &Aliases);
337
338     /// isAlias - Return true if there is any possibility that the two addresses
339     /// overlap.
340     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
341
342     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
343     /// looking for a better chain (aliasing node.)
344     SDValue FindBetterChain(SDNode *N, SDValue Chain);
345
346     /// Merge consecutive store operations into a wide store.
347     /// This optimization uses wide integers or vectors when possible.
348     /// \return True if some memory operations were changed.
349     bool MergeConsecutiveStores(StoreSDNode *N);
350
351     /// \brief Try to transform a truncation where C is a constant:
352     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
353     ///
354     /// \p N needs to be a truncation and its first operand an AND. Other
355     /// requirements are checked by the function (e.g. that trunc is
356     /// single-use) and if missed an empty SDValue is returned.
357     SDValue distributeTruncateThroughAnd(SDNode *N);
358
359   public:
360     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
361         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
362           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
363       AttributeSet FnAttrs =
364           DAG.getMachineFunction().getFunction()->getAttributes();
365       ForCodeSize =
366           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
367                                Attribute::OptimizeForSize) ||
368           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
369     }
370
371     /// Run - runs the dag combiner on all nodes in the work list
372     void Run(CombineLevel AtLevel);
373
374     SelectionDAG &getDAG() const { return DAG; }
375
376     /// getShiftAmountTy - Returns a type large enough to hold any valid
377     /// shift amount - before type legalization these can be huge.
378     EVT getShiftAmountTy(EVT LHSTy) {
379       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
380       if (LHSTy.isVector())
381         return LHSTy;
382       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
383                         : TLI.getPointerTy();
384     }
385
386     /// isTypeLegal - This method returns true if we are running before type
387     /// legalization or if the specified VT is legal.
388     bool isTypeLegal(const EVT &VT) {
389       if (!LegalTypes) return true;
390       return TLI.isTypeLegal(VT);
391     }
392
393     /// getSetCCResultType - Convenience wrapper around
394     /// TargetLowering::getSetCCResultType
395     EVT getSetCCResultType(EVT VT) const {
396       return TLI.getSetCCResultType(*DAG.getContext(), VT);
397     }
398   };
399 }
400
401
402 namespace {
403 /// WorklistRemover - This class is a DAGUpdateListener that removes any deleted
404 /// nodes from the worklist.
405 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
406   DAGCombiner &DC;
407 public:
408   explicit WorklistRemover(DAGCombiner &dc)
409     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
410
411   void NodeDeleted(SDNode *N, SDNode *E) override {
412     DC.removeFromWorklist(N);
413   }
414 };
415 }
416
417 //===----------------------------------------------------------------------===//
418 //  TargetLowering::DAGCombinerInfo implementation
419 //===----------------------------------------------------------------------===//
420
421 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
422   ((DAGCombiner*)DC)->AddToWorklist(N);
423 }
424
425 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
426   ((DAGCombiner*)DC)->removeFromWorklist(N);
427 }
428
429 SDValue TargetLowering::DAGCombinerInfo::
430 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
431   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
432 }
433
434 SDValue TargetLowering::DAGCombinerInfo::
435 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
436   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
437 }
438
439
440 SDValue TargetLowering::DAGCombinerInfo::
441 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
442   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
443 }
444
445 void TargetLowering::DAGCombinerInfo::
446 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
447   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
448 }
449
450 //===----------------------------------------------------------------------===//
451 // Helper Functions
452 //===----------------------------------------------------------------------===//
453
454 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
455 /// specified expression for the same cost as the expression itself, or 2 if we
456 /// can compute the negated form more cheaply than the expression itself.
457 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
458                                const TargetLowering &TLI,
459                                const TargetOptions *Options,
460                                unsigned Depth = 0) {
461   // fneg is removable even if it has multiple uses.
462   if (Op.getOpcode() == ISD::FNEG) return 2;
463
464   // Don't allow anything with multiple uses.
465   if (!Op.hasOneUse()) return 0;
466
467   // Don't recurse exponentially.
468   if (Depth > 6) return 0;
469
470   switch (Op.getOpcode()) {
471   default: return false;
472   case ISD::ConstantFP:
473     // Don't invert constant FP values after legalize.  The negated constant
474     // isn't necessarily legal.
475     return LegalOperations ? 0 : 1;
476   case ISD::FADD:
477     // FIXME: determine better conditions for this xform.
478     if (!Options->UnsafeFPMath) return 0;
479
480     // After operation legalization, it might not be legal to create new FSUBs.
481     if (LegalOperations &&
482         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
483       return 0;
484
485     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
486     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
487                                     Options, Depth + 1))
488       return V;
489     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
490     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
491                               Depth + 1);
492   case ISD::FSUB:
493     // We can't turn -(A-B) into B-A when we honor signed zeros.
494     if (!Options->UnsafeFPMath) return 0;
495
496     // fold (fneg (fsub A, B)) -> (fsub B, A)
497     return 1;
498
499   case ISD::FMUL:
500   case ISD::FDIV:
501     if (Options->HonorSignDependentRoundingFPMath()) return 0;
502
503     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
504     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
505                                     Options, Depth + 1))
506       return V;
507
508     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
509                               Depth + 1);
510
511   case ISD::FP_EXTEND:
512   case ISD::FP_ROUND:
513   case ISD::FSIN:
514     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
515                               Depth + 1);
516   }
517 }
518
519 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
520 /// returns the newly negated expression.
521 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
522                                     bool LegalOperations, unsigned Depth = 0) {
523   // fneg is removable even if it has multiple uses.
524   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
525
526   // Don't allow anything with multiple uses.
527   assert(Op.hasOneUse() && "Unknown reuse!");
528
529   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
530   switch (Op.getOpcode()) {
531   default: llvm_unreachable("Unknown code");
532   case ISD::ConstantFP: {
533     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
534     V.changeSign();
535     return DAG.getConstantFP(V, Op.getValueType());
536   }
537   case ISD::FADD:
538     // FIXME: determine better conditions for this xform.
539     assert(DAG.getTarget().Options.UnsafeFPMath);
540
541     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
542     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
543                            DAG.getTargetLoweringInfo(),
544                            &DAG.getTarget().Options, Depth+1))
545       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
546                          GetNegatedExpression(Op.getOperand(0), DAG,
547                                               LegalOperations, Depth+1),
548                          Op.getOperand(1));
549     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
550     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
551                        GetNegatedExpression(Op.getOperand(1), DAG,
552                                             LegalOperations, Depth+1),
553                        Op.getOperand(0));
554   case ISD::FSUB:
555     // We can't turn -(A-B) into B-A when we honor signed zeros.
556     assert(DAG.getTarget().Options.UnsafeFPMath);
557
558     // fold (fneg (fsub 0, B)) -> B
559     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
560       if (N0CFP->getValueAPF().isZero())
561         return Op.getOperand(1);
562
563     // fold (fneg (fsub A, B)) -> (fsub B, A)
564     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
565                        Op.getOperand(1), Op.getOperand(0));
566
567   case ISD::FMUL:
568   case ISD::FDIV:
569     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
570
571     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
572     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
573                            DAG.getTargetLoweringInfo(),
574                            &DAG.getTarget().Options, Depth+1))
575       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
576                          GetNegatedExpression(Op.getOperand(0), DAG,
577                                               LegalOperations, Depth+1),
578                          Op.getOperand(1));
579
580     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
581     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
582                        Op.getOperand(0),
583                        GetNegatedExpression(Op.getOperand(1), DAG,
584                                             LegalOperations, Depth+1));
585
586   case ISD::FP_EXTEND:
587   case ISD::FSIN:
588     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
589                        GetNegatedExpression(Op.getOperand(0), DAG,
590                                             LegalOperations, Depth+1));
591   case ISD::FP_ROUND:
592       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
593                          GetNegatedExpression(Op.getOperand(0), DAG,
594                                               LegalOperations, Depth+1),
595                          Op.getOperand(1));
596   }
597 }
598
599 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
600 // that selects between the target values used for true and false, making it
601 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
602 // the appropriate nodes based on the type of node we are checking. This
603 // simplifies life a bit for the callers.
604 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
605                                     SDValue &CC) const {
606   if (N.getOpcode() == ISD::SETCC) {
607     LHS = N.getOperand(0);
608     RHS = N.getOperand(1);
609     CC  = N.getOperand(2);
610     return true;
611   }
612
613   if (N.getOpcode() != ISD::SELECT_CC ||
614       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
615       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
616     return false;
617
618   LHS = N.getOperand(0);
619   RHS = N.getOperand(1);
620   CC  = N.getOperand(4);
621   return true;
622 }
623
624 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
625 // one use.  If this is true, it allows the users to invert the operation for
626 // free when it is profitable to do so.
627 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
628   SDValue N0, N1, N2;
629   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
630     return true;
631   return false;
632 }
633
634 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
635 /// elements are all the same constant or undefined.
636 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
637   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
638   if (!C)
639     return false;
640
641   APInt SplatUndef;
642   unsigned SplatBitSize;
643   bool HasAnyUndefs;
644   EVT EltVT = N->getValueType(0).getVectorElementType();
645   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
646                              HasAnyUndefs) &&
647           EltVT.getSizeInBits() >= SplatBitSize);
648 }
649
650 // \brief Returns the SDNode if it is a constant BuildVector or constant.
651 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
652   if (isa<ConstantSDNode>(N))
653     return N.getNode();
654   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
655   if(BV && BV->isConstant())
656     return BV;
657   return nullptr;
658 }
659
660 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
661 // int.
662 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
663   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
664     return CN;
665
666   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
667     BitVector UndefElements;
668     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
669
670     // BuildVectors can truncate their operands. Ignore that case here.
671     // FIXME: We blindly ignore splats which include undef which is overly
672     // pessimistic.
673     if (CN && UndefElements.none() &&
674         CN->getValueType(0) == N.getValueType().getScalarType())
675       return CN;
676   }
677
678   return nullptr;
679 }
680
681 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
682                                     SDValue N0, SDValue N1) {
683   EVT VT = N0.getValueType();
684   if (N0.getOpcode() == Opc) {
685     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
686       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
687         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
688         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
689         if (!OpNode.getNode())
690           return SDValue();
691         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
692       }
693       if (N0.hasOneUse()) {
694         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
695         // use
696         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
697         if (!OpNode.getNode())
698           return SDValue();
699         AddToWorklist(OpNode.getNode());
700         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
701       }
702     }
703   }
704
705   if (N1.getOpcode() == Opc) {
706     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
707       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
708         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
709         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
710         if (!OpNode.getNode())
711           return SDValue();
712         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
713       }
714       if (N1.hasOneUse()) {
715         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
716         // use
717         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
718         if (!OpNode.getNode())
719           return SDValue();
720         AddToWorklist(OpNode.getNode());
721         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
722       }
723     }
724   }
725
726   return SDValue();
727 }
728
729 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
730                                bool AddTo) {
731   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
732   ++NodesCombined;
733   DEBUG(dbgs() << "\nReplacing.1 ";
734         N->dump(&DAG);
735         dbgs() << "\nWith: ";
736         To[0].getNode()->dump(&DAG);
737         dbgs() << " and " << NumTo-1 << " other values\n";
738         for (unsigned i = 0, e = NumTo; i != e; ++i)
739           assert((!To[i].getNode() ||
740                   N->getValueType(i) == To[i].getValueType()) &&
741                  "Cannot combine value to value of different type!"));
742   WorklistRemover DeadNodes(*this);
743   DAG.ReplaceAllUsesWith(N, To);
744   if (AddTo) {
745     // Push the new nodes and any users onto the worklist
746     for (unsigned i = 0, e = NumTo; i != e; ++i) {
747       if (To[i].getNode()) {
748         AddToWorklist(To[i].getNode());
749         AddUsersToWorklist(To[i].getNode());
750       }
751     }
752   }
753
754   // Finally, if the node is now dead, remove it from the graph.  The node
755   // may not be dead if the replacement process recursively simplified to
756   // something else needing this node.
757   if (N->use_empty()) {
758     // Nodes can be reintroduced into the worklist.  Make sure we do not
759     // process a node that has been replaced.
760     removeFromWorklist(N);
761
762     // Finally, since the node is now dead, remove it from the graph.
763     DAG.DeleteNode(N);
764   }
765   return SDValue(N, 0);
766 }
767
768 void DAGCombiner::
769 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
770   // Replace all uses.  If any nodes become isomorphic to other nodes and
771   // are deleted, make sure to remove them from our worklist.
772   WorklistRemover DeadNodes(*this);
773   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
774
775   // Push the new node and any (possibly new) users onto the worklist.
776   AddToWorklist(TLO.New.getNode());
777   AddUsersToWorklist(TLO.New.getNode());
778
779   // Finally, if the node is now dead, remove it from the graph.  The node
780   // may not be dead if the replacement process recursively simplified to
781   // something else needing this node.
782   if (TLO.Old.getNode()->use_empty()) {
783     removeFromWorklist(TLO.Old.getNode());
784
785     // If the operands of this node are only used by the node, they will now
786     // be dead.  Make sure to visit them first to delete dead nodes early.
787     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
788       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
789         AddToWorklist(TLO.Old.getNode()->getOperand(i).getNode());
790
791     DAG.DeleteNode(TLO.Old.getNode());
792   }
793 }
794
795 /// SimplifyDemandedBits - Check the specified integer node value to see if
796 /// it can be simplified or if things it uses can be simplified by bit
797 /// propagation.  If so, return true.
798 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
799   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
800   APInt KnownZero, KnownOne;
801   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
802     return false;
803
804   // Revisit the node.
805   AddToWorklist(Op.getNode());
806
807   // Replace the old value with the new one.
808   ++NodesCombined;
809   DEBUG(dbgs() << "\nReplacing.2 ";
810         TLO.Old.getNode()->dump(&DAG);
811         dbgs() << "\nWith: ";
812         TLO.New.getNode()->dump(&DAG);
813         dbgs() << '\n');
814
815   CommitTargetLoweringOpt(TLO);
816   return true;
817 }
818
819 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
820   SDLoc dl(Load);
821   EVT VT = Load->getValueType(0);
822   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
823
824   DEBUG(dbgs() << "\nReplacing.9 ";
825         Load->dump(&DAG);
826         dbgs() << "\nWith: ";
827         Trunc.getNode()->dump(&DAG);
828         dbgs() << '\n');
829   WorklistRemover DeadNodes(*this);
830   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
831   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
832   removeFromWorklist(Load);
833   DAG.DeleteNode(Load);
834   AddToWorklist(Trunc.getNode());
835 }
836
837 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
838   Replace = false;
839   SDLoc dl(Op);
840   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
841     EVT MemVT = LD->getMemoryVT();
842     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
843       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
844                                                   : ISD::EXTLOAD)
845       : LD->getExtensionType();
846     Replace = true;
847     return DAG.getExtLoad(ExtType, dl, PVT,
848                           LD->getChain(), LD->getBasePtr(),
849                           MemVT, LD->getMemOperand());
850   }
851
852   unsigned Opc = Op.getOpcode();
853   switch (Opc) {
854   default: break;
855   case ISD::AssertSext:
856     return DAG.getNode(ISD::AssertSext, dl, PVT,
857                        SExtPromoteOperand(Op.getOperand(0), PVT),
858                        Op.getOperand(1));
859   case ISD::AssertZext:
860     return DAG.getNode(ISD::AssertZext, dl, PVT,
861                        ZExtPromoteOperand(Op.getOperand(0), PVT),
862                        Op.getOperand(1));
863   case ISD::Constant: {
864     unsigned ExtOpc =
865       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
866     return DAG.getNode(ExtOpc, dl, PVT, Op);
867   }
868   }
869
870   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
871     return SDValue();
872   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
873 }
874
875 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
876   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
877     return SDValue();
878   EVT OldVT = Op.getValueType();
879   SDLoc dl(Op);
880   bool Replace = false;
881   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
882   if (!NewOp.getNode())
883     return SDValue();
884   AddToWorklist(NewOp.getNode());
885
886   if (Replace)
887     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
888   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
889                      DAG.getValueType(OldVT));
890 }
891
892 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
893   EVT OldVT = Op.getValueType();
894   SDLoc dl(Op);
895   bool Replace = false;
896   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
897   if (!NewOp.getNode())
898     return SDValue();
899   AddToWorklist(NewOp.getNode());
900
901   if (Replace)
902     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
903   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
904 }
905
906 /// PromoteIntBinOp - Promote the specified integer binary operation if the
907 /// target indicates it is beneficial. e.g. On x86, it's usually better to
908 /// promote i16 operations to i32 since i16 instructions are longer.
909 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
910   if (!LegalOperations)
911     return SDValue();
912
913   EVT VT = Op.getValueType();
914   if (VT.isVector() || !VT.isInteger())
915     return SDValue();
916
917   // If operation type is 'undesirable', e.g. i16 on x86, consider
918   // promoting it.
919   unsigned Opc = Op.getOpcode();
920   if (TLI.isTypeDesirableForOp(Opc, VT))
921     return SDValue();
922
923   EVT PVT = VT;
924   // Consult target whether it is a good idea to promote this operation and
925   // what's the right type to promote it to.
926   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
927     assert(PVT != VT && "Don't know what type to promote to!");
928
929     bool Replace0 = false;
930     SDValue N0 = Op.getOperand(0);
931     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
932     if (!NN0.getNode())
933       return SDValue();
934
935     bool Replace1 = false;
936     SDValue N1 = Op.getOperand(1);
937     SDValue NN1;
938     if (N0 == N1)
939       NN1 = NN0;
940     else {
941       NN1 = PromoteOperand(N1, PVT, Replace1);
942       if (!NN1.getNode())
943         return SDValue();
944     }
945
946     AddToWorklist(NN0.getNode());
947     if (NN1.getNode())
948       AddToWorklist(NN1.getNode());
949
950     if (Replace0)
951       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
952     if (Replace1)
953       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
954
955     DEBUG(dbgs() << "\nPromoting ";
956           Op.getNode()->dump(&DAG));
957     SDLoc dl(Op);
958     return DAG.getNode(ISD::TRUNCATE, dl, VT,
959                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
960   }
961   return SDValue();
962 }
963
964 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
965 /// target indicates it is beneficial. e.g. On x86, it's usually better to
966 /// promote i16 operations to i32 since i16 instructions are longer.
967 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
968   if (!LegalOperations)
969     return SDValue();
970
971   EVT VT = Op.getValueType();
972   if (VT.isVector() || !VT.isInteger())
973     return SDValue();
974
975   // If operation type is 'undesirable', e.g. i16 on x86, consider
976   // promoting it.
977   unsigned Opc = Op.getOpcode();
978   if (TLI.isTypeDesirableForOp(Opc, VT))
979     return SDValue();
980
981   EVT PVT = VT;
982   // Consult target whether it is a good idea to promote this operation and
983   // what's the right type to promote it to.
984   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
985     assert(PVT != VT && "Don't know what type to promote to!");
986
987     bool Replace = false;
988     SDValue N0 = Op.getOperand(0);
989     if (Opc == ISD::SRA)
990       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
991     else if (Opc == ISD::SRL)
992       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
993     else
994       N0 = PromoteOperand(N0, PVT, Replace);
995     if (!N0.getNode())
996       return SDValue();
997
998     AddToWorklist(N0.getNode());
999     if (Replace)
1000       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1001
1002     DEBUG(dbgs() << "\nPromoting ";
1003           Op.getNode()->dump(&DAG));
1004     SDLoc dl(Op);
1005     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1006                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1007   }
1008   return SDValue();
1009 }
1010
1011 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1012   if (!LegalOperations)
1013     return SDValue();
1014
1015   EVT VT = Op.getValueType();
1016   if (VT.isVector() || !VT.isInteger())
1017     return SDValue();
1018
1019   // If operation type is 'undesirable', e.g. i16 on x86, consider
1020   // promoting it.
1021   unsigned Opc = Op.getOpcode();
1022   if (TLI.isTypeDesirableForOp(Opc, VT))
1023     return SDValue();
1024
1025   EVT PVT = VT;
1026   // Consult target whether it is a good idea to promote this operation and
1027   // what's the right type to promote it to.
1028   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1029     assert(PVT != VT && "Don't know what type to promote to!");
1030     // fold (aext (aext x)) -> (aext x)
1031     // fold (aext (zext x)) -> (zext x)
1032     // fold (aext (sext x)) -> (sext x)
1033     DEBUG(dbgs() << "\nPromoting ";
1034           Op.getNode()->dump(&DAG));
1035     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1036   }
1037   return SDValue();
1038 }
1039
1040 bool DAGCombiner::PromoteLoad(SDValue Op) {
1041   if (!LegalOperations)
1042     return false;
1043
1044   EVT VT = Op.getValueType();
1045   if (VT.isVector() || !VT.isInteger())
1046     return false;
1047
1048   // If operation type is 'undesirable', e.g. i16 on x86, consider
1049   // promoting it.
1050   unsigned Opc = Op.getOpcode();
1051   if (TLI.isTypeDesirableForOp(Opc, VT))
1052     return false;
1053
1054   EVT PVT = VT;
1055   // Consult target whether it is a good idea to promote this operation and
1056   // what's the right type to promote it to.
1057   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1058     assert(PVT != VT && "Don't know what type to promote to!");
1059
1060     SDLoc dl(Op);
1061     SDNode *N = Op.getNode();
1062     LoadSDNode *LD = cast<LoadSDNode>(N);
1063     EVT MemVT = LD->getMemoryVT();
1064     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1065       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1066                                                   : ISD::EXTLOAD)
1067       : LD->getExtensionType();
1068     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1069                                    LD->getChain(), LD->getBasePtr(),
1070                                    MemVT, LD->getMemOperand());
1071     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1072
1073     DEBUG(dbgs() << "\nPromoting ";
1074           N->dump(&DAG);
1075           dbgs() << "\nTo: ";
1076           Result.getNode()->dump(&DAG);
1077           dbgs() << '\n');
1078     WorklistRemover DeadNodes(*this);
1079     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1080     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1081     removeFromWorklist(N);
1082     DAG.DeleteNode(N);
1083     AddToWorklist(Result.getNode());
1084     return true;
1085   }
1086   return false;
1087 }
1088
1089 /// \brief Recursively delete a node which has no uses and any operands for
1090 /// which it is the only use.
1091 ///
1092 /// Note that this both deletes the nodes and removes them from the worklist.
1093 /// It also adds any nodes who have had a user deleted to the worklist as they
1094 /// may now have only one use and subject to other combines.
1095 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1096   if (!N->use_empty())
1097     return false;
1098
1099   SmallSetVector<SDNode *, 16> Nodes;
1100   Nodes.insert(N);
1101   do {
1102     N = Nodes.pop_back_val();
1103     if (!N)
1104       continue;
1105
1106     if (N->use_empty()) {
1107       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1108         Nodes.insert(N->getOperand(i).getNode());
1109
1110       removeFromWorklist(N);
1111       DAG.DeleteNode(N);
1112     } else {
1113       AddToWorklist(N);
1114     }
1115   } while (!Nodes.empty());
1116   return true;
1117 }
1118
1119 //===----------------------------------------------------------------------===//
1120 //  Main DAG Combiner implementation
1121 //===----------------------------------------------------------------------===//
1122
1123 void DAGCombiner::Run(CombineLevel AtLevel) {
1124   // set the instance variables, so that the various visit routines may use it.
1125   Level = AtLevel;
1126   LegalOperations = Level >= AfterLegalizeVectorOps;
1127   LegalTypes = Level >= AfterLegalizeTypes;
1128
1129   // Add all the dag nodes to the worklist.
1130   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1131        E = DAG.allnodes_end(); I != E; ++I)
1132     AddToWorklist(I);
1133
1134   // Create a dummy node (which is not added to allnodes), that adds a reference
1135   // to the root node, preventing it from being deleted, and tracking any
1136   // changes of the root.
1137   HandleSDNode Dummy(DAG.getRoot());
1138
1139   // The root of the dag may dangle to deleted nodes until the dag combiner is
1140   // done.  Set it to null to avoid confusion.
1141   DAG.setRoot(SDValue());
1142
1143   // while the worklist isn't empty, find a node and
1144   // try and combine it.
1145   while (!WorklistMap.empty()) {
1146     SDNode *N;
1147     // The Worklist holds the SDNodes in order, but it may contain null entries.
1148     do {
1149       N = Worklist.pop_back_val();
1150     } while (!N);
1151
1152     bool GoodWorklistEntry = WorklistMap.erase(N);
1153     (void)GoodWorklistEntry;
1154     assert(GoodWorklistEntry &&
1155            "Found a worklist entry without a corresponding map entry!");
1156
1157     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1158     // N is deleted from the DAG, since they too may now be dead or may have a
1159     // reduced number of uses, allowing other xforms.
1160     if (recursivelyDeleteUnusedNodes(N))
1161       continue;
1162
1163     DEBUG(dbgs() << "\nCombining: ";
1164           N->dump(&DAG));
1165
1166     // Add any operands of the new node which have not yet been combined to the
1167     // worklist as well. Because the worklist uniques things already, this
1168     // won't repeatedly process the same operand.
1169     CombinedNodes.insert(N);
1170     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1171       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1172         AddToWorklist(N->getOperand(i).getNode());
1173
1174     WorklistRemover DeadNodes(*this);
1175
1176     SDValue RV = combine(N);
1177
1178     if (!RV.getNode())
1179       continue;
1180
1181     ++NodesCombined;
1182
1183     // If we get back the same node we passed in, rather than a new node or
1184     // zero, we know that the node must have defined multiple values and
1185     // CombineTo was used.  Since CombineTo takes care of the worklist
1186     // mechanics for us, we have no work to do in this case.
1187     if (RV.getNode() == N)
1188       continue;
1189
1190     assert(N->getOpcode() != ISD::DELETED_NODE &&
1191            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1192            "Node was deleted but visit returned new node!");
1193
1194     DEBUG(dbgs() << " ... into: ";
1195           RV.getNode()->dump(&DAG));
1196
1197     // Transfer debug value.
1198     DAG.TransferDbgValues(SDValue(N, 0), RV);
1199     if (N->getNumValues() == RV.getNode()->getNumValues())
1200       DAG.ReplaceAllUsesWith(N, RV.getNode());
1201     else {
1202       assert(N->getValueType(0) == RV.getValueType() &&
1203              N->getNumValues() == 1 && "Type mismatch");
1204       SDValue OpV = RV;
1205       DAG.ReplaceAllUsesWith(N, &OpV);
1206     }
1207
1208     // Push the new node and any users onto the worklist
1209     AddToWorklist(RV.getNode());
1210     AddUsersToWorklist(RV.getNode());
1211
1212     // Finally, if the node is now dead, remove it from the graph.  The node
1213     // may not be dead if the replacement process recursively simplified to
1214     // something else needing this node. This will also take care of adding any
1215     // operands which have lost a user to the worklist.
1216     recursivelyDeleteUnusedNodes(N);
1217   }
1218
1219   // If the root changed (e.g. it was a dead load, update the root).
1220   DAG.setRoot(Dummy.getValue());
1221   DAG.RemoveDeadNodes();
1222 }
1223
1224 SDValue DAGCombiner::visit(SDNode *N) {
1225   switch (N->getOpcode()) {
1226   default: break;
1227   case ISD::TokenFactor:        return visitTokenFactor(N);
1228   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1229   case ISD::ADD:                return visitADD(N);
1230   case ISD::SUB:                return visitSUB(N);
1231   case ISD::ADDC:               return visitADDC(N);
1232   case ISD::SUBC:               return visitSUBC(N);
1233   case ISD::ADDE:               return visitADDE(N);
1234   case ISD::SUBE:               return visitSUBE(N);
1235   case ISD::MUL:                return visitMUL(N);
1236   case ISD::SDIV:               return visitSDIV(N);
1237   case ISD::UDIV:               return visitUDIV(N);
1238   case ISD::SREM:               return visitSREM(N);
1239   case ISD::UREM:               return visitUREM(N);
1240   case ISD::MULHU:              return visitMULHU(N);
1241   case ISD::MULHS:              return visitMULHS(N);
1242   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1243   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1244   case ISD::SMULO:              return visitSMULO(N);
1245   case ISD::UMULO:              return visitUMULO(N);
1246   case ISD::SDIVREM:            return visitSDIVREM(N);
1247   case ISD::UDIVREM:            return visitUDIVREM(N);
1248   case ISD::AND:                return visitAND(N);
1249   case ISD::OR:                 return visitOR(N);
1250   case ISD::XOR:                return visitXOR(N);
1251   case ISD::SHL:                return visitSHL(N);
1252   case ISD::SRA:                return visitSRA(N);
1253   case ISD::SRL:                return visitSRL(N);
1254   case ISD::ROTR:
1255   case ISD::ROTL:               return visitRotate(N);
1256   case ISD::CTLZ:               return visitCTLZ(N);
1257   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1258   case ISD::CTTZ:               return visitCTTZ(N);
1259   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1260   case ISD::CTPOP:              return visitCTPOP(N);
1261   case ISD::SELECT:             return visitSELECT(N);
1262   case ISD::VSELECT:            return visitVSELECT(N);
1263   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1264   case ISD::SETCC:              return visitSETCC(N);
1265   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1266   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1267   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1268   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1269   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1270   case ISD::BITCAST:            return visitBITCAST(N);
1271   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1272   case ISD::FADD:               return visitFADD(N);
1273   case ISD::FSUB:               return visitFSUB(N);
1274   case ISD::FMUL:               return visitFMUL(N);
1275   case ISD::FMA:                return visitFMA(N);
1276   case ISD::FDIV:               return visitFDIV(N);
1277   case ISD::FREM:               return visitFREM(N);
1278   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1279   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1280   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1281   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1282   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1283   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1284   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1285   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1286   case ISD::FNEG:               return visitFNEG(N);
1287   case ISD::FABS:               return visitFABS(N);
1288   case ISD::FFLOOR:             return visitFFLOOR(N);
1289   case ISD::FCEIL:              return visitFCEIL(N);
1290   case ISD::FTRUNC:             return visitFTRUNC(N);
1291   case ISD::BRCOND:             return visitBRCOND(N);
1292   case ISD::BR_CC:              return visitBR_CC(N);
1293   case ISD::LOAD:               return visitLOAD(N);
1294   case ISD::STORE:              return visitSTORE(N);
1295   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1296   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1297   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1298   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1299   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1300   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1301   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1302   }
1303   return SDValue();
1304 }
1305
1306 SDValue DAGCombiner::combine(SDNode *N) {
1307   SDValue RV = visit(N);
1308
1309   // If nothing happened, try a target-specific DAG combine.
1310   if (!RV.getNode()) {
1311     assert(N->getOpcode() != ISD::DELETED_NODE &&
1312            "Node was deleted but visit returned NULL!");
1313
1314     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1315         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1316
1317       // Expose the DAG combiner to the target combiner impls.
1318       TargetLowering::DAGCombinerInfo
1319         DagCombineInfo(DAG, Level, false, this);
1320
1321       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1322     }
1323   }
1324
1325   // If nothing happened still, try promoting the operation.
1326   if (!RV.getNode()) {
1327     switch (N->getOpcode()) {
1328     default: break;
1329     case ISD::ADD:
1330     case ISD::SUB:
1331     case ISD::MUL:
1332     case ISD::AND:
1333     case ISD::OR:
1334     case ISD::XOR:
1335       RV = PromoteIntBinOp(SDValue(N, 0));
1336       break;
1337     case ISD::SHL:
1338     case ISD::SRA:
1339     case ISD::SRL:
1340       RV = PromoteIntShiftOp(SDValue(N, 0));
1341       break;
1342     case ISD::SIGN_EXTEND:
1343     case ISD::ZERO_EXTEND:
1344     case ISD::ANY_EXTEND:
1345       RV = PromoteExtend(SDValue(N, 0));
1346       break;
1347     case ISD::LOAD:
1348       if (PromoteLoad(SDValue(N, 0)))
1349         RV = SDValue(N, 0);
1350       break;
1351     }
1352   }
1353
1354   // If N is a commutative binary node, try commuting it to enable more
1355   // sdisel CSE.
1356   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1357       N->getNumValues() == 1) {
1358     SDValue N0 = N->getOperand(0);
1359     SDValue N1 = N->getOperand(1);
1360
1361     // Constant operands are canonicalized to RHS.
1362     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1363       SDValue Ops[] = {N1, N0};
1364       SDNode *CSENode;
1365       if (const BinaryWithFlagsSDNode *BinNode =
1366               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1367         CSENode = DAG.getNodeIfExists(
1368             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1369             BinNode->hasNoSignedWrap(), BinNode->isExact());
1370       } else {
1371         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1372       }
1373       if (CSENode)
1374         return SDValue(CSENode, 0);
1375     }
1376   }
1377
1378   return RV;
1379 }
1380
1381 /// getInputChainForNode - Given a node, return its input chain if it has one,
1382 /// otherwise return a null sd operand.
1383 static SDValue getInputChainForNode(SDNode *N) {
1384   if (unsigned NumOps = N->getNumOperands()) {
1385     if (N->getOperand(0).getValueType() == MVT::Other)
1386       return N->getOperand(0);
1387     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1388       return N->getOperand(NumOps-1);
1389     for (unsigned i = 1; i < NumOps-1; ++i)
1390       if (N->getOperand(i).getValueType() == MVT::Other)
1391         return N->getOperand(i);
1392   }
1393   return SDValue();
1394 }
1395
1396 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1397   // If N has two operands, where one has an input chain equal to the other,
1398   // the 'other' chain is redundant.
1399   if (N->getNumOperands() == 2) {
1400     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1401       return N->getOperand(0);
1402     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1403       return N->getOperand(1);
1404   }
1405
1406   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1407   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1408   SmallPtrSet<SDNode*, 16> SeenOps;
1409   bool Changed = false;             // If we should replace this token factor.
1410
1411   // Start out with this token factor.
1412   TFs.push_back(N);
1413
1414   // Iterate through token factors.  The TFs grows when new token factors are
1415   // encountered.
1416   for (unsigned i = 0; i < TFs.size(); ++i) {
1417     SDNode *TF = TFs[i];
1418
1419     // Check each of the operands.
1420     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1421       SDValue Op = TF->getOperand(i);
1422
1423       switch (Op.getOpcode()) {
1424       case ISD::EntryToken:
1425         // Entry tokens don't need to be added to the list. They are
1426         // rededundant.
1427         Changed = true;
1428         break;
1429
1430       case ISD::TokenFactor:
1431         if (Op.hasOneUse() &&
1432             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1433           // Queue up for processing.
1434           TFs.push_back(Op.getNode());
1435           // Clean up in case the token factor is removed.
1436           AddToWorklist(Op.getNode());
1437           Changed = true;
1438           break;
1439         }
1440         // Fall thru
1441
1442       default:
1443         // Only add if it isn't already in the list.
1444         if (SeenOps.insert(Op.getNode()))
1445           Ops.push_back(Op);
1446         else
1447           Changed = true;
1448         break;
1449       }
1450     }
1451   }
1452
1453   SDValue Result;
1454
1455   // If we've change things around then replace token factor.
1456   if (Changed) {
1457     if (Ops.empty()) {
1458       // The entry token is the only possible outcome.
1459       Result = DAG.getEntryNode();
1460     } else {
1461       // New and improved token factor.
1462       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1463     }
1464
1465     // Don't add users to work list.
1466     return CombineTo(N, Result, false);
1467   }
1468
1469   return Result;
1470 }
1471
1472 /// MERGE_VALUES can always be eliminated.
1473 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1474   WorklistRemover DeadNodes(*this);
1475   // Replacing results may cause a different MERGE_VALUES to suddenly
1476   // be CSE'd with N, and carry its uses with it. Iterate until no
1477   // uses remain, to ensure that the node can be safely deleted.
1478   // First add the users of this node to the work list so that they
1479   // can be tried again once they have new operands.
1480   AddUsersToWorklist(N);
1481   do {
1482     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1483       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1484   } while (!N->use_empty());
1485   removeFromWorklist(N);
1486   DAG.DeleteNode(N);
1487   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1488 }
1489
1490 static
1491 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1492                               SelectionDAG &DAG) {
1493   EVT VT = N0.getValueType();
1494   SDValue N00 = N0.getOperand(0);
1495   SDValue N01 = N0.getOperand(1);
1496   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1497
1498   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1499       isa<ConstantSDNode>(N00.getOperand(1))) {
1500     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1501     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1502                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1503                                  N00.getOperand(0), N01),
1504                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1505                                  N00.getOperand(1), N01));
1506     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1507   }
1508
1509   return SDValue();
1510 }
1511
1512 SDValue DAGCombiner::visitADD(SDNode *N) {
1513   SDValue N0 = N->getOperand(0);
1514   SDValue N1 = N->getOperand(1);
1515   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1516   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1517   EVT VT = N0.getValueType();
1518
1519   // fold vector ops
1520   if (VT.isVector()) {
1521     SDValue FoldedVOp = SimplifyVBinOp(N);
1522     if (FoldedVOp.getNode()) return FoldedVOp;
1523
1524     // fold (add x, 0) -> x, vector edition
1525     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1526       return N0;
1527     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1528       return N1;
1529   }
1530
1531   // fold (add x, undef) -> undef
1532   if (N0.getOpcode() == ISD::UNDEF)
1533     return N0;
1534   if (N1.getOpcode() == ISD::UNDEF)
1535     return N1;
1536   // fold (add c1, c2) -> c1+c2
1537   if (N0C && N1C)
1538     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1539   // canonicalize constant to RHS
1540   if (N0C && !N1C)
1541     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1542   // fold (add x, 0) -> x
1543   if (N1C && N1C->isNullValue())
1544     return N0;
1545   // fold (add Sym, c) -> Sym+c
1546   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1547     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1548         GA->getOpcode() == ISD::GlobalAddress)
1549       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1550                                   GA->getOffset() +
1551                                     (uint64_t)N1C->getSExtValue());
1552   // fold ((c1-A)+c2) -> (c1+c2)-A
1553   if (N1C && N0.getOpcode() == ISD::SUB)
1554     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1555       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1556                          DAG.getConstant(N1C->getAPIntValue()+
1557                                          N0C->getAPIntValue(), VT),
1558                          N0.getOperand(1));
1559   // reassociate add
1560   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1561   if (RADD.getNode())
1562     return RADD;
1563   // fold ((0-A) + B) -> B-A
1564   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1565       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1566     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1567   // fold (A + (0-B)) -> A-B
1568   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1569       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1570     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1571   // fold (A+(B-A)) -> B
1572   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1573     return N1.getOperand(0);
1574   // fold ((B-A)+A) -> B
1575   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1576     return N0.getOperand(0);
1577   // fold (A+(B-(A+C))) to (B-C)
1578   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1579       N0 == N1.getOperand(1).getOperand(0))
1580     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1581                        N1.getOperand(1).getOperand(1));
1582   // fold (A+(B-(C+A))) to (B-C)
1583   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1584       N0 == N1.getOperand(1).getOperand(1))
1585     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1586                        N1.getOperand(1).getOperand(0));
1587   // fold (A+((B-A)+or-C)) to (B+or-C)
1588   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1589       N1.getOperand(0).getOpcode() == ISD::SUB &&
1590       N0 == N1.getOperand(0).getOperand(1))
1591     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1592                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1593
1594   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1595   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1596     SDValue N00 = N0.getOperand(0);
1597     SDValue N01 = N0.getOperand(1);
1598     SDValue N10 = N1.getOperand(0);
1599     SDValue N11 = N1.getOperand(1);
1600
1601     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1602       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1603                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1604                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1605   }
1606
1607   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1608     return SDValue(N, 0);
1609
1610   // fold (a+b) -> (a|b) iff a and b share no bits.
1611   if (VT.isInteger() && !VT.isVector()) {
1612     APInt LHSZero, LHSOne;
1613     APInt RHSZero, RHSOne;
1614     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1615
1616     if (LHSZero.getBoolValue()) {
1617       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1618
1619       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1620       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1621       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1622         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1623           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1624       }
1625     }
1626   }
1627
1628   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1629   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1630     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1631     if (Result.getNode()) return Result;
1632   }
1633   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1634     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1635     if (Result.getNode()) return Result;
1636   }
1637
1638   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1639   if (N1.getOpcode() == ISD::SHL &&
1640       N1.getOperand(0).getOpcode() == ISD::SUB)
1641     if (ConstantSDNode *C =
1642           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1643       if (C->getAPIntValue() == 0)
1644         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1645                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1646                                        N1.getOperand(0).getOperand(1),
1647                                        N1.getOperand(1)));
1648   if (N0.getOpcode() == ISD::SHL &&
1649       N0.getOperand(0).getOpcode() == ISD::SUB)
1650     if (ConstantSDNode *C =
1651           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1652       if (C->getAPIntValue() == 0)
1653         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1654                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1655                                        N0.getOperand(0).getOperand(1),
1656                                        N0.getOperand(1)));
1657
1658   if (N1.getOpcode() == ISD::AND) {
1659     SDValue AndOp0 = N1.getOperand(0);
1660     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1661     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1662     unsigned DestBits = VT.getScalarType().getSizeInBits();
1663
1664     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1665     // and similar xforms where the inner op is either ~0 or 0.
1666     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1667       SDLoc DL(N);
1668       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1669     }
1670   }
1671
1672   // add (sext i1), X -> sub X, (zext i1)
1673   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1674       N0.getOperand(0).getValueType() == MVT::i1 &&
1675       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1676     SDLoc DL(N);
1677     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1678     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1679   }
1680
1681   return SDValue();
1682 }
1683
1684 SDValue DAGCombiner::visitADDC(SDNode *N) {
1685   SDValue N0 = N->getOperand(0);
1686   SDValue N1 = N->getOperand(1);
1687   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1688   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1689   EVT VT = N0.getValueType();
1690
1691   // If the flag result is dead, turn this into an ADD.
1692   if (!N->hasAnyUseOfValue(1))
1693     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1694                      DAG.getNode(ISD::CARRY_FALSE,
1695                                  SDLoc(N), MVT::Glue));
1696
1697   // canonicalize constant to RHS.
1698   if (N0C && !N1C)
1699     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1700
1701   // fold (addc x, 0) -> x + no carry out
1702   if (N1C && N1C->isNullValue())
1703     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1704                                         SDLoc(N), MVT::Glue));
1705
1706   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1707   APInt LHSZero, LHSOne;
1708   APInt RHSZero, RHSOne;
1709   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1710
1711   if (LHSZero.getBoolValue()) {
1712     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1713
1714     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1715     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1716     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1717       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1718                        DAG.getNode(ISD::CARRY_FALSE,
1719                                    SDLoc(N), MVT::Glue));
1720   }
1721
1722   return SDValue();
1723 }
1724
1725 SDValue DAGCombiner::visitADDE(SDNode *N) {
1726   SDValue N0 = N->getOperand(0);
1727   SDValue N1 = N->getOperand(1);
1728   SDValue CarryIn = N->getOperand(2);
1729   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1730   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1731
1732   // canonicalize constant to RHS
1733   if (N0C && !N1C)
1734     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1735                        N1, N0, CarryIn);
1736
1737   // fold (adde x, y, false) -> (addc x, y)
1738   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1739     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1740
1741   return SDValue();
1742 }
1743
1744 // Since it may not be valid to emit a fold to zero for vector initializers
1745 // check if we can before folding.
1746 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1747                              SelectionDAG &DAG,
1748                              bool LegalOperations, bool LegalTypes) {
1749   if (!VT.isVector())
1750     return DAG.getConstant(0, VT);
1751   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1752     return DAG.getConstant(0, VT);
1753   return SDValue();
1754 }
1755
1756 SDValue DAGCombiner::visitSUB(SDNode *N) {
1757   SDValue N0 = N->getOperand(0);
1758   SDValue N1 = N->getOperand(1);
1759   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1760   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1761   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1762     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1763   EVT VT = N0.getValueType();
1764
1765   // fold vector ops
1766   if (VT.isVector()) {
1767     SDValue FoldedVOp = SimplifyVBinOp(N);
1768     if (FoldedVOp.getNode()) return FoldedVOp;
1769
1770     // fold (sub x, 0) -> x, vector edition
1771     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1772       return N0;
1773   }
1774
1775   // fold (sub x, x) -> 0
1776   // FIXME: Refactor this and xor and other similar operations together.
1777   if (N0 == N1)
1778     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1779   // fold (sub c1, c2) -> c1-c2
1780   if (N0C && N1C)
1781     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1782   // fold (sub x, c) -> (add x, -c)
1783   if (N1C)
1784     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1785                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1786   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1787   if (N0C && N0C->isAllOnesValue())
1788     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1789   // fold A-(A-B) -> B
1790   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1791     return N1.getOperand(1);
1792   // fold (A+B)-A -> B
1793   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1794     return N0.getOperand(1);
1795   // fold (A+B)-B -> A
1796   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1797     return N0.getOperand(0);
1798   // fold C2-(A+C1) -> (C2-C1)-A
1799   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1800     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1801                                    VT);
1802     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1803                        N1.getOperand(0));
1804   }
1805   // fold ((A+(B+or-C))-B) -> A+or-C
1806   if (N0.getOpcode() == ISD::ADD &&
1807       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1808        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1809       N0.getOperand(1).getOperand(0) == N1)
1810     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1811                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1812   // fold ((A+(C+B))-B) -> A+C
1813   if (N0.getOpcode() == ISD::ADD &&
1814       N0.getOperand(1).getOpcode() == ISD::ADD &&
1815       N0.getOperand(1).getOperand(1) == N1)
1816     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1817                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1818   // fold ((A-(B-C))-C) -> A-B
1819   if (N0.getOpcode() == ISD::SUB &&
1820       N0.getOperand(1).getOpcode() == ISD::SUB &&
1821       N0.getOperand(1).getOperand(1) == N1)
1822     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1823                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1824
1825   // If either operand of a sub is undef, the result is undef
1826   if (N0.getOpcode() == ISD::UNDEF)
1827     return N0;
1828   if (N1.getOpcode() == ISD::UNDEF)
1829     return N1;
1830
1831   // If the relocation model supports it, consider symbol offsets.
1832   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1833     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1834       // fold (sub Sym, c) -> Sym-c
1835       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1836         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1837                                     GA->getOffset() -
1838                                       (uint64_t)N1C->getSExtValue());
1839       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1840       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1841         if (GA->getGlobal() == GB->getGlobal())
1842           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1843                                  VT);
1844     }
1845
1846   return SDValue();
1847 }
1848
1849 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1850   SDValue N0 = N->getOperand(0);
1851   SDValue N1 = N->getOperand(1);
1852   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1853   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1854   EVT VT = N0.getValueType();
1855
1856   // If the flag result is dead, turn this into an SUB.
1857   if (!N->hasAnyUseOfValue(1))
1858     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1859                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1860                                  MVT::Glue));
1861
1862   // fold (subc x, x) -> 0 + no borrow
1863   if (N0 == N1)
1864     return CombineTo(N, DAG.getConstant(0, VT),
1865                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1866                                  MVT::Glue));
1867
1868   // fold (subc x, 0) -> x + no borrow
1869   if (N1C && N1C->isNullValue())
1870     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1871                                         MVT::Glue));
1872
1873   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1874   if (N0C && N0C->isAllOnesValue())
1875     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1876                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1877                                  MVT::Glue));
1878
1879   return SDValue();
1880 }
1881
1882 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1883   SDValue N0 = N->getOperand(0);
1884   SDValue N1 = N->getOperand(1);
1885   SDValue CarryIn = N->getOperand(2);
1886
1887   // fold (sube x, y, false) -> (subc x, y)
1888   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1889     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1890
1891   return SDValue();
1892 }
1893
1894 SDValue DAGCombiner::visitMUL(SDNode *N) {
1895   SDValue N0 = N->getOperand(0);
1896   SDValue N1 = N->getOperand(1);
1897   EVT VT = N0.getValueType();
1898
1899   // fold (mul x, undef) -> 0
1900   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1901     return DAG.getConstant(0, VT);
1902
1903   bool N0IsConst = false;
1904   bool N1IsConst = false;
1905   APInt ConstValue0, ConstValue1;
1906   // fold vector ops
1907   if (VT.isVector()) {
1908     SDValue FoldedVOp = SimplifyVBinOp(N);
1909     if (FoldedVOp.getNode()) return FoldedVOp;
1910
1911     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1912     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1913   } else {
1914     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1915     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1916                             : APInt();
1917     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1918     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1919                             : APInt();
1920   }
1921
1922   // fold (mul c1, c2) -> c1*c2
1923   if (N0IsConst && N1IsConst)
1924     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1925
1926   // canonicalize constant to RHS
1927   if (N0IsConst && !N1IsConst)
1928     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1929   // fold (mul x, 0) -> 0
1930   if (N1IsConst && ConstValue1 == 0)
1931     return N1;
1932   // We require a splat of the entire scalar bit width for non-contiguous
1933   // bit patterns.
1934   bool IsFullSplat =
1935     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1936   // fold (mul x, 1) -> x
1937   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1938     return N0;
1939   // fold (mul x, -1) -> 0-x
1940   if (N1IsConst && ConstValue1.isAllOnesValue())
1941     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1942                        DAG.getConstant(0, VT), N0);
1943   // fold (mul x, (1 << c)) -> x << c
1944   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1945     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1946                        DAG.getConstant(ConstValue1.logBase2(),
1947                                        getShiftAmountTy(N0.getValueType())));
1948   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1949   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1950     unsigned Log2Val = (-ConstValue1).logBase2();
1951     // FIXME: If the input is something that is easily negated (e.g. a
1952     // single-use add), we should put the negate there.
1953     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1954                        DAG.getConstant(0, VT),
1955                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1956                             DAG.getConstant(Log2Val,
1957                                       getShiftAmountTy(N0.getValueType()))));
1958   }
1959
1960   APInt Val;
1961   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1962   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1963       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1964                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1965     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1966                              N1, N0.getOperand(1));
1967     AddToWorklist(C3.getNode());
1968     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1969                        N0.getOperand(0), C3);
1970   }
1971
1972   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1973   // use.
1974   {
1975     SDValue Sh(nullptr,0), Y(nullptr,0);
1976     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1977     if (N0.getOpcode() == ISD::SHL &&
1978         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1979                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1980         N0.getNode()->hasOneUse()) {
1981       Sh = N0; Y = N1;
1982     } else if (N1.getOpcode() == ISD::SHL &&
1983                isa<ConstantSDNode>(N1.getOperand(1)) &&
1984                N1.getNode()->hasOneUse()) {
1985       Sh = N1; Y = N0;
1986     }
1987
1988     if (Sh.getNode()) {
1989       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1990                                 Sh.getOperand(0), Y);
1991       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1992                          Mul, Sh.getOperand(1));
1993     }
1994   }
1995
1996   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1997   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1998       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1999                      isa<ConstantSDNode>(N0.getOperand(1))))
2000     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2001                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2002                                    N0.getOperand(0), N1),
2003                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2004                                    N0.getOperand(1), N1));
2005
2006   // reassociate mul
2007   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2008   if (RMUL.getNode())
2009     return RMUL;
2010
2011   return SDValue();
2012 }
2013
2014 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2015   SDValue N0 = N->getOperand(0);
2016   SDValue N1 = N->getOperand(1);
2017   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2018   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2019   EVT VT = N->getValueType(0);
2020
2021   // fold vector ops
2022   if (VT.isVector()) {
2023     SDValue FoldedVOp = SimplifyVBinOp(N);
2024     if (FoldedVOp.getNode()) return FoldedVOp;
2025   }
2026
2027   // fold (sdiv c1, c2) -> c1/c2
2028   if (N0C && N1C && !N1C->isNullValue())
2029     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2030   // fold (sdiv X, 1) -> X
2031   if (N1C && N1C->getAPIntValue() == 1LL)
2032     return N0;
2033   // fold (sdiv X, -1) -> 0-X
2034   if (N1C && N1C->isAllOnesValue())
2035     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2036                        DAG.getConstant(0, VT), N0);
2037   // If we know the sign bits of both operands are zero, strength reduce to a
2038   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2039   if (!VT.isVector()) {
2040     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2041       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2042                          N0, N1);
2043   }
2044
2045   // fold (sdiv X, pow2) -> simple ops after legalize
2046   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2047                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2048     // If dividing by powers of two is cheap, then don't perform the following
2049     // fold.
2050     if (TLI.isPow2DivCheap())
2051       return SDValue();
2052
2053     // Target-specific implementation of sdiv x, pow2.
2054     SDValue Res = BuildSDIVPow2(N);
2055     if (Res.getNode())
2056       return Res;
2057
2058     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2059
2060     // Splat the sign bit into the register
2061     SDValue SGN =
2062         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2063                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2064                                     getShiftAmountTy(N0.getValueType())));
2065     AddToWorklist(SGN.getNode());
2066
2067     // Add (N0 < 0) ? abs2 - 1 : 0;
2068     SDValue SRL =
2069         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2070                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2071                                     getShiftAmountTy(SGN.getValueType())));
2072     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2073     AddToWorklist(SRL.getNode());
2074     AddToWorklist(ADD.getNode());    // Divide by pow2
2075     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2076                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2077
2078     // If we're dividing by a positive value, we're done.  Otherwise, we must
2079     // negate the result.
2080     if (N1C->getAPIntValue().isNonNegative())
2081       return SRA;
2082
2083     AddToWorklist(SRA.getNode());
2084     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2085   }
2086
2087   // if integer divide is expensive and we satisfy the requirements, emit an
2088   // alternate sequence.
2089   if (N1C && !TLI.isIntDivCheap()) {
2090     SDValue Op = BuildSDIV(N);
2091     if (Op.getNode()) return Op;
2092   }
2093
2094   // undef / X -> 0
2095   if (N0.getOpcode() == ISD::UNDEF)
2096     return DAG.getConstant(0, VT);
2097   // X / undef -> undef
2098   if (N1.getOpcode() == ISD::UNDEF)
2099     return N1;
2100
2101   return SDValue();
2102 }
2103
2104 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2105   SDValue N0 = N->getOperand(0);
2106   SDValue N1 = N->getOperand(1);
2107   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2108   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2109   EVT VT = N->getValueType(0);
2110
2111   // fold vector ops
2112   if (VT.isVector()) {
2113     SDValue FoldedVOp = SimplifyVBinOp(N);
2114     if (FoldedVOp.getNode()) return FoldedVOp;
2115   }
2116
2117   // fold (udiv c1, c2) -> c1/c2
2118   if (N0C && N1C && !N1C->isNullValue())
2119     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2120   // fold (udiv x, (1 << c)) -> x >>u c
2121   if (N1C && N1C->getAPIntValue().isPowerOf2())
2122     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2123                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2124                                        getShiftAmountTy(N0.getValueType())));
2125   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2126   if (N1.getOpcode() == ISD::SHL) {
2127     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2128       if (SHC->getAPIntValue().isPowerOf2()) {
2129         EVT ADDVT = N1.getOperand(1).getValueType();
2130         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2131                                   N1.getOperand(1),
2132                                   DAG.getConstant(SHC->getAPIntValue()
2133                                                                   .logBase2(),
2134                                                   ADDVT));
2135         AddToWorklist(Add.getNode());
2136         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2137       }
2138     }
2139   }
2140   // fold (udiv x, c) -> alternate
2141   if (N1C && !TLI.isIntDivCheap()) {
2142     SDValue Op = BuildUDIV(N);
2143     if (Op.getNode()) return Op;
2144   }
2145
2146   // undef / X -> 0
2147   if (N0.getOpcode() == ISD::UNDEF)
2148     return DAG.getConstant(0, VT);
2149   // X / undef -> undef
2150   if (N1.getOpcode() == ISD::UNDEF)
2151     return N1;
2152
2153   return SDValue();
2154 }
2155
2156 SDValue DAGCombiner::visitSREM(SDNode *N) {
2157   SDValue N0 = N->getOperand(0);
2158   SDValue N1 = N->getOperand(1);
2159   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2160   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2161   EVT VT = N->getValueType(0);
2162
2163   // fold (srem c1, c2) -> c1%c2
2164   if (N0C && N1C && !N1C->isNullValue())
2165     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2166   // If we know the sign bits of both operands are zero, strength reduce to a
2167   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2168   if (!VT.isVector()) {
2169     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2170       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2171   }
2172
2173   // If X/C can be simplified by the division-by-constant logic, lower
2174   // X%C to the equivalent of X-X/C*C.
2175   if (N1C && !N1C->isNullValue()) {
2176     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2177     AddToWorklist(Div.getNode());
2178     SDValue OptimizedDiv = combine(Div.getNode());
2179     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2180       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2181                                 OptimizedDiv, N1);
2182       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2183       AddToWorklist(Mul.getNode());
2184       return Sub;
2185     }
2186   }
2187
2188   // undef % X -> 0
2189   if (N0.getOpcode() == ISD::UNDEF)
2190     return DAG.getConstant(0, VT);
2191   // X % undef -> undef
2192   if (N1.getOpcode() == ISD::UNDEF)
2193     return N1;
2194
2195   return SDValue();
2196 }
2197
2198 SDValue DAGCombiner::visitUREM(SDNode *N) {
2199   SDValue N0 = N->getOperand(0);
2200   SDValue N1 = N->getOperand(1);
2201   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2202   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2203   EVT VT = N->getValueType(0);
2204
2205   // fold (urem c1, c2) -> c1%c2
2206   if (N0C && N1C && !N1C->isNullValue())
2207     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2208   // fold (urem x, pow2) -> (and x, pow2-1)
2209   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2210     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2211                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2212   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2213   if (N1.getOpcode() == ISD::SHL) {
2214     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2215       if (SHC->getAPIntValue().isPowerOf2()) {
2216         SDValue Add =
2217           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2218                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2219                                  VT));
2220         AddToWorklist(Add.getNode());
2221         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2222       }
2223     }
2224   }
2225
2226   // If X/C can be simplified by the division-by-constant logic, lower
2227   // X%C to the equivalent of X-X/C*C.
2228   if (N1C && !N1C->isNullValue()) {
2229     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2230     AddToWorklist(Div.getNode());
2231     SDValue OptimizedDiv = combine(Div.getNode());
2232     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2233       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2234                                 OptimizedDiv, N1);
2235       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2236       AddToWorklist(Mul.getNode());
2237       return Sub;
2238     }
2239   }
2240
2241   // undef % X -> 0
2242   if (N0.getOpcode() == ISD::UNDEF)
2243     return DAG.getConstant(0, VT);
2244   // X % undef -> undef
2245   if (N1.getOpcode() == ISD::UNDEF)
2246     return N1;
2247
2248   return SDValue();
2249 }
2250
2251 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2252   SDValue N0 = N->getOperand(0);
2253   SDValue N1 = N->getOperand(1);
2254   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2255   EVT VT = N->getValueType(0);
2256   SDLoc DL(N);
2257
2258   // fold (mulhs x, 0) -> 0
2259   if (N1C && N1C->isNullValue())
2260     return N1;
2261   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2262   if (N1C && N1C->getAPIntValue() == 1)
2263     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2264                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2265                                        getShiftAmountTy(N0.getValueType())));
2266   // fold (mulhs x, undef) -> 0
2267   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2268     return DAG.getConstant(0, VT);
2269
2270   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2271   // plus a shift.
2272   if (VT.isSimple() && !VT.isVector()) {
2273     MVT Simple = VT.getSimpleVT();
2274     unsigned SimpleSize = Simple.getSizeInBits();
2275     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2276     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2277       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2278       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2279       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2280       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2281             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2282       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2283     }
2284   }
2285
2286   return SDValue();
2287 }
2288
2289 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2290   SDValue N0 = N->getOperand(0);
2291   SDValue N1 = N->getOperand(1);
2292   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2293   EVT VT = N->getValueType(0);
2294   SDLoc DL(N);
2295
2296   // fold (mulhu x, 0) -> 0
2297   if (N1C && N1C->isNullValue())
2298     return N1;
2299   // fold (mulhu x, 1) -> 0
2300   if (N1C && N1C->getAPIntValue() == 1)
2301     return DAG.getConstant(0, N0.getValueType());
2302   // fold (mulhu x, undef) -> 0
2303   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2304     return DAG.getConstant(0, VT);
2305
2306   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2307   // plus a shift.
2308   if (VT.isSimple() && !VT.isVector()) {
2309     MVT Simple = VT.getSimpleVT();
2310     unsigned SimpleSize = Simple.getSizeInBits();
2311     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2312     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2313       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2314       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2315       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2316       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2317             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2318       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2319     }
2320   }
2321
2322   return SDValue();
2323 }
2324
2325 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2326 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2327 /// that are being performed. Return true if a simplification was made.
2328 ///
2329 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2330                                                 unsigned HiOp) {
2331   // If the high half is not needed, just compute the low half.
2332   bool HiExists = N->hasAnyUseOfValue(1);
2333   if (!HiExists &&
2334       (!LegalOperations ||
2335        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2336     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2337                               ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2338     return CombineTo(N, Res, Res);
2339   }
2340
2341   // If the low half is not needed, just compute the high half.
2342   bool LoExists = N->hasAnyUseOfValue(0);
2343   if (!LoExists &&
2344       (!LegalOperations ||
2345        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2346     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2347                               ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2348     return CombineTo(N, Res, Res);
2349   }
2350
2351   // If both halves are used, return as it is.
2352   if (LoExists && HiExists)
2353     return SDValue();
2354
2355   // If the two computed results can be simplified separately, separate them.
2356   if (LoExists) {
2357     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2358                              ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2359     AddToWorklist(Lo.getNode());
2360     SDValue LoOpt = combine(Lo.getNode());
2361     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2362         (!LegalOperations ||
2363          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2364       return CombineTo(N, LoOpt, LoOpt);
2365   }
2366
2367   if (HiExists) {
2368     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2369                              ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2370     AddToWorklist(Hi.getNode());
2371     SDValue HiOpt = combine(Hi.getNode());
2372     if (HiOpt.getNode() && HiOpt != Hi &&
2373         (!LegalOperations ||
2374          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2375       return CombineTo(N, HiOpt, HiOpt);
2376   }
2377
2378   return SDValue();
2379 }
2380
2381 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2382   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2383   if (Res.getNode()) return Res;
2384
2385   EVT VT = N->getValueType(0);
2386   SDLoc DL(N);
2387
2388   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2389   // plus a shift.
2390   if (VT.isSimple() && !VT.isVector()) {
2391     MVT Simple = VT.getSimpleVT();
2392     unsigned SimpleSize = Simple.getSizeInBits();
2393     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2394     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2395       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2396       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2397       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2398       // Compute the high part as N1.
2399       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2400             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2401       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2402       // Compute the low part as N0.
2403       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2404       return CombineTo(N, Lo, Hi);
2405     }
2406   }
2407
2408   return SDValue();
2409 }
2410
2411 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2412   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2413   if (Res.getNode()) return Res;
2414
2415   EVT VT = N->getValueType(0);
2416   SDLoc DL(N);
2417
2418   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2419   // plus a shift.
2420   if (VT.isSimple() && !VT.isVector()) {
2421     MVT Simple = VT.getSimpleVT();
2422     unsigned SimpleSize = Simple.getSizeInBits();
2423     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2424     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2425       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2426       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2427       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2428       // Compute the high part as N1.
2429       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2430             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2431       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2432       // Compute the low part as N0.
2433       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2434       return CombineTo(N, Lo, Hi);
2435     }
2436   }
2437
2438   return SDValue();
2439 }
2440
2441 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2442   // (smulo x, 2) -> (saddo x, x)
2443   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2444     if (C2->getAPIntValue() == 2)
2445       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2446                          N->getOperand(0), N->getOperand(0));
2447
2448   return SDValue();
2449 }
2450
2451 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2452   // (umulo x, 2) -> (uaddo x, x)
2453   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2454     if (C2->getAPIntValue() == 2)
2455       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2456                          N->getOperand(0), N->getOperand(0));
2457
2458   return SDValue();
2459 }
2460
2461 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2462   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2463   if (Res.getNode()) return Res;
2464
2465   return SDValue();
2466 }
2467
2468 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2469   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2470   if (Res.getNode()) return Res;
2471
2472   return SDValue();
2473 }
2474
2475 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2476 /// two operands of the same opcode, try to simplify it.
2477 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2478   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2479   EVT VT = N0.getValueType();
2480   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2481
2482   // Bail early if none of these transforms apply.
2483   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2484
2485   // For each of OP in AND/OR/XOR:
2486   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2487   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2488   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2489   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2490   //
2491   // do not sink logical op inside of a vector extend, since it may combine
2492   // into a vsetcc.
2493   EVT Op0VT = N0.getOperand(0).getValueType();
2494   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2495        N0.getOpcode() == ISD::SIGN_EXTEND ||
2496        // Avoid infinite looping with PromoteIntBinOp.
2497        (N0.getOpcode() == ISD::ANY_EXTEND &&
2498         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2499        (N0.getOpcode() == ISD::TRUNCATE &&
2500         (!TLI.isZExtFree(VT, Op0VT) ||
2501          !TLI.isTruncateFree(Op0VT, VT)) &&
2502         TLI.isTypeLegal(Op0VT))) &&
2503       !VT.isVector() &&
2504       Op0VT == N1.getOperand(0).getValueType() &&
2505       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2506     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2507                                  N0.getOperand(0).getValueType(),
2508                                  N0.getOperand(0), N1.getOperand(0));
2509     AddToWorklist(ORNode.getNode());
2510     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2511   }
2512
2513   // For each of OP in SHL/SRL/SRA/AND...
2514   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2515   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2516   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2517   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2518        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2519       N0.getOperand(1) == N1.getOperand(1)) {
2520     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2521                                  N0.getOperand(0).getValueType(),
2522                                  N0.getOperand(0), N1.getOperand(0));
2523     AddToWorklist(ORNode.getNode());
2524     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2525                        ORNode, N0.getOperand(1));
2526   }
2527
2528   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2529   // Only perform this optimization after type legalization and before
2530   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2531   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2532   // we don't want to undo this promotion.
2533   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2534   // on scalars.
2535   if ((N0.getOpcode() == ISD::BITCAST ||
2536        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2537       Level == AfterLegalizeTypes) {
2538     SDValue In0 = N0.getOperand(0);
2539     SDValue In1 = N1.getOperand(0);
2540     EVT In0Ty = In0.getValueType();
2541     EVT In1Ty = In1.getValueType();
2542     SDLoc DL(N);
2543     // If both incoming values are integers, and the original types are the
2544     // same.
2545     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2546       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2547       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2548       AddToWorklist(Op.getNode());
2549       return BC;
2550     }
2551   }
2552
2553   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2554   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2555   // If both shuffles use the same mask, and both shuffle within a single
2556   // vector, then it is worthwhile to move the swizzle after the operation.
2557   // The type-legalizer generates this pattern when loading illegal
2558   // vector types from memory. In many cases this allows additional shuffle
2559   // optimizations.
2560   // There are other cases where moving the shuffle after the xor/and/or
2561   // is profitable even if shuffles don't perform a swizzle.
2562   // If both shuffles use the same mask, and both shuffles have the same first
2563   // or second operand, then it might still be profitable to move the shuffle
2564   // after the xor/and/or operation.
2565   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2566     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2567     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2568
2569     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2570            "Inputs to shuffles are not the same type");
2571
2572     // Check that both shuffles use the same mask. The masks are known to be of
2573     // the same length because the result vector type is the same.
2574     // Check also that shuffles have only one use to avoid introducing extra
2575     // instructions.
2576     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2577         SVN0->getMask().equals(SVN1->getMask())) {
2578       SDValue ShOp = N0->getOperand(1);
2579
2580       // Don't try to fold this node if it requires introducing a
2581       // build vector of all zeros that might be illegal at this stage.
2582       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2583         if (!LegalTypes)
2584           ShOp = DAG.getConstant(0, VT);
2585         else
2586           ShOp = SDValue();
2587       }
2588
2589       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2590       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2591       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2592       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2593         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2594                                       N0->getOperand(0), N1->getOperand(0));
2595         AddToWorklist(NewNode.getNode());
2596         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2597                                     &SVN0->getMask()[0]);
2598       }
2599
2600       // Don't try to fold this node if it requires introducing a
2601       // build vector of all zeros that might be illegal at this stage.
2602       ShOp = N0->getOperand(0);
2603       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2604         if (!LegalTypes)
2605           ShOp = DAG.getConstant(0, VT);
2606         else
2607           ShOp = SDValue();
2608       }
2609
2610       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2611       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2612       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2613       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2614         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2615                                       N0->getOperand(1), N1->getOperand(1));
2616         AddToWorklist(NewNode.getNode());
2617         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2618                                     &SVN0->getMask()[0]);
2619       }
2620     }
2621   }
2622
2623   return SDValue();
2624 }
2625
2626 SDValue DAGCombiner::visitAND(SDNode *N) {
2627   SDValue N0 = N->getOperand(0);
2628   SDValue N1 = N->getOperand(1);
2629   SDValue LL, LR, RL, RR, CC0, CC1;
2630   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2631   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2632   EVT VT = N1.getValueType();
2633   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2634
2635   // fold vector ops
2636   if (VT.isVector()) {
2637     SDValue FoldedVOp = SimplifyVBinOp(N);
2638     if (FoldedVOp.getNode()) return FoldedVOp;
2639
2640     // fold (and x, 0) -> 0, vector edition
2641     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2642       return N0;
2643     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2644       return N1;
2645
2646     // fold (and x, -1) -> x, vector edition
2647     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2648       return N1;
2649     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2650       return N0;
2651   }
2652
2653   // fold (and x, undef) -> 0
2654   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2655     return DAG.getConstant(0, VT);
2656   // fold (and c1, c2) -> c1&c2
2657   if (N0C && N1C)
2658     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2659   // canonicalize constant to RHS
2660   if (N0C && !N1C)
2661     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2662   // fold (and x, -1) -> x
2663   if (N1C && N1C->isAllOnesValue())
2664     return N0;
2665   // if (and x, c) is known to be zero, return 0
2666   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2667                                    APInt::getAllOnesValue(BitWidth)))
2668     return DAG.getConstant(0, VT);
2669   // reassociate and
2670   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2671   if (RAND.getNode())
2672     return RAND;
2673   // fold (and (or x, C), D) -> D if (C & D) == D
2674   if (N1C && N0.getOpcode() == ISD::OR)
2675     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2676       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2677         return N1;
2678   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2679   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2680     SDValue N0Op0 = N0.getOperand(0);
2681     APInt Mask = ~N1C->getAPIntValue();
2682     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2683     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2684       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2685                                  N0.getValueType(), N0Op0);
2686
2687       // Replace uses of the AND with uses of the Zero extend node.
2688       CombineTo(N, Zext);
2689
2690       // We actually want to replace all uses of the any_extend with the
2691       // zero_extend, to avoid duplicating things.  This will later cause this
2692       // AND to be folded.
2693       CombineTo(N0.getNode(), Zext);
2694       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2695     }
2696   }
2697   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2698   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2699   // already be zero by virtue of the width of the base type of the load.
2700   //
2701   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2702   // more cases.
2703   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2704        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2705       N0.getOpcode() == ISD::LOAD) {
2706     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2707                                          N0 : N0.getOperand(0) );
2708
2709     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2710     // This can be a pure constant or a vector splat, in which case we treat the
2711     // vector as a scalar and use the splat value.
2712     APInt Constant = APInt::getNullValue(1);
2713     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2714       Constant = C->getAPIntValue();
2715     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2716       APInt SplatValue, SplatUndef;
2717       unsigned SplatBitSize;
2718       bool HasAnyUndefs;
2719       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2720                                              SplatBitSize, HasAnyUndefs);
2721       if (IsSplat) {
2722         // Undef bits can contribute to a possible optimisation if set, so
2723         // set them.
2724         SplatValue |= SplatUndef;
2725
2726         // The splat value may be something like "0x00FFFFFF", which means 0 for
2727         // the first vector value and FF for the rest, repeating. We need a mask
2728         // that will apply equally to all members of the vector, so AND all the
2729         // lanes of the constant together.
2730         EVT VT = Vector->getValueType(0);
2731         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2732
2733         // If the splat value has been compressed to a bitlength lower
2734         // than the size of the vector lane, we need to re-expand it to
2735         // the lane size.
2736         if (BitWidth > SplatBitSize)
2737           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2738                SplatBitSize < BitWidth;
2739                SplatBitSize = SplatBitSize * 2)
2740             SplatValue |= SplatValue.shl(SplatBitSize);
2741
2742         Constant = APInt::getAllOnesValue(BitWidth);
2743         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2744           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2745       }
2746     }
2747
2748     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2749     // actually legal and isn't going to get expanded, else this is a false
2750     // optimisation.
2751     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2752                                                     Load->getMemoryVT());
2753
2754     // Resize the constant to the same size as the original memory access before
2755     // extension. If it is still the AllOnesValue then this AND is completely
2756     // unneeded.
2757     Constant =
2758       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2759
2760     bool B;
2761     switch (Load->getExtensionType()) {
2762     default: B = false; break;
2763     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2764     case ISD::ZEXTLOAD:
2765     case ISD::NON_EXTLOAD: B = true; break;
2766     }
2767
2768     if (B && Constant.isAllOnesValue()) {
2769       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2770       // preserve semantics once we get rid of the AND.
2771       SDValue NewLoad(Load, 0);
2772       if (Load->getExtensionType() == ISD::EXTLOAD) {
2773         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2774                               Load->getValueType(0), SDLoc(Load),
2775                               Load->getChain(), Load->getBasePtr(),
2776                               Load->getOffset(), Load->getMemoryVT(),
2777                               Load->getMemOperand());
2778         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2779         if (Load->getNumValues() == 3) {
2780           // PRE/POST_INC loads have 3 values.
2781           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2782                            NewLoad.getValue(2) };
2783           CombineTo(Load, To, 3, true);
2784         } else {
2785           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2786         }
2787       }
2788
2789       // Fold the AND away, taking care not to fold to the old load node if we
2790       // replaced it.
2791       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2792
2793       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2794     }
2795   }
2796   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2797   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2798     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2799     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2800
2801     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2802         LL.getValueType().isInteger()) {
2803       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2804       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2805         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2806                                      LR.getValueType(), LL, RL);
2807         AddToWorklist(ORNode.getNode());
2808         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2809       }
2810       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2811       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2812         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2813                                       LR.getValueType(), LL, RL);
2814         AddToWorklist(ANDNode.getNode());
2815         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2816       }
2817       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2818       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2819         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2820                                      LR.getValueType(), LL, RL);
2821         AddToWorklist(ORNode.getNode());
2822         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2823       }
2824     }
2825     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2826     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2827         Op0 == Op1 && LL.getValueType().isInteger() &&
2828       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2829                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2830                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2831                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2832       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2833                                     LL, DAG.getConstant(1, LL.getValueType()));
2834       AddToWorklist(ADDNode.getNode());
2835       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2836                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2837     }
2838     // canonicalize equivalent to ll == rl
2839     if (LL == RR && LR == RL) {
2840       Op1 = ISD::getSetCCSwappedOperands(Op1);
2841       std::swap(RL, RR);
2842     }
2843     if (LL == RL && LR == RR) {
2844       bool isInteger = LL.getValueType().isInteger();
2845       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2846       if (Result != ISD::SETCC_INVALID &&
2847           (!LegalOperations ||
2848            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2849             TLI.isOperationLegal(ISD::SETCC,
2850                             getSetCCResultType(N0.getSimpleValueType())))))
2851         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2852                             LL, LR, Result);
2853     }
2854   }
2855
2856   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2857   if (N0.getOpcode() == N1.getOpcode()) {
2858     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2859     if (Tmp.getNode()) return Tmp;
2860   }
2861
2862   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2863   // fold (and (sra)) -> (and (srl)) when possible.
2864   if (!VT.isVector() &&
2865       SimplifyDemandedBits(SDValue(N, 0)))
2866     return SDValue(N, 0);
2867
2868   // fold (zext_inreg (extload x)) -> (zextload x)
2869   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2870     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2871     EVT MemVT = LN0->getMemoryVT();
2872     // If we zero all the possible extended bits, then we can turn this into
2873     // a zextload if we are running before legalize or the operation is legal.
2874     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2875     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2876                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2877         ((!LegalOperations && !LN0->isVolatile()) ||
2878          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2879       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2880                                        LN0->getChain(), LN0->getBasePtr(),
2881                                        MemVT, LN0->getMemOperand());
2882       AddToWorklist(N);
2883       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2884       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2885     }
2886   }
2887   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2888   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2889       N0.hasOneUse()) {
2890     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2891     EVT MemVT = LN0->getMemoryVT();
2892     // If we zero all the possible extended bits, then we can turn this into
2893     // a zextload if we are running before legalize or the operation is legal.
2894     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2895     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2896                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2897         ((!LegalOperations && !LN0->isVolatile()) ||
2898          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2899       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2900                                        LN0->getChain(), LN0->getBasePtr(),
2901                                        MemVT, LN0->getMemOperand());
2902       AddToWorklist(N);
2903       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2904       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2905     }
2906   }
2907
2908   // fold (and (load x), 255) -> (zextload x, i8)
2909   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2910   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2911   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2912               (N0.getOpcode() == ISD::ANY_EXTEND &&
2913                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2914     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2915     LoadSDNode *LN0 = HasAnyExt
2916       ? cast<LoadSDNode>(N0.getOperand(0))
2917       : cast<LoadSDNode>(N0);
2918     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2919         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2920       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2921       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2922         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2923         EVT LoadedVT = LN0->getMemoryVT();
2924
2925         if (ExtVT == LoadedVT &&
2926             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2927           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2928
2929           SDValue NewLoad =
2930             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2931                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2932                            LN0->getMemOperand());
2933           AddToWorklist(N);
2934           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2935           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2936         }
2937
2938         // Do not change the width of a volatile load.
2939         // Do not generate loads of non-round integer types since these can
2940         // be expensive (and would be wrong if the type is not byte sized).
2941         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2942             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2943           EVT PtrType = LN0->getOperand(1).getValueType();
2944
2945           unsigned Alignment = LN0->getAlignment();
2946           SDValue NewPtr = LN0->getBasePtr();
2947
2948           // For big endian targets, we need to add an offset to the pointer
2949           // to load the correct bytes.  For little endian systems, we merely
2950           // need to read fewer bytes from the same pointer.
2951           if (TLI.isBigEndian()) {
2952             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2953             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2954             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2955             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2956                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2957             Alignment = MinAlign(Alignment, PtrOff);
2958           }
2959
2960           AddToWorklist(NewPtr.getNode());
2961
2962           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2963           SDValue Load =
2964             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2965                            LN0->getChain(), NewPtr,
2966                            LN0->getPointerInfo(),
2967                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2968                            Alignment, LN0->getAAInfo());
2969           AddToWorklist(N);
2970           CombineTo(LN0, Load, Load.getValue(1));
2971           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2972         }
2973       }
2974     }
2975   }
2976
2977   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2978       VT.getSizeInBits() <= 64) {
2979     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2980       APInt ADDC = ADDI->getAPIntValue();
2981       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2982         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2983         // immediate for an add, but it is legal if its top c2 bits are set,
2984         // transform the ADD so the immediate doesn't need to be materialized
2985         // in a register.
2986         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2987           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2988                                              SRLI->getZExtValue());
2989           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2990             ADDC |= Mask;
2991             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2992               SDValue NewAdd =
2993                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2994                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2995               CombineTo(N0.getNode(), NewAdd);
2996               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2997             }
2998           }
2999         }
3000       }
3001     }
3002   }
3003
3004   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3005   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3006     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3007                                        N0.getOperand(1), false);
3008     if (BSwap.getNode())
3009       return BSwap;
3010   }
3011
3012   return SDValue();
3013 }
3014
3015 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
3016 ///
3017 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3018                                         bool DemandHighBits) {
3019   if (!LegalOperations)
3020     return SDValue();
3021
3022   EVT VT = N->getValueType(0);
3023   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3024     return SDValue();
3025   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3026     return SDValue();
3027
3028   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3029   bool LookPassAnd0 = false;
3030   bool LookPassAnd1 = false;
3031   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3032       std::swap(N0, N1);
3033   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3034       std::swap(N0, N1);
3035   if (N0.getOpcode() == ISD::AND) {
3036     if (!N0.getNode()->hasOneUse())
3037       return SDValue();
3038     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3039     if (!N01C || N01C->getZExtValue() != 0xFF00)
3040       return SDValue();
3041     N0 = N0.getOperand(0);
3042     LookPassAnd0 = true;
3043   }
3044
3045   if (N1.getOpcode() == ISD::AND) {
3046     if (!N1.getNode()->hasOneUse())
3047       return SDValue();
3048     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3049     if (!N11C || N11C->getZExtValue() != 0xFF)
3050       return SDValue();
3051     N1 = N1.getOperand(0);
3052     LookPassAnd1 = true;
3053   }
3054
3055   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3056     std::swap(N0, N1);
3057   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3058     return SDValue();
3059   if (!N0.getNode()->hasOneUse() ||
3060       !N1.getNode()->hasOneUse())
3061     return SDValue();
3062
3063   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3064   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3065   if (!N01C || !N11C)
3066     return SDValue();
3067   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3068     return SDValue();
3069
3070   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3071   SDValue N00 = N0->getOperand(0);
3072   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3073     if (!N00.getNode()->hasOneUse())
3074       return SDValue();
3075     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3076     if (!N001C || N001C->getZExtValue() != 0xFF)
3077       return SDValue();
3078     N00 = N00.getOperand(0);
3079     LookPassAnd0 = true;
3080   }
3081
3082   SDValue N10 = N1->getOperand(0);
3083   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3084     if (!N10.getNode()->hasOneUse())
3085       return SDValue();
3086     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3087     if (!N101C || N101C->getZExtValue() != 0xFF00)
3088       return SDValue();
3089     N10 = N10.getOperand(0);
3090     LookPassAnd1 = true;
3091   }
3092
3093   if (N00 != N10)
3094     return SDValue();
3095
3096   // Make sure everything beyond the low halfword gets set to zero since the SRL
3097   // 16 will clear the top bits.
3098   unsigned OpSizeInBits = VT.getSizeInBits();
3099   if (DemandHighBits && OpSizeInBits > 16) {
3100     // If the left-shift isn't masked out then the only way this is a bswap is
3101     // if all bits beyond the low 8 are 0. In that case the entire pattern
3102     // reduces to a left shift anyway: leave it for other parts of the combiner.
3103     if (!LookPassAnd0)
3104       return SDValue();
3105
3106     // However, if the right shift isn't masked out then it might be because
3107     // it's not needed. See if we can spot that too.
3108     if (!LookPassAnd1 &&
3109         !DAG.MaskedValueIsZero(
3110             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3111       return SDValue();
3112   }
3113
3114   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3115   if (OpSizeInBits > 16)
3116     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3117                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3118   return Res;
3119 }
3120
3121 /// isBSwapHWordElement - Return true if the specified node is an element
3122 /// that makes up a 32-bit packed halfword byteswap. i.e.
3123 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3124 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3125   if (!N.getNode()->hasOneUse())
3126     return false;
3127
3128   unsigned Opc = N.getOpcode();
3129   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3130     return false;
3131
3132   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3133   if (!N1C)
3134     return false;
3135
3136   unsigned Num;
3137   switch (N1C->getZExtValue()) {
3138   default:
3139     return false;
3140   case 0xFF:       Num = 0; break;
3141   case 0xFF00:     Num = 1; break;
3142   case 0xFF0000:   Num = 2; break;
3143   case 0xFF000000: Num = 3; break;
3144   }
3145
3146   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3147   SDValue N0 = N.getOperand(0);
3148   if (Opc == ISD::AND) {
3149     if (Num == 0 || Num == 2) {
3150       // (x >> 8) & 0xff
3151       // (x >> 8) & 0xff0000
3152       if (N0.getOpcode() != ISD::SRL)
3153         return false;
3154       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3155       if (!C || C->getZExtValue() != 8)
3156         return false;
3157     } else {
3158       // (x << 8) & 0xff00
3159       // (x << 8) & 0xff000000
3160       if (N0.getOpcode() != ISD::SHL)
3161         return false;
3162       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3163       if (!C || C->getZExtValue() != 8)
3164         return false;
3165     }
3166   } else if (Opc == ISD::SHL) {
3167     // (x & 0xff) << 8
3168     // (x & 0xff0000) << 8
3169     if (Num != 0 && Num != 2)
3170       return false;
3171     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3172     if (!C || C->getZExtValue() != 8)
3173       return false;
3174   } else { // Opc == ISD::SRL
3175     // (x & 0xff00) >> 8
3176     // (x & 0xff000000) >> 8
3177     if (Num != 1 && Num != 3)
3178       return false;
3179     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3180     if (!C || C->getZExtValue() != 8)
3181       return false;
3182   }
3183
3184   if (Parts[Num])
3185     return false;
3186
3187   Parts[Num] = N0.getOperand(0).getNode();
3188   return true;
3189 }
3190
3191 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3192 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3193 /// => (rotl (bswap x), 16)
3194 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3195   if (!LegalOperations)
3196     return SDValue();
3197
3198   EVT VT = N->getValueType(0);
3199   if (VT != MVT::i32)
3200     return SDValue();
3201   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3202     return SDValue();
3203
3204   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3205   // Look for either
3206   // (or (or (and), (and)), (or (and), (and)))
3207   // (or (or (or (and), (and)), (and)), (and))
3208   if (N0.getOpcode() != ISD::OR)
3209     return SDValue();
3210   SDValue N00 = N0.getOperand(0);
3211   SDValue N01 = N0.getOperand(1);
3212
3213   if (N1.getOpcode() == ISD::OR &&
3214       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3215     // (or (or (and), (and)), (or (and), (and)))
3216     SDValue N000 = N00.getOperand(0);
3217     if (!isBSwapHWordElement(N000, Parts))
3218       return SDValue();
3219
3220     SDValue N001 = N00.getOperand(1);
3221     if (!isBSwapHWordElement(N001, Parts))
3222       return SDValue();
3223     SDValue N010 = N01.getOperand(0);
3224     if (!isBSwapHWordElement(N010, Parts))
3225       return SDValue();
3226     SDValue N011 = N01.getOperand(1);
3227     if (!isBSwapHWordElement(N011, Parts))
3228       return SDValue();
3229   } else {
3230     // (or (or (or (and), (and)), (and)), (and))
3231     if (!isBSwapHWordElement(N1, Parts))
3232       return SDValue();
3233     if (!isBSwapHWordElement(N01, Parts))
3234       return SDValue();
3235     if (N00.getOpcode() != ISD::OR)
3236       return SDValue();
3237     SDValue N000 = N00.getOperand(0);
3238     if (!isBSwapHWordElement(N000, Parts))
3239       return SDValue();
3240     SDValue N001 = N00.getOperand(1);
3241     if (!isBSwapHWordElement(N001, Parts))
3242       return SDValue();
3243   }
3244
3245   // Make sure the parts are all coming from the same node.
3246   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3247     return SDValue();
3248
3249   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3250                               SDValue(Parts[0],0));
3251
3252   // Result of the bswap should be rotated by 16. If it's not legal, then
3253   // do  (x << 16) | (x >> 16).
3254   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3255   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3256     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3257   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3258     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3259   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3260                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3261                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3262 }
3263
3264 SDValue DAGCombiner::visitOR(SDNode *N) {
3265   SDValue N0 = N->getOperand(0);
3266   SDValue N1 = N->getOperand(1);
3267   SDValue LL, LR, RL, RR, CC0, CC1;
3268   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3269   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3270   EVT VT = N1.getValueType();
3271
3272   // fold vector ops
3273   if (VT.isVector()) {
3274     SDValue FoldedVOp = SimplifyVBinOp(N);
3275     if (FoldedVOp.getNode()) return FoldedVOp;
3276
3277     // fold (or x, 0) -> x, vector edition
3278     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3279       return N1;
3280     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3281       return N0;
3282
3283     // fold (or x, -1) -> -1, vector edition
3284     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3285       return N0;
3286     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3287       return N1;
3288
3289     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3290     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3291     // Do this only if the resulting shuffle is legal.
3292     if (isa<ShuffleVectorSDNode>(N0) &&
3293         isa<ShuffleVectorSDNode>(N1) &&
3294         // Avoid folding a node with illegal type.
3295         TLI.isTypeLegal(VT) &&
3296         N0->getOperand(1) == N1->getOperand(1) &&
3297         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3298       bool CanFold = true;
3299       unsigned NumElts = VT.getVectorNumElements();
3300       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3301       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3302       // We construct two shuffle masks:
3303       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3304       // and N1 as the second operand.
3305       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3306       // and N0 as the second operand.
3307       // We do this because OR is commutable and therefore there might be
3308       // two ways to fold this node into a shuffle.
3309       SmallVector<int,4> Mask1;
3310       SmallVector<int,4> Mask2;
3311
3312       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3313         int M0 = SV0->getMaskElt(i);
3314         int M1 = SV1->getMaskElt(i);
3315
3316         // Both shuffle indexes are undef. Propagate Undef.
3317         if (M0 < 0 && M1 < 0) {
3318           Mask1.push_back(M0);
3319           Mask2.push_back(M0);
3320           continue;
3321         }
3322
3323         if (M0 < 0 || M1 < 0 ||
3324             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3325             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3326           CanFold = false;
3327           break;
3328         }
3329
3330         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3331         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3332       }
3333
3334       if (CanFold) {
3335         // Fold this sequence only if the resulting shuffle is 'legal'.
3336         if (TLI.isShuffleMaskLegal(Mask1, VT))
3337           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3338                                       N1->getOperand(0), &Mask1[0]);
3339         if (TLI.isShuffleMaskLegal(Mask2, VT))
3340           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3341                                       N0->getOperand(0), &Mask2[0]);
3342       }
3343     }
3344   }
3345
3346   // fold (or x, undef) -> -1
3347   if (!LegalOperations &&
3348       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3349     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3350     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3351   }
3352   // fold (or c1, c2) -> c1|c2
3353   if (N0C && N1C)
3354     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3355   // canonicalize constant to RHS
3356   if (N0C && !N1C)
3357     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3358   // fold (or x, 0) -> x
3359   if (N1C && N1C->isNullValue())
3360     return N0;
3361   // fold (or x, -1) -> -1
3362   if (N1C && N1C->isAllOnesValue())
3363     return N1;
3364   // fold (or x, c) -> c iff (x & ~c) == 0
3365   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3366     return N1;
3367
3368   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3369   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3370   if (BSwap.getNode())
3371     return BSwap;
3372   BSwap = MatchBSwapHWordLow(N, N0, N1);
3373   if (BSwap.getNode())
3374     return BSwap;
3375
3376   // reassociate or
3377   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3378   if (ROR.getNode())
3379     return ROR;
3380   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3381   // iff (c1 & c2) == 0.
3382   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3383              isa<ConstantSDNode>(N0.getOperand(1))) {
3384     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3385     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3386       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3387       if (!COR.getNode())
3388         return SDValue();
3389       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3390                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3391                                      N0.getOperand(0), N1), COR);
3392     }
3393   }
3394   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3395   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3396     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3397     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3398
3399     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3400         LL.getValueType().isInteger()) {
3401       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3402       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3403       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3404           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3405         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3406                                      LR.getValueType(), LL, RL);
3407         AddToWorklist(ORNode.getNode());
3408         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3409       }
3410       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3411       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3412       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3413           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3414         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3415                                       LR.getValueType(), LL, RL);
3416         AddToWorklist(ANDNode.getNode());
3417         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3418       }
3419     }
3420     // canonicalize equivalent to ll == rl
3421     if (LL == RR && LR == RL) {
3422       Op1 = ISD::getSetCCSwappedOperands(Op1);
3423       std::swap(RL, RR);
3424     }
3425     if (LL == RL && LR == RR) {
3426       bool isInteger = LL.getValueType().isInteger();
3427       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3428       if (Result != ISD::SETCC_INVALID &&
3429           (!LegalOperations ||
3430            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3431             TLI.isOperationLegal(ISD::SETCC,
3432               getSetCCResultType(N0.getValueType())))))
3433         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3434                             LL, LR, Result);
3435     }
3436   }
3437
3438   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3439   if (N0.getOpcode() == N1.getOpcode()) {
3440     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3441     if (Tmp.getNode()) return Tmp;
3442   }
3443
3444   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3445   if (N0.getOpcode() == ISD::AND &&
3446       N1.getOpcode() == ISD::AND &&
3447       N0.getOperand(1).getOpcode() == ISD::Constant &&
3448       N1.getOperand(1).getOpcode() == ISD::Constant &&
3449       // Don't increase # computations.
3450       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3451     // We can only do this xform if we know that bits from X that are set in C2
3452     // but not in C1 are already zero.  Likewise for Y.
3453     const APInt &LHSMask =
3454       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3455     const APInt &RHSMask =
3456       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3457
3458     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3459         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3460       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3461                               N0.getOperand(0), N1.getOperand(0));
3462       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3463                          DAG.getConstant(LHSMask | RHSMask, VT));
3464     }
3465   }
3466
3467   // See if this is some rotate idiom.
3468   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3469     return SDValue(Rot, 0);
3470
3471   // Simplify the operands using demanded-bits information.
3472   if (!VT.isVector() &&
3473       SimplifyDemandedBits(SDValue(N, 0)))
3474     return SDValue(N, 0);
3475
3476   return SDValue();
3477 }
3478
3479 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3480 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3481   if (Op.getOpcode() == ISD::AND) {
3482     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3483       Mask = Op.getOperand(1);
3484       Op = Op.getOperand(0);
3485     } else {
3486       return false;
3487     }
3488   }
3489
3490   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3491     Shift = Op;
3492     return true;
3493   }
3494
3495   return false;
3496 }
3497
3498 // Return true if we can prove that, whenever Neg and Pos are both in the
3499 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3500 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3501 //
3502 //     (or (shift1 X, Neg), (shift2 X, Pos))
3503 //
3504 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3505 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3506 // to consider shift amounts with defined behavior.
3507 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3508   // If OpSize is a power of 2 then:
3509   //
3510   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3511   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3512   //
3513   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3514   // for the stronger condition:
3515   //
3516   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3517   //
3518   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3519   // we can just replace Neg with Neg' for the rest of the function.
3520   //
3521   // In other cases we check for the even stronger condition:
3522   //
3523   //     Neg == OpSize - Pos                                    [B]
3524   //
3525   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3526   // behavior if Pos == 0 (and consequently Neg == OpSize).
3527   //
3528   // We could actually use [A] whenever OpSize is a power of 2, but the
3529   // only extra cases that it would match are those uninteresting ones
3530   // where Neg and Pos are never in range at the same time.  E.g. for
3531   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3532   // as well as (sub 32, Pos), but:
3533   //
3534   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3535   //
3536   // always invokes undefined behavior for 32-bit X.
3537   //
3538   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3539   unsigned MaskLoBits = 0;
3540   if (Neg.getOpcode() == ISD::AND &&
3541       isPowerOf2_64(OpSize) &&
3542       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3543       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3544     Neg = Neg.getOperand(0);
3545     MaskLoBits = Log2_64(OpSize);
3546   }
3547
3548   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3549   if (Neg.getOpcode() != ISD::SUB)
3550     return 0;
3551   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3552   if (!NegC)
3553     return 0;
3554   SDValue NegOp1 = Neg.getOperand(1);
3555
3556   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3557   // Pos'.  The truncation is redundant for the purpose of the equality.
3558   if (MaskLoBits &&
3559       Pos.getOpcode() == ISD::AND &&
3560       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3561       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3562     Pos = Pos.getOperand(0);
3563
3564   // The condition we need is now:
3565   //
3566   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3567   //
3568   // If NegOp1 == Pos then we need:
3569   //
3570   //              OpSize & Mask == NegC & Mask
3571   //
3572   // (because "x & Mask" is a truncation and distributes through subtraction).
3573   APInt Width;
3574   if (Pos == NegOp1)
3575     Width = NegC->getAPIntValue();
3576   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3577   // Then the condition we want to prove becomes:
3578   //
3579   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3580   //
3581   // which, again because "x & Mask" is a truncation, becomes:
3582   //
3583   //                NegC & Mask == (OpSize - PosC) & Mask
3584   //              OpSize & Mask == (NegC + PosC) & Mask
3585   else if (Pos.getOpcode() == ISD::ADD &&
3586            Pos.getOperand(0) == NegOp1 &&
3587            Pos.getOperand(1).getOpcode() == ISD::Constant)
3588     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3589              NegC->getAPIntValue());
3590   else
3591     return false;
3592
3593   // Now we just need to check that OpSize & Mask == Width & Mask.
3594   if (MaskLoBits)
3595     // Opsize & Mask is 0 since Mask is Opsize - 1.
3596     return Width.getLoBits(MaskLoBits) == 0;
3597   return Width == OpSize;
3598 }
3599
3600 // A subroutine of MatchRotate used once we have found an OR of two opposite
3601 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3602 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3603 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3604 // Neg with outer conversions stripped away.
3605 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3606                                        SDValue Neg, SDValue InnerPos,
3607                                        SDValue InnerNeg, unsigned PosOpcode,
3608                                        unsigned NegOpcode, SDLoc DL) {
3609   // fold (or (shl x, (*ext y)),
3610   //          (srl x, (*ext (sub 32, y)))) ->
3611   //   (rotl x, y) or (rotr x, (sub 32, y))
3612   //
3613   // fold (or (shl x, (*ext (sub 32, y))),
3614   //          (srl x, (*ext y))) ->
3615   //   (rotr x, y) or (rotl x, (sub 32, y))
3616   EVT VT = Shifted.getValueType();
3617   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3618     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3619     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3620                        HasPos ? Pos : Neg).getNode();
3621   }
3622
3623   return nullptr;
3624 }
3625
3626 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3627 // idioms for rotate, and if the target supports rotation instructions, generate
3628 // a rot[lr].
3629 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3630   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3631   EVT VT = LHS.getValueType();
3632   if (!TLI.isTypeLegal(VT)) return nullptr;
3633
3634   // The target must have at least one rotate flavor.
3635   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3636   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3637   if (!HasROTL && !HasROTR) return nullptr;
3638
3639   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3640   SDValue LHSShift;   // The shift.
3641   SDValue LHSMask;    // AND value if any.
3642   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3643     return nullptr; // Not part of a rotate.
3644
3645   SDValue RHSShift;   // The shift.
3646   SDValue RHSMask;    // AND value if any.
3647   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3648     return nullptr; // Not part of a rotate.
3649
3650   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3651     return nullptr;   // Not shifting the same value.
3652
3653   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3654     return nullptr;   // Shifts must disagree.
3655
3656   // Canonicalize shl to left side in a shl/srl pair.
3657   if (RHSShift.getOpcode() == ISD::SHL) {
3658     std::swap(LHS, RHS);
3659     std::swap(LHSShift, RHSShift);
3660     std::swap(LHSMask , RHSMask );
3661   }
3662
3663   unsigned OpSizeInBits = VT.getSizeInBits();
3664   SDValue LHSShiftArg = LHSShift.getOperand(0);
3665   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3666   SDValue RHSShiftArg = RHSShift.getOperand(0);
3667   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3668
3669   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3670   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3671   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3672       RHSShiftAmt.getOpcode() == ISD::Constant) {
3673     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3674     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3675     if ((LShVal + RShVal) != OpSizeInBits)
3676       return nullptr;
3677
3678     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3679                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3680
3681     // If there is an AND of either shifted operand, apply it to the result.
3682     if (LHSMask.getNode() || RHSMask.getNode()) {
3683       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3684
3685       if (LHSMask.getNode()) {
3686         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3687         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3688       }
3689       if (RHSMask.getNode()) {
3690         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3691         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3692       }
3693
3694       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3695     }
3696
3697     return Rot.getNode();
3698   }
3699
3700   // If there is a mask here, and we have a variable shift, we can't be sure
3701   // that we're masking out the right stuff.
3702   if (LHSMask.getNode() || RHSMask.getNode())
3703     return nullptr;
3704
3705   // If the shift amount is sign/zext/any-extended just peel it off.
3706   SDValue LExtOp0 = LHSShiftAmt;
3707   SDValue RExtOp0 = RHSShiftAmt;
3708   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3709        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3710        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3711        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3712       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3713        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3714        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3715        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3716     LExtOp0 = LHSShiftAmt.getOperand(0);
3717     RExtOp0 = RHSShiftAmt.getOperand(0);
3718   }
3719
3720   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3721                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3722   if (TryL)
3723     return TryL;
3724
3725   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3726                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3727   if (TryR)
3728     return TryR;
3729
3730   return nullptr;
3731 }
3732
3733 SDValue DAGCombiner::visitXOR(SDNode *N) {
3734   SDValue N0 = N->getOperand(0);
3735   SDValue N1 = N->getOperand(1);
3736   SDValue LHS, RHS, CC;
3737   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3738   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3739   EVT VT = N0.getValueType();
3740
3741   // fold vector ops
3742   if (VT.isVector()) {
3743     SDValue FoldedVOp = SimplifyVBinOp(N);
3744     if (FoldedVOp.getNode()) return FoldedVOp;
3745
3746     // fold (xor x, 0) -> x, vector edition
3747     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3748       return N1;
3749     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3750       return N0;
3751   }
3752
3753   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3754   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3755     return DAG.getConstant(0, VT);
3756   // fold (xor x, undef) -> undef
3757   if (N0.getOpcode() == ISD::UNDEF)
3758     return N0;
3759   if (N1.getOpcode() == ISD::UNDEF)
3760     return N1;
3761   // fold (xor c1, c2) -> c1^c2
3762   if (N0C && N1C)
3763     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3764   // canonicalize constant to RHS
3765   if (N0C && !N1C)
3766     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3767   // fold (xor x, 0) -> x
3768   if (N1C && N1C->isNullValue())
3769     return N0;
3770   // reassociate xor
3771   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3772   if (RXOR.getNode())
3773     return RXOR;
3774
3775   // fold !(x cc y) -> (x !cc y)
3776   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3777     bool isInt = LHS.getValueType().isInteger();
3778     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3779                                                isInt);
3780
3781     if (!LegalOperations ||
3782         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3783       switch (N0.getOpcode()) {
3784       default:
3785         llvm_unreachable("Unhandled SetCC Equivalent!");
3786       case ISD::SETCC:
3787         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3788       case ISD::SELECT_CC:
3789         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3790                                N0.getOperand(3), NotCC);
3791       }
3792     }
3793   }
3794
3795   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3796   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3797       N0.getNode()->hasOneUse() &&
3798       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3799     SDValue V = N0.getOperand(0);
3800     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3801                     DAG.getConstant(1, V.getValueType()));
3802     AddToWorklist(V.getNode());
3803     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3804   }
3805
3806   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3807   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3808       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3809     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3810     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3811       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3812       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3813       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3814       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3815       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3816     }
3817   }
3818   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3819   if (N1C && N1C->isAllOnesValue() &&
3820       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3821     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3822     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3823       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3824       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3825       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3826       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3827       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3828     }
3829   }
3830   // fold (xor (and x, y), y) -> (and (not x), y)
3831   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3832       N0->getOperand(1) == N1) {
3833     SDValue X = N0->getOperand(0);
3834     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3835     AddToWorklist(NotX.getNode());
3836     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3837   }
3838   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3839   if (N1C && N0.getOpcode() == ISD::XOR) {
3840     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3841     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3842     if (N00C)
3843       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3844                          DAG.getConstant(N1C->getAPIntValue() ^
3845                                          N00C->getAPIntValue(), VT));
3846     if (N01C)
3847       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3848                          DAG.getConstant(N1C->getAPIntValue() ^
3849                                          N01C->getAPIntValue(), VT));
3850   }
3851   // fold (xor x, x) -> 0
3852   if (N0 == N1)
3853     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3854
3855   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3856   if (N0.getOpcode() == N1.getOpcode()) {
3857     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3858     if (Tmp.getNode()) return Tmp;
3859   }
3860
3861   // Simplify the expression using non-local knowledge.
3862   if (!VT.isVector() &&
3863       SimplifyDemandedBits(SDValue(N, 0)))
3864     return SDValue(N, 0);
3865
3866   return SDValue();
3867 }
3868
3869 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3870 /// the shift amount is a constant.
3871 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3872   // We can't and shouldn't fold opaque constants.
3873   if (Amt->isOpaque())
3874     return SDValue();
3875
3876   SDNode *LHS = N->getOperand(0).getNode();
3877   if (!LHS->hasOneUse()) return SDValue();
3878
3879   // We want to pull some binops through shifts, so that we have (and (shift))
3880   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3881   // thing happens with address calculations, so it's important to canonicalize
3882   // it.
3883   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3884
3885   switch (LHS->getOpcode()) {
3886   default: return SDValue();
3887   case ISD::OR:
3888   case ISD::XOR:
3889     HighBitSet = false; // We can only transform sra if the high bit is clear.
3890     break;
3891   case ISD::AND:
3892     HighBitSet = true;  // We can only transform sra if the high bit is set.
3893     break;
3894   case ISD::ADD:
3895     if (N->getOpcode() != ISD::SHL)
3896       return SDValue(); // only shl(add) not sr[al](add).
3897     HighBitSet = false; // We can only transform sra if the high bit is clear.
3898     break;
3899   }
3900
3901   // We require the RHS of the binop to be a constant and not opaque as well.
3902   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3903   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3904
3905   // FIXME: disable this unless the input to the binop is a shift by a constant.
3906   // If it is not a shift, it pessimizes some common cases like:
3907   //
3908   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3909   //    int bar(int *X, int i) { return X[i & 255]; }
3910   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3911   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3912        BinOpLHSVal->getOpcode() != ISD::SRA &&
3913        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3914       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3915     return SDValue();
3916
3917   EVT VT = N->getValueType(0);
3918
3919   // If this is a signed shift right, and the high bit is modified by the
3920   // logical operation, do not perform the transformation. The highBitSet
3921   // boolean indicates the value of the high bit of the constant which would
3922   // cause it to be modified for this operation.
3923   if (N->getOpcode() == ISD::SRA) {
3924     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3925     if (BinOpRHSSignSet != HighBitSet)
3926       return SDValue();
3927   }
3928
3929   if (!TLI.isDesirableToCommuteWithShift(LHS))
3930     return SDValue();
3931
3932   // Fold the constants, shifting the binop RHS by the shift amount.
3933   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3934                                N->getValueType(0),
3935                                LHS->getOperand(1), N->getOperand(1));
3936   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3937
3938   // Create the new shift.
3939   SDValue NewShift = DAG.getNode(N->getOpcode(),
3940                                  SDLoc(LHS->getOperand(0)),
3941                                  VT, LHS->getOperand(0), N->getOperand(1));
3942
3943   // Create the new binop.
3944   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3945 }
3946
3947 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3948   assert(N->getOpcode() == ISD::TRUNCATE);
3949   assert(N->getOperand(0).getOpcode() == ISD::AND);
3950
3951   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3952   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3953     SDValue N01 = N->getOperand(0).getOperand(1);
3954
3955     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3956       EVT TruncVT = N->getValueType(0);
3957       SDValue N00 = N->getOperand(0).getOperand(0);
3958       APInt TruncC = N01C->getAPIntValue();
3959       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3960
3961       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3962                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3963                          DAG.getConstant(TruncC, TruncVT));
3964     }
3965   }
3966
3967   return SDValue();
3968 }
3969
3970 SDValue DAGCombiner::visitRotate(SDNode *N) {
3971   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3972   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3973       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3974     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3975     if (NewOp1.getNode())
3976       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3977                          N->getOperand(0), NewOp1);
3978   }
3979   return SDValue();
3980 }
3981
3982 SDValue DAGCombiner::visitSHL(SDNode *N) {
3983   SDValue N0 = N->getOperand(0);
3984   SDValue N1 = N->getOperand(1);
3985   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3986   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3987   EVT VT = N0.getValueType();
3988   unsigned OpSizeInBits = VT.getScalarSizeInBits();
3989
3990   // fold vector ops
3991   if (VT.isVector()) {
3992     SDValue FoldedVOp = SimplifyVBinOp(N);
3993     if (FoldedVOp.getNode()) return FoldedVOp;
3994
3995     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3996     // If setcc produces all-one true value then:
3997     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3998     if (N1CV && N1CV->isConstant()) {
3999       if (N0.getOpcode() == ISD::AND) {
4000         SDValue N00 = N0->getOperand(0);
4001         SDValue N01 = N0->getOperand(1);
4002         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4003
4004         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4005             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4006                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4007           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4008           if (C.getNode())
4009             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4010         }
4011       } else {
4012         N1C = isConstOrConstSplat(N1);
4013       }
4014     }
4015   }
4016
4017   // fold (shl c1, c2) -> c1<<c2
4018   if (N0C && N1C)
4019     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4020   // fold (shl 0, x) -> 0
4021   if (N0C && N0C->isNullValue())
4022     return N0;
4023   // fold (shl x, c >= size(x)) -> undef
4024   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4025     return DAG.getUNDEF(VT);
4026   // fold (shl x, 0) -> x
4027   if (N1C && N1C->isNullValue())
4028     return N0;
4029   // fold (shl undef, x) -> 0
4030   if (N0.getOpcode() == ISD::UNDEF)
4031     return DAG.getConstant(0, VT);
4032   // if (shl x, c) is known to be zero, return 0
4033   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4034                             APInt::getAllOnesValue(OpSizeInBits)))
4035     return DAG.getConstant(0, VT);
4036   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4037   if (N1.getOpcode() == ISD::TRUNCATE &&
4038       N1.getOperand(0).getOpcode() == ISD::AND) {
4039     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4040     if (NewOp1.getNode())
4041       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4042   }
4043
4044   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4045     return SDValue(N, 0);
4046
4047   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4048   if (N1C && N0.getOpcode() == ISD::SHL) {
4049     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4050       uint64_t c1 = N0C1->getZExtValue();
4051       uint64_t c2 = N1C->getZExtValue();
4052       if (c1 + c2 >= OpSizeInBits)
4053         return DAG.getConstant(0, VT);
4054       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4055                          DAG.getConstant(c1 + c2, N1.getValueType()));
4056     }
4057   }
4058
4059   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4060   // For this to be valid, the second form must not preserve any of the bits
4061   // that are shifted out by the inner shift in the first form.  This means
4062   // the outer shift size must be >= the number of bits added by the ext.
4063   // As a corollary, we don't care what kind of ext it is.
4064   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4065               N0.getOpcode() == ISD::ANY_EXTEND ||
4066               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4067       N0.getOperand(0).getOpcode() == ISD::SHL) {
4068     SDValue N0Op0 = N0.getOperand(0);
4069     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4070       uint64_t c1 = N0Op0C1->getZExtValue();
4071       uint64_t c2 = N1C->getZExtValue();
4072       EVT InnerShiftVT = N0Op0.getValueType();
4073       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4074       if (c2 >= OpSizeInBits - InnerShiftSize) {
4075         if (c1 + c2 >= OpSizeInBits)
4076           return DAG.getConstant(0, VT);
4077         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4078                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4079                                        N0Op0->getOperand(0)),
4080                            DAG.getConstant(c1 + c2, N1.getValueType()));
4081       }
4082     }
4083   }
4084
4085   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4086   // Only fold this if the inner zext has no other uses to avoid increasing
4087   // the total number of instructions.
4088   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4089       N0.getOperand(0).getOpcode() == ISD::SRL) {
4090     SDValue N0Op0 = N0.getOperand(0);
4091     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4092       uint64_t c1 = N0Op0C1->getZExtValue();
4093       if (c1 < VT.getScalarSizeInBits()) {
4094         uint64_t c2 = N1C->getZExtValue();
4095         if (c1 == c2) {
4096           SDValue NewOp0 = N0.getOperand(0);
4097           EVT CountVT = NewOp0.getOperand(1).getValueType();
4098           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4099                                        NewOp0, DAG.getConstant(c2, CountVT));
4100           AddToWorklist(NewSHL.getNode());
4101           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4102         }
4103       }
4104     }
4105   }
4106
4107   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4108   //                               (and (srl x, (sub c1, c2), MASK)
4109   // Only fold this if the inner shift has no other uses -- if it does, folding
4110   // this will increase the total number of instructions.
4111   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4112     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4113       uint64_t c1 = N0C1->getZExtValue();
4114       if (c1 < OpSizeInBits) {
4115         uint64_t c2 = N1C->getZExtValue();
4116         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4117         SDValue Shift;
4118         if (c2 > c1) {
4119           Mask = Mask.shl(c2 - c1);
4120           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4121                               DAG.getConstant(c2 - c1, N1.getValueType()));
4122         } else {
4123           Mask = Mask.lshr(c1 - c2);
4124           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4125                               DAG.getConstant(c1 - c2, N1.getValueType()));
4126         }
4127         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4128                            DAG.getConstant(Mask, VT));
4129       }
4130     }
4131   }
4132   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4133   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4134     unsigned BitSize = VT.getScalarSizeInBits();
4135     SDValue HiBitsMask =
4136       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4137                                             BitSize - N1C->getZExtValue()), VT);
4138     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4139                        HiBitsMask);
4140   }
4141
4142   if (N1C) {
4143     SDValue NewSHL = visitShiftByConstant(N, N1C);
4144     if (NewSHL.getNode())
4145       return NewSHL;
4146   }
4147
4148   return SDValue();
4149 }
4150
4151 SDValue DAGCombiner::visitSRA(SDNode *N) {
4152   SDValue N0 = N->getOperand(0);
4153   SDValue N1 = N->getOperand(1);
4154   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4155   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4156   EVT VT = N0.getValueType();
4157   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4158
4159   // fold vector ops
4160   if (VT.isVector()) {
4161     SDValue FoldedVOp = SimplifyVBinOp(N);
4162     if (FoldedVOp.getNode()) return FoldedVOp;
4163
4164     N1C = isConstOrConstSplat(N1);
4165   }
4166
4167   // fold (sra c1, c2) -> (sra c1, c2)
4168   if (N0C && N1C)
4169     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4170   // fold (sra 0, x) -> 0
4171   if (N0C && N0C->isNullValue())
4172     return N0;
4173   // fold (sra -1, x) -> -1
4174   if (N0C && N0C->isAllOnesValue())
4175     return N0;
4176   // fold (sra x, (setge c, size(x))) -> undef
4177   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4178     return DAG.getUNDEF(VT);
4179   // fold (sra x, 0) -> x
4180   if (N1C && N1C->isNullValue())
4181     return N0;
4182   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4183   // sext_inreg.
4184   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4185     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4186     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4187     if (VT.isVector())
4188       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4189                                ExtVT, VT.getVectorNumElements());
4190     if ((!LegalOperations ||
4191          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4192       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4193                          N0.getOperand(0), DAG.getValueType(ExtVT));
4194   }
4195
4196   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4197   if (N1C && N0.getOpcode() == ISD::SRA) {
4198     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4199       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4200       if (Sum >= OpSizeInBits)
4201         Sum = OpSizeInBits - 1;
4202       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4203                          DAG.getConstant(Sum, N1.getValueType()));
4204     }
4205   }
4206
4207   // fold (sra (shl X, m), (sub result_size, n))
4208   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4209   // result_size - n != m.
4210   // If truncate is free for the target sext(shl) is likely to result in better
4211   // code.
4212   if (N0.getOpcode() == ISD::SHL && N1C) {
4213     // Get the two constanst of the shifts, CN0 = m, CN = n.
4214     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4215     if (N01C) {
4216       LLVMContext &Ctx = *DAG.getContext();
4217       // Determine what the truncate's result bitsize and type would be.
4218       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4219
4220       if (VT.isVector())
4221         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4222
4223       // Determine the residual right-shift amount.
4224       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4225
4226       // If the shift is not a no-op (in which case this should be just a sign
4227       // extend already), the truncated to type is legal, sign_extend is legal
4228       // on that type, and the truncate to that type is both legal and free,
4229       // perform the transform.
4230       if ((ShiftAmt > 0) &&
4231           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4232           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4233           TLI.isTruncateFree(VT, TruncVT)) {
4234
4235           SDValue Amt = DAG.getConstant(ShiftAmt,
4236               getShiftAmountTy(N0.getOperand(0).getValueType()));
4237           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4238                                       N0.getOperand(0), Amt);
4239           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4240                                       Shift);
4241           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4242                              N->getValueType(0), Trunc);
4243       }
4244     }
4245   }
4246
4247   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4248   if (N1.getOpcode() == ISD::TRUNCATE &&
4249       N1.getOperand(0).getOpcode() == ISD::AND) {
4250     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4251     if (NewOp1.getNode())
4252       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4253   }
4254
4255   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4256   //      if c1 is equal to the number of bits the trunc removes
4257   if (N0.getOpcode() == ISD::TRUNCATE &&
4258       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4259        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4260       N0.getOperand(0).hasOneUse() &&
4261       N0.getOperand(0).getOperand(1).hasOneUse() &&
4262       N1C) {
4263     SDValue N0Op0 = N0.getOperand(0);
4264     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4265       unsigned LargeShiftVal = LargeShift->getZExtValue();
4266       EVT LargeVT = N0Op0.getValueType();
4267
4268       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4269         SDValue Amt =
4270           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4271                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4272         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4273                                   N0Op0.getOperand(0), Amt);
4274         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4275       }
4276     }
4277   }
4278
4279   // Simplify, based on bits shifted out of the LHS.
4280   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4281     return SDValue(N, 0);
4282
4283
4284   // If the sign bit is known to be zero, switch this to a SRL.
4285   if (DAG.SignBitIsZero(N0))
4286     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4287
4288   if (N1C) {
4289     SDValue NewSRA = visitShiftByConstant(N, N1C);
4290     if (NewSRA.getNode())
4291       return NewSRA;
4292   }
4293
4294   return SDValue();
4295 }
4296
4297 SDValue DAGCombiner::visitSRL(SDNode *N) {
4298   SDValue N0 = N->getOperand(0);
4299   SDValue N1 = N->getOperand(1);
4300   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4301   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4302   EVT VT = N0.getValueType();
4303   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4304
4305   // fold vector ops
4306   if (VT.isVector()) {
4307     SDValue FoldedVOp = SimplifyVBinOp(N);
4308     if (FoldedVOp.getNode()) return FoldedVOp;
4309
4310     N1C = isConstOrConstSplat(N1);
4311   }
4312
4313   // fold (srl c1, c2) -> c1 >>u c2
4314   if (N0C && N1C)
4315     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4316   // fold (srl 0, x) -> 0
4317   if (N0C && N0C->isNullValue())
4318     return N0;
4319   // fold (srl x, c >= size(x)) -> undef
4320   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4321     return DAG.getUNDEF(VT);
4322   // fold (srl x, 0) -> x
4323   if (N1C && N1C->isNullValue())
4324     return N0;
4325   // if (srl x, c) is known to be zero, return 0
4326   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4327                                    APInt::getAllOnesValue(OpSizeInBits)))
4328     return DAG.getConstant(0, VT);
4329
4330   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4331   if (N1C && N0.getOpcode() == ISD::SRL) {
4332     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4333       uint64_t c1 = N01C->getZExtValue();
4334       uint64_t c2 = N1C->getZExtValue();
4335       if (c1 + c2 >= OpSizeInBits)
4336         return DAG.getConstant(0, VT);
4337       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4338                          DAG.getConstant(c1 + c2, N1.getValueType()));
4339     }
4340   }
4341
4342   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4343   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4344       N0.getOperand(0).getOpcode() == ISD::SRL &&
4345       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4346     uint64_t c1 =
4347       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4348     uint64_t c2 = N1C->getZExtValue();
4349     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4350     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4351     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4352     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4353     if (c1 + OpSizeInBits == InnerShiftSize) {
4354       if (c1 + c2 >= InnerShiftSize)
4355         return DAG.getConstant(0, VT);
4356       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4357                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4358                                      N0.getOperand(0)->getOperand(0),
4359                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4360     }
4361   }
4362
4363   // fold (srl (shl x, c), c) -> (and x, cst2)
4364   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4365     unsigned BitSize = N0.getScalarValueSizeInBits();
4366     if (BitSize <= 64) {
4367       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4368       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4369                          DAG.getConstant(~0ULL >> ShAmt, VT));
4370     }
4371   }
4372
4373   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4374   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4375     // Shifting in all undef bits?
4376     EVT SmallVT = N0.getOperand(0).getValueType();
4377     unsigned BitSize = SmallVT.getScalarSizeInBits();
4378     if (N1C->getZExtValue() >= BitSize)
4379       return DAG.getUNDEF(VT);
4380
4381     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4382       uint64_t ShiftAmt = N1C->getZExtValue();
4383       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4384                                        N0.getOperand(0),
4385                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4386       AddToWorklist(SmallShift.getNode());
4387       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4388       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4389                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4390                          DAG.getConstant(Mask, VT));
4391     }
4392   }
4393
4394   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4395   // bit, which is unmodified by sra.
4396   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4397     if (N0.getOpcode() == ISD::SRA)
4398       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4399   }
4400
4401   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4402   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4403       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4404     APInt KnownZero, KnownOne;
4405     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4406
4407     // If any of the input bits are KnownOne, then the input couldn't be all
4408     // zeros, thus the result of the srl will always be zero.
4409     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4410
4411     // If all of the bits input the to ctlz node are known to be zero, then
4412     // the result of the ctlz is "32" and the result of the shift is one.
4413     APInt UnknownBits = ~KnownZero;
4414     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4415
4416     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4417     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4418       // Okay, we know that only that the single bit specified by UnknownBits
4419       // could be set on input to the CTLZ node. If this bit is set, the SRL
4420       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4421       // to an SRL/XOR pair, which is likely to simplify more.
4422       unsigned ShAmt = UnknownBits.countTrailingZeros();
4423       SDValue Op = N0.getOperand(0);
4424
4425       if (ShAmt) {
4426         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4427                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4428         AddToWorklist(Op.getNode());
4429       }
4430
4431       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4432                          Op, DAG.getConstant(1, VT));
4433     }
4434   }
4435
4436   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4437   if (N1.getOpcode() == ISD::TRUNCATE &&
4438       N1.getOperand(0).getOpcode() == ISD::AND) {
4439     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4440     if (NewOp1.getNode())
4441       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4442   }
4443
4444   // fold operands of srl based on knowledge that the low bits are not
4445   // demanded.
4446   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4447     return SDValue(N, 0);
4448
4449   if (N1C) {
4450     SDValue NewSRL = visitShiftByConstant(N, N1C);
4451     if (NewSRL.getNode())
4452       return NewSRL;
4453   }
4454
4455   // Attempt to convert a srl of a load into a narrower zero-extending load.
4456   SDValue NarrowLoad = ReduceLoadWidth(N);
4457   if (NarrowLoad.getNode())
4458     return NarrowLoad;
4459
4460   // Here is a common situation. We want to optimize:
4461   //
4462   //   %a = ...
4463   //   %b = and i32 %a, 2
4464   //   %c = srl i32 %b, 1
4465   //   brcond i32 %c ...
4466   //
4467   // into
4468   //
4469   //   %a = ...
4470   //   %b = and %a, 2
4471   //   %c = setcc eq %b, 0
4472   //   brcond %c ...
4473   //
4474   // However when after the source operand of SRL is optimized into AND, the SRL
4475   // itself may not be optimized further. Look for it and add the BRCOND into
4476   // the worklist.
4477   if (N->hasOneUse()) {
4478     SDNode *Use = *N->use_begin();
4479     if (Use->getOpcode() == ISD::BRCOND)
4480       AddToWorklist(Use);
4481     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4482       // Also look pass the truncate.
4483       Use = *Use->use_begin();
4484       if (Use->getOpcode() == ISD::BRCOND)
4485         AddToWorklist(Use);
4486     }
4487   }
4488
4489   return SDValue();
4490 }
4491
4492 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4493   SDValue N0 = N->getOperand(0);
4494   EVT VT = N->getValueType(0);
4495
4496   // fold (ctlz c1) -> c2
4497   if (isa<ConstantSDNode>(N0))
4498     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4499   return SDValue();
4500 }
4501
4502 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4503   SDValue N0 = N->getOperand(0);
4504   EVT VT = N->getValueType(0);
4505
4506   // fold (ctlz_zero_undef c1) -> c2
4507   if (isa<ConstantSDNode>(N0))
4508     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4509   return SDValue();
4510 }
4511
4512 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4513   SDValue N0 = N->getOperand(0);
4514   EVT VT = N->getValueType(0);
4515
4516   // fold (cttz c1) -> c2
4517   if (isa<ConstantSDNode>(N0))
4518     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4519   return SDValue();
4520 }
4521
4522 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4523   SDValue N0 = N->getOperand(0);
4524   EVT VT = N->getValueType(0);
4525
4526   // fold (cttz_zero_undef c1) -> c2
4527   if (isa<ConstantSDNode>(N0))
4528     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4529   return SDValue();
4530 }
4531
4532 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4533   SDValue N0 = N->getOperand(0);
4534   EVT VT = N->getValueType(0);
4535
4536   // fold (ctpop c1) -> c2
4537   if (isa<ConstantSDNode>(N0))
4538     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4539   return SDValue();
4540 }
4541
4542 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4543   SDValue N0 = N->getOperand(0);
4544   SDValue N1 = N->getOperand(1);
4545   SDValue N2 = N->getOperand(2);
4546   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4547   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4548   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4549   EVT VT = N->getValueType(0);
4550   EVT VT0 = N0.getValueType();
4551
4552   // fold (select C, X, X) -> X
4553   if (N1 == N2)
4554     return N1;
4555   // fold (select true, X, Y) -> X
4556   if (N0C && !N0C->isNullValue())
4557     return N1;
4558   // fold (select false, X, Y) -> Y
4559   if (N0C && N0C->isNullValue())
4560     return N2;
4561   // fold (select C, 1, X) -> (or C, X)
4562   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4563     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4564   // fold (select C, 0, 1) -> (xor C, 1)
4565   // We can't do this reliably if integer based booleans have different contents
4566   // to floating point based booleans. This is because we can't tell whether we
4567   // have an integer-based boolean or a floating-point-based boolean unless we
4568   // can find the SETCC that produced it and inspect its operands. This is
4569   // fairly easy if C is the SETCC node, but it can potentially be
4570   // undiscoverable (or not reasonably discoverable). For example, it could be
4571   // in another basic block or it could require searching a complicated
4572   // expression.
4573   if (VT.isInteger() &&
4574       (VT0 == MVT::i1 || (VT0.isInteger() &&
4575                           TLI.getBooleanContents(false, false) ==
4576                               TLI.getBooleanContents(false, true) &&
4577                           TLI.getBooleanContents(false, false) ==
4578                               TargetLowering::ZeroOrOneBooleanContent)) &&
4579       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4580     SDValue XORNode;
4581     if (VT == VT0)
4582       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4583                          N0, DAG.getConstant(1, VT0));
4584     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4585                           N0, DAG.getConstant(1, VT0));
4586     AddToWorklist(XORNode.getNode());
4587     if (VT.bitsGT(VT0))
4588       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4589     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4590   }
4591   // fold (select C, 0, X) -> (and (not C), X)
4592   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4593     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4594     AddToWorklist(NOTNode.getNode());
4595     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4596   }
4597   // fold (select C, X, 1) -> (or (not C), X)
4598   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4599     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4600     AddToWorklist(NOTNode.getNode());
4601     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4602   }
4603   // fold (select C, X, 0) -> (and C, X)
4604   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4605     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4606   // fold (select X, X, Y) -> (or X, Y)
4607   // fold (select X, 1, Y) -> (or X, Y)
4608   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4609     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4610   // fold (select X, Y, X) -> (and X, Y)
4611   // fold (select X, Y, 0) -> (and X, Y)
4612   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4613     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4614
4615   // If we can fold this based on the true/false value, do so.
4616   if (SimplifySelectOps(N, N1, N2))
4617     return SDValue(N, 0);  // Don't revisit N.
4618
4619   // fold selects based on a setcc into other things, such as min/max/abs
4620   if (N0.getOpcode() == ISD::SETCC) {
4621     if ((!LegalOperations &&
4622          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4623         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4624       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4625                          N0.getOperand(0), N0.getOperand(1),
4626                          N1, N2, N0.getOperand(2));
4627     return SimplifySelect(SDLoc(N), N0, N1, N2);
4628   }
4629
4630   return SDValue();
4631 }
4632
4633 static
4634 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4635   SDLoc DL(N);
4636   EVT LoVT, HiVT;
4637   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4638
4639   // Split the inputs.
4640   SDValue Lo, Hi, LL, LH, RL, RH;
4641   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4642   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4643
4644   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4645   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4646
4647   return std::make_pair(Lo, Hi);
4648 }
4649
4650 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4651 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4652 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4653   SDLoc dl(N);
4654   SDValue Cond = N->getOperand(0);
4655   SDValue LHS = N->getOperand(1);
4656   SDValue RHS = N->getOperand(2);
4657   MVT VT = N->getSimpleValueType(0);
4658   int NumElems = VT.getVectorNumElements();
4659   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4660          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4661          Cond.getOpcode() == ISD::BUILD_VECTOR);
4662
4663   // We're sure we have an even number of elements due to the
4664   // concat_vectors we have as arguments to vselect.
4665   // Skip BV elements until we find one that's not an UNDEF
4666   // After we find an UNDEF element, keep looping until we get to half the
4667   // length of the BV and see if all the non-undef nodes are the same.
4668   ConstantSDNode *BottomHalf = nullptr;
4669   for (int i = 0; i < NumElems / 2; ++i) {
4670     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4671       continue;
4672
4673     if (BottomHalf == nullptr)
4674       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4675     else if (Cond->getOperand(i).getNode() != BottomHalf)
4676       return SDValue();
4677   }
4678
4679   // Do the same for the second half of the BuildVector
4680   ConstantSDNode *TopHalf = nullptr;
4681   for (int i = NumElems / 2; i < NumElems; ++i) {
4682     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4683       continue;
4684
4685     if (TopHalf == nullptr)
4686       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4687     else if (Cond->getOperand(i).getNode() != TopHalf)
4688       return SDValue();
4689   }
4690
4691   assert(TopHalf && BottomHalf &&
4692          "One half of the selector was all UNDEFs and the other was all the "
4693          "same value. This should have been addressed before this function.");
4694   return DAG.getNode(
4695       ISD::CONCAT_VECTORS, dl, VT,
4696       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4697       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4698 }
4699
4700 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4701   SDValue N0 = N->getOperand(0);
4702   SDValue N1 = N->getOperand(1);
4703   SDValue N2 = N->getOperand(2);
4704   SDLoc DL(N);
4705
4706   // Canonicalize integer abs.
4707   // vselect (setg[te] X,  0),  X, -X ->
4708   // vselect (setgt    X, -1),  X, -X ->
4709   // vselect (setl[te] X,  0), -X,  X ->
4710   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4711   if (N0.getOpcode() == ISD::SETCC) {
4712     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4713     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4714     bool isAbs = false;
4715     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4716
4717     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4718          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4719         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4720       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4721     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4722              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4723       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4724
4725     if (isAbs) {
4726       EVT VT = LHS.getValueType();
4727       SDValue Shift = DAG.getNode(
4728           ISD::SRA, DL, VT, LHS,
4729           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4730       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4731       AddToWorklist(Shift.getNode());
4732       AddToWorklist(Add.getNode());
4733       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4734     }
4735   }
4736
4737   // If the VSELECT result requires splitting and the mask is provided by a
4738   // SETCC, then split both nodes and its operands before legalization. This
4739   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4740   // and enables future optimizations (e.g. min/max pattern matching on X86).
4741   if (N0.getOpcode() == ISD::SETCC) {
4742     EVT VT = N->getValueType(0);
4743
4744     // Check if any splitting is required.
4745     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4746         TargetLowering::TypeSplitVector)
4747       return SDValue();
4748
4749     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4750     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4751     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4752     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4753
4754     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4755     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4756
4757     // Add the new VSELECT nodes to the work list in case they need to be split
4758     // again.
4759     AddToWorklist(Lo.getNode());
4760     AddToWorklist(Hi.getNode());
4761
4762     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4763   }
4764
4765   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4766   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4767     return N1;
4768   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4769   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4770     return N2;
4771
4772   // The ConvertSelectToConcatVector function is assuming both the above
4773   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4774   // and addressed.
4775   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4776       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4777       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4778     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4779     if (CV.getNode())
4780       return CV;
4781   }
4782
4783   return SDValue();
4784 }
4785
4786 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4787   SDValue N0 = N->getOperand(0);
4788   SDValue N1 = N->getOperand(1);
4789   SDValue N2 = N->getOperand(2);
4790   SDValue N3 = N->getOperand(3);
4791   SDValue N4 = N->getOperand(4);
4792   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4793
4794   // fold select_cc lhs, rhs, x, x, cc -> x
4795   if (N2 == N3)
4796     return N2;
4797
4798   // Determine if the condition we're dealing with is constant
4799   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4800                               N0, N1, CC, SDLoc(N), false);
4801   if (SCC.getNode()) {
4802     AddToWorklist(SCC.getNode());
4803
4804     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4805       if (!SCCC->isNullValue())
4806         return N2;    // cond always true -> true val
4807       else
4808         return N3;    // cond always false -> false val
4809     }
4810
4811     // Fold to a simpler select_cc
4812     if (SCC.getOpcode() == ISD::SETCC)
4813       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4814                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4815                          SCC.getOperand(2));
4816   }
4817
4818   // If we can fold this based on the true/false value, do so.
4819   if (SimplifySelectOps(N, N2, N3))
4820     return SDValue(N, 0);  // Don't revisit N.
4821
4822   // fold select_cc into other things, such as min/max/abs
4823   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4824 }
4825
4826 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4827   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4828                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4829                        SDLoc(N));
4830 }
4831
4832 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4833 // dag node into a ConstantSDNode or a build_vector of constants.
4834 // This function is called by the DAGCombiner when visiting sext/zext/aext
4835 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4836 // Vector extends are not folded if operations are legal; this is to
4837 // avoid introducing illegal build_vector dag nodes.
4838 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4839                                          SelectionDAG &DAG, bool LegalTypes,
4840                                          bool LegalOperations) {
4841   unsigned Opcode = N->getOpcode();
4842   SDValue N0 = N->getOperand(0);
4843   EVT VT = N->getValueType(0);
4844
4845   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4846          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4847
4848   // fold (sext c1) -> c1
4849   // fold (zext c1) -> c1
4850   // fold (aext c1) -> c1
4851   if (isa<ConstantSDNode>(N0))
4852     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4853
4854   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4855   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4856   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4857   EVT SVT = VT.getScalarType();
4858   if (!(VT.isVector() &&
4859       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4860       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4861     return nullptr;
4862
4863   // We can fold this node into a build_vector.
4864   unsigned VTBits = SVT.getSizeInBits();
4865   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4866   unsigned ShAmt = VTBits - EVTBits;
4867   SmallVector<SDValue, 8> Elts;
4868   unsigned NumElts = N0->getNumOperands();
4869   SDLoc DL(N);
4870
4871   for (unsigned i=0; i != NumElts; ++i) {
4872     SDValue Op = N0->getOperand(i);
4873     if (Op->getOpcode() == ISD::UNDEF) {
4874       Elts.push_back(DAG.getUNDEF(SVT));
4875       continue;
4876     }
4877
4878     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4879     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4880     if (Opcode == ISD::SIGN_EXTEND)
4881       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4882                                      SVT));
4883     else
4884       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4885                                      SVT));
4886   }
4887
4888   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4889 }
4890
4891 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4892 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4893 // transformation. Returns true if extension are possible and the above
4894 // mentioned transformation is profitable.
4895 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4896                                     unsigned ExtOpc,
4897                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4898                                     const TargetLowering &TLI) {
4899   bool HasCopyToRegUses = false;
4900   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4901   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4902                             UE = N0.getNode()->use_end();
4903        UI != UE; ++UI) {
4904     SDNode *User = *UI;
4905     if (User == N)
4906       continue;
4907     if (UI.getUse().getResNo() != N0.getResNo())
4908       continue;
4909     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4910     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4911       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4912       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4913         // Sign bits will be lost after a zext.
4914         return false;
4915       bool Add = false;
4916       for (unsigned i = 0; i != 2; ++i) {
4917         SDValue UseOp = User->getOperand(i);
4918         if (UseOp == N0)
4919           continue;
4920         if (!isa<ConstantSDNode>(UseOp))
4921           return false;
4922         Add = true;
4923       }
4924       if (Add)
4925         ExtendNodes.push_back(User);
4926       continue;
4927     }
4928     // If truncates aren't free and there are users we can't
4929     // extend, it isn't worthwhile.
4930     if (!isTruncFree)
4931       return false;
4932     // Remember if this value is live-out.
4933     if (User->getOpcode() == ISD::CopyToReg)
4934       HasCopyToRegUses = true;
4935   }
4936
4937   if (HasCopyToRegUses) {
4938     bool BothLiveOut = false;
4939     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4940          UI != UE; ++UI) {
4941       SDUse &Use = UI.getUse();
4942       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4943         BothLiveOut = true;
4944         break;
4945       }
4946     }
4947     if (BothLiveOut)
4948       // Both unextended and extended values are live out. There had better be
4949       // a good reason for the transformation.
4950       return ExtendNodes.size();
4951   }
4952   return true;
4953 }
4954
4955 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4956                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4957                                   ISD::NodeType ExtType) {
4958   // Extend SetCC uses if necessary.
4959   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4960     SDNode *SetCC = SetCCs[i];
4961     SmallVector<SDValue, 4> Ops;
4962
4963     for (unsigned j = 0; j != 2; ++j) {
4964       SDValue SOp = SetCC->getOperand(j);
4965       if (SOp == Trunc)
4966         Ops.push_back(ExtLoad);
4967       else
4968         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4969     }
4970
4971     Ops.push_back(SetCC->getOperand(2));
4972     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4973   }
4974 }
4975
4976 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4977   SDValue N0 = N->getOperand(0);
4978   EVT VT = N->getValueType(0);
4979
4980   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4981                                               LegalOperations))
4982     return SDValue(Res, 0);
4983
4984   // fold (sext (sext x)) -> (sext x)
4985   // fold (sext (aext x)) -> (sext x)
4986   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4987     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4988                        N0.getOperand(0));
4989
4990   if (N0.getOpcode() == ISD::TRUNCATE) {
4991     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4992     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4993     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4994     if (NarrowLoad.getNode()) {
4995       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4996       if (NarrowLoad.getNode() != N0.getNode()) {
4997         CombineTo(N0.getNode(), NarrowLoad);
4998         // CombineTo deleted the truncate, if needed, but not what's under it.
4999         AddToWorklist(oye);
5000       }
5001       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5002     }
5003
5004     // See if the value being truncated is already sign extended.  If so, just
5005     // eliminate the trunc/sext pair.
5006     SDValue Op = N0.getOperand(0);
5007     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5008     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5009     unsigned DestBits = VT.getScalarType().getSizeInBits();
5010     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5011
5012     if (OpBits == DestBits) {
5013       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5014       // bits, it is already ready.
5015       if (NumSignBits > DestBits-MidBits)
5016         return Op;
5017     } else if (OpBits < DestBits) {
5018       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5019       // bits, just sext from i32.
5020       if (NumSignBits > OpBits-MidBits)
5021         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5022     } else {
5023       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5024       // bits, just truncate to i32.
5025       if (NumSignBits > OpBits-MidBits)
5026         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5027     }
5028
5029     // fold (sext (truncate x)) -> (sextinreg x).
5030     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5031                                                  N0.getValueType())) {
5032       if (OpBits < DestBits)
5033         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5034       else if (OpBits > DestBits)
5035         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5036       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5037                          DAG.getValueType(N0.getValueType()));
5038     }
5039   }
5040
5041   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5042   // None of the supported targets knows how to perform load and sign extend
5043   // on vectors in one instruction.  We only perform this transformation on
5044   // scalars.
5045   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5046       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5047       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5048        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5049     bool DoXform = true;
5050     SmallVector<SDNode*, 4> SetCCs;
5051     if (!N0.hasOneUse())
5052       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5053     if (DoXform) {
5054       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5055       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5056                                        LN0->getChain(),
5057                                        LN0->getBasePtr(), N0.getValueType(),
5058                                        LN0->getMemOperand());
5059       CombineTo(N, ExtLoad);
5060       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5061                                   N0.getValueType(), ExtLoad);
5062       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5063       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5064                       ISD::SIGN_EXTEND);
5065       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5066     }
5067   }
5068
5069   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5070   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5071   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5072       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5073     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5074     EVT MemVT = LN0->getMemoryVT();
5075     if ((!LegalOperations && !LN0->isVolatile()) ||
5076         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5077       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5078                                        LN0->getChain(),
5079                                        LN0->getBasePtr(), MemVT,
5080                                        LN0->getMemOperand());
5081       CombineTo(N, ExtLoad);
5082       CombineTo(N0.getNode(),
5083                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5084                             N0.getValueType(), ExtLoad),
5085                 ExtLoad.getValue(1));
5086       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5087     }
5088   }
5089
5090   // fold (sext (and/or/xor (load x), cst)) ->
5091   //      (and/or/xor (sextload x), (sext cst))
5092   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5093        N0.getOpcode() == ISD::XOR) &&
5094       isa<LoadSDNode>(N0.getOperand(0)) &&
5095       N0.getOperand(1).getOpcode() == ISD::Constant &&
5096       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5097       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5098     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5099     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5100       bool DoXform = true;
5101       SmallVector<SDNode*, 4> SetCCs;
5102       if (!N0.hasOneUse())
5103         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5104                                           SetCCs, TLI);
5105       if (DoXform) {
5106         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5107                                          LN0->getChain(), LN0->getBasePtr(),
5108                                          LN0->getMemoryVT(),
5109                                          LN0->getMemOperand());
5110         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5111         Mask = Mask.sext(VT.getSizeInBits());
5112         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5113                                   ExtLoad, DAG.getConstant(Mask, VT));
5114         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5115                                     SDLoc(N0.getOperand(0)),
5116                                     N0.getOperand(0).getValueType(), ExtLoad);
5117         CombineTo(N, And);
5118         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5119         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5120                         ISD::SIGN_EXTEND);
5121         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5122       }
5123     }
5124   }
5125
5126   if (N0.getOpcode() == ISD::SETCC) {
5127     EVT N0VT = N0.getOperand(0).getValueType();
5128     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5129     // Only do this before legalize for now.
5130     if (VT.isVector() && !LegalOperations &&
5131         TLI.getBooleanContents(N0VT) ==
5132             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5133       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5134       // of the same size as the compared operands. Only optimize sext(setcc())
5135       // if this is the case.
5136       EVT SVT = getSetCCResultType(N0VT);
5137
5138       // We know that the # elements of the results is the same as the
5139       // # elements of the compare (and the # elements of the compare result
5140       // for that matter).  Check to see that they are the same size.  If so,
5141       // we know that the element size of the sext'd result matches the
5142       // element size of the compare operands.
5143       if (VT.getSizeInBits() == SVT.getSizeInBits())
5144         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5145                              N0.getOperand(1),
5146                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5147
5148       // If the desired elements are smaller or larger than the source
5149       // elements we can use a matching integer vector type and then
5150       // truncate/sign extend
5151       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5152       if (SVT == MatchingVectorType) {
5153         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5154                                N0.getOperand(0), N0.getOperand(1),
5155                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5156         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5157       }
5158     }
5159
5160     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5161     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5162     SDValue NegOne =
5163       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5164     SDValue SCC =
5165       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5166                        NegOne, DAG.getConstant(0, VT),
5167                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5168     if (SCC.getNode()) return SCC;
5169
5170     if (!VT.isVector()) {
5171       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5172       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5173         SDLoc DL(N);
5174         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5175         SDValue SetCC = DAG.getSetCC(DL,
5176                                      SetCCVT,
5177                                      N0.getOperand(0), N0.getOperand(1), CC);
5178         EVT SelectVT = getSetCCResultType(VT);
5179         return DAG.getSelect(DL, VT,
5180                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5181                              NegOne, DAG.getConstant(0, VT));
5182
5183       }
5184     }
5185   }
5186
5187   // fold (sext x) -> (zext x) if the sign bit is known zero.
5188   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5189       DAG.SignBitIsZero(N0))
5190     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5191
5192   return SDValue();
5193 }
5194
5195 // isTruncateOf - If N is a truncate of some other value, return true, record
5196 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5197 // This function computes KnownZero to avoid a duplicated call to
5198 // computeKnownBits in the caller.
5199 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5200                          APInt &KnownZero) {
5201   APInt KnownOne;
5202   if (N->getOpcode() == ISD::TRUNCATE) {
5203     Op = N->getOperand(0);
5204     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5205     return true;
5206   }
5207
5208   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5209       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5210     return false;
5211
5212   SDValue Op0 = N->getOperand(0);
5213   SDValue Op1 = N->getOperand(1);
5214   assert(Op0.getValueType() == Op1.getValueType());
5215
5216   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5217   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5218   if (COp0 && COp0->isNullValue())
5219     Op = Op1;
5220   else if (COp1 && COp1->isNullValue())
5221     Op = Op0;
5222   else
5223     return false;
5224
5225   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5226
5227   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5228     return false;
5229
5230   return true;
5231 }
5232
5233 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5234   SDValue N0 = N->getOperand(0);
5235   EVT VT = N->getValueType(0);
5236
5237   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5238                                               LegalOperations))
5239     return SDValue(Res, 0);
5240
5241   // fold (zext (zext x)) -> (zext x)
5242   // fold (zext (aext x)) -> (zext x)
5243   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5244     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5245                        N0.getOperand(0));
5246
5247   // fold (zext (truncate x)) -> (zext x) or
5248   //      (zext (truncate x)) -> (truncate x)
5249   // This is valid when the truncated bits of x are already zero.
5250   // FIXME: We should extend this to work for vectors too.
5251   SDValue Op;
5252   APInt KnownZero;
5253   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5254     APInt TruncatedBits =
5255       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5256       APInt(Op.getValueSizeInBits(), 0) :
5257       APInt::getBitsSet(Op.getValueSizeInBits(),
5258                         N0.getValueSizeInBits(),
5259                         std::min(Op.getValueSizeInBits(),
5260                                  VT.getSizeInBits()));
5261     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5262       if (VT.bitsGT(Op.getValueType()))
5263         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5264       if (VT.bitsLT(Op.getValueType()))
5265         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5266
5267       return Op;
5268     }
5269   }
5270
5271   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5272   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5273   if (N0.getOpcode() == ISD::TRUNCATE) {
5274     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5275     if (NarrowLoad.getNode()) {
5276       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5277       if (NarrowLoad.getNode() != N0.getNode()) {
5278         CombineTo(N0.getNode(), NarrowLoad);
5279         // CombineTo deleted the truncate, if needed, but not what's under it.
5280         AddToWorklist(oye);
5281       }
5282       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5283     }
5284   }
5285
5286   // fold (zext (truncate x)) -> (and x, mask)
5287   if (N0.getOpcode() == ISD::TRUNCATE &&
5288       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5289
5290     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5291     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5292     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5293     if (NarrowLoad.getNode()) {
5294       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5295       if (NarrowLoad.getNode() != N0.getNode()) {
5296         CombineTo(N0.getNode(), NarrowLoad);
5297         // CombineTo deleted the truncate, if needed, but not what's under it.
5298         AddToWorklist(oye);
5299       }
5300       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5301     }
5302
5303     SDValue Op = N0.getOperand(0);
5304     if (Op.getValueType().bitsLT(VT)) {
5305       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5306       AddToWorklist(Op.getNode());
5307     } else if (Op.getValueType().bitsGT(VT)) {
5308       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5309       AddToWorklist(Op.getNode());
5310     }
5311     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5312                                   N0.getValueType().getScalarType());
5313   }
5314
5315   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5316   // if either of the casts is not free.
5317   if (N0.getOpcode() == ISD::AND &&
5318       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5319       N0.getOperand(1).getOpcode() == ISD::Constant &&
5320       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5321                            N0.getValueType()) ||
5322        !TLI.isZExtFree(N0.getValueType(), VT))) {
5323     SDValue X = N0.getOperand(0).getOperand(0);
5324     if (X.getValueType().bitsLT(VT)) {
5325       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5326     } else if (X.getValueType().bitsGT(VT)) {
5327       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5328     }
5329     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5330     Mask = Mask.zext(VT.getSizeInBits());
5331     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5332                        X, DAG.getConstant(Mask, VT));
5333   }
5334
5335   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5336   // None of the supported targets knows how to perform load and vector_zext
5337   // on vectors in one instruction.  We only perform this transformation on
5338   // scalars.
5339   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5340       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5341       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5342        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5343     bool DoXform = true;
5344     SmallVector<SDNode*, 4> SetCCs;
5345     if (!N0.hasOneUse())
5346       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5347     if (DoXform) {
5348       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5349       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5350                                        LN0->getChain(),
5351                                        LN0->getBasePtr(), N0.getValueType(),
5352                                        LN0->getMemOperand());
5353       CombineTo(N, ExtLoad);
5354       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5355                                   N0.getValueType(), ExtLoad);
5356       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5357
5358       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5359                       ISD::ZERO_EXTEND);
5360       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5361     }
5362   }
5363
5364   // fold (zext (and/or/xor (load x), cst)) ->
5365   //      (and/or/xor (zextload x), (zext cst))
5366   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5367        N0.getOpcode() == ISD::XOR) &&
5368       isa<LoadSDNode>(N0.getOperand(0)) &&
5369       N0.getOperand(1).getOpcode() == ISD::Constant &&
5370       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5371       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5372     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5373     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5374       bool DoXform = true;
5375       SmallVector<SDNode*, 4> SetCCs;
5376       if (!N0.hasOneUse())
5377         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5378                                           SetCCs, TLI);
5379       if (DoXform) {
5380         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5381                                          LN0->getChain(), LN0->getBasePtr(),
5382                                          LN0->getMemoryVT(),
5383                                          LN0->getMemOperand());
5384         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5385         Mask = Mask.zext(VT.getSizeInBits());
5386         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5387                                   ExtLoad, DAG.getConstant(Mask, VT));
5388         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5389                                     SDLoc(N0.getOperand(0)),
5390                                     N0.getOperand(0).getValueType(), ExtLoad);
5391         CombineTo(N, And);
5392         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
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
5400   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5401   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5402   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5403       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5404     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5405     EVT MemVT = LN0->getMemoryVT();
5406     if ((!LegalOperations && !LN0->isVolatile()) ||
5407         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5408       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5409                                        LN0->getChain(),
5410                                        LN0->getBasePtr(), MemVT,
5411                                        LN0->getMemOperand());
5412       CombineTo(N, ExtLoad);
5413       CombineTo(N0.getNode(),
5414                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5415                             ExtLoad),
5416                 ExtLoad.getValue(1));
5417       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5418     }
5419   }
5420
5421   if (N0.getOpcode() == ISD::SETCC) {
5422     if (!LegalOperations && VT.isVector() &&
5423         N0.getValueType().getVectorElementType() == MVT::i1) {
5424       EVT N0VT = N0.getOperand(0).getValueType();
5425       if (getSetCCResultType(N0VT) == N0.getValueType())
5426         return SDValue();
5427
5428       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5429       // Only do this before legalize for now.
5430       EVT EltVT = VT.getVectorElementType();
5431       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5432                                     DAG.getConstant(1, EltVT));
5433       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5434         // We know that the # elements of the results is the same as the
5435         // # elements of the compare (and the # elements of the compare result
5436         // for that matter).  Check to see that they are the same size.  If so,
5437         // we know that the element size of the sext'd result matches the
5438         // element size of the compare operands.
5439         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5440                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5441                                          N0.getOperand(1),
5442                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5443                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5444                                        OneOps));
5445
5446       // If the desired elements are smaller or larger than the source
5447       // elements we can use a matching integer vector type and then
5448       // truncate/sign extend
5449       EVT MatchingElementType =
5450         EVT::getIntegerVT(*DAG.getContext(),
5451                           N0VT.getScalarType().getSizeInBits());
5452       EVT MatchingVectorType =
5453         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5454                          N0VT.getVectorNumElements());
5455       SDValue VsetCC =
5456         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5457                       N0.getOperand(1),
5458                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5459       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5460                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5461                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5462     }
5463
5464     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5465     SDValue SCC =
5466       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5467                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5468                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5469     if (SCC.getNode()) return SCC;
5470   }
5471
5472   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5473   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5474       isa<ConstantSDNode>(N0.getOperand(1)) &&
5475       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5476       N0.hasOneUse()) {
5477     SDValue ShAmt = N0.getOperand(1);
5478     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5479     if (N0.getOpcode() == ISD::SHL) {
5480       SDValue InnerZExt = N0.getOperand(0);
5481       // If the original shl may be shifting out bits, do not perform this
5482       // transformation.
5483       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5484         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5485       if (ShAmtVal > KnownZeroBits)
5486         return SDValue();
5487     }
5488
5489     SDLoc DL(N);
5490
5491     // Ensure that the shift amount is wide enough for the shifted value.
5492     if (VT.getSizeInBits() >= 256)
5493       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5494
5495     return DAG.getNode(N0.getOpcode(), DL, VT,
5496                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5497                        ShAmt);
5498   }
5499
5500   return SDValue();
5501 }
5502
5503 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5504   SDValue N0 = N->getOperand(0);
5505   EVT VT = N->getValueType(0);
5506
5507   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5508                                               LegalOperations))
5509     return SDValue(Res, 0);
5510
5511   // fold (aext (aext x)) -> (aext x)
5512   // fold (aext (zext x)) -> (zext x)
5513   // fold (aext (sext x)) -> (sext x)
5514   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5515       N0.getOpcode() == ISD::ZERO_EXTEND ||
5516       N0.getOpcode() == ISD::SIGN_EXTEND)
5517     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5518
5519   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5520   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5521   if (N0.getOpcode() == ISD::TRUNCATE) {
5522     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5523     if (NarrowLoad.getNode()) {
5524       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5525       if (NarrowLoad.getNode() != N0.getNode()) {
5526         CombineTo(N0.getNode(), NarrowLoad);
5527         // CombineTo deleted the truncate, if needed, but not what's under it.
5528         AddToWorklist(oye);
5529       }
5530       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5531     }
5532   }
5533
5534   // fold (aext (truncate x))
5535   if (N0.getOpcode() == ISD::TRUNCATE) {
5536     SDValue TruncOp = N0.getOperand(0);
5537     if (TruncOp.getValueType() == VT)
5538       return TruncOp; // x iff x size == zext size.
5539     if (TruncOp.getValueType().bitsGT(VT))
5540       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5541     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5542   }
5543
5544   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5545   // if the trunc is not free.
5546   if (N0.getOpcode() == ISD::AND &&
5547       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5548       N0.getOperand(1).getOpcode() == ISD::Constant &&
5549       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5550                           N0.getValueType())) {
5551     SDValue X = N0.getOperand(0).getOperand(0);
5552     if (X.getValueType().bitsLT(VT)) {
5553       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5554     } else if (X.getValueType().bitsGT(VT)) {
5555       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5556     }
5557     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5558     Mask = Mask.zext(VT.getSizeInBits());
5559     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5560                        X, DAG.getConstant(Mask, VT));
5561   }
5562
5563   // fold (aext (load x)) -> (aext (truncate (extload x)))
5564   // None of the supported targets knows how to perform load and any_ext
5565   // on vectors in one instruction.  We only perform this transformation on
5566   // scalars.
5567   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5568       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5569       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5570     bool DoXform = true;
5571     SmallVector<SDNode*, 4> SetCCs;
5572     if (!N0.hasOneUse())
5573       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5574     if (DoXform) {
5575       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5576       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5577                                        LN0->getChain(),
5578                                        LN0->getBasePtr(), N0.getValueType(),
5579                                        LN0->getMemOperand());
5580       CombineTo(N, ExtLoad);
5581       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5582                                   N0.getValueType(), ExtLoad);
5583       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5584       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5585                       ISD::ANY_EXTEND);
5586       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5587     }
5588   }
5589
5590   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5591   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5592   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5593   if (N0.getOpcode() == ISD::LOAD &&
5594       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5595       N0.hasOneUse()) {
5596     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5597     ISD::LoadExtType ExtType = LN0->getExtensionType();
5598     EVT MemVT = LN0->getMemoryVT();
5599     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5600       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5601                                        VT, LN0->getChain(), LN0->getBasePtr(),
5602                                        MemVT, LN0->getMemOperand());
5603       CombineTo(N, ExtLoad);
5604       CombineTo(N0.getNode(),
5605                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5606                             N0.getValueType(), ExtLoad),
5607                 ExtLoad.getValue(1));
5608       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5609     }
5610   }
5611
5612   if (N0.getOpcode() == ISD::SETCC) {
5613     // For vectors:
5614     // aext(setcc) -> vsetcc
5615     // aext(setcc) -> truncate(vsetcc)
5616     // aext(setcc) -> aext(vsetcc)
5617     // Only do this before legalize for now.
5618     if (VT.isVector() && !LegalOperations) {
5619       EVT N0VT = N0.getOperand(0).getValueType();
5620         // We know that the # elements of the results is the same as the
5621         // # elements of the compare (and the # elements of the compare result
5622         // for that matter).  Check to see that they are the same size.  If so,
5623         // we know that the element size of the sext'd result matches the
5624         // element size of the compare operands.
5625       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5626         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5627                              N0.getOperand(1),
5628                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5629       // If the desired elements are smaller or larger than the source
5630       // elements we can use a matching integer vector type and then
5631       // truncate/any extend
5632       else {
5633         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5634         SDValue VsetCC =
5635           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5636                         N0.getOperand(1),
5637                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5638         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5639       }
5640     }
5641
5642     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5643     SDValue SCC =
5644       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5645                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5646                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5647     if (SCC.getNode())
5648       return SCC;
5649   }
5650
5651   return SDValue();
5652 }
5653
5654 /// GetDemandedBits - See if the specified operand can be simplified with the
5655 /// knowledge that only the bits specified by Mask are used.  If so, return the
5656 /// simpler operand, otherwise return a null SDValue.
5657 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5658   switch (V.getOpcode()) {
5659   default: break;
5660   case ISD::Constant: {
5661     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5662     assert(CV && "Const value should be ConstSDNode.");
5663     const APInt &CVal = CV->getAPIntValue();
5664     APInt NewVal = CVal & Mask;
5665     if (NewVal != CVal)
5666       return DAG.getConstant(NewVal, V.getValueType());
5667     break;
5668   }
5669   case ISD::OR:
5670   case ISD::XOR:
5671     // If the LHS or RHS don't contribute bits to the or, drop them.
5672     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5673       return V.getOperand(1);
5674     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5675       return V.getOperand(0);
5676     break;
5677   case ISD::SRL:
5678     // Only look at single-use SRLs.
5679     if (!V.getNode()->hasOneUse())
5680       break;
5681     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5682       // See if we can recursively simplify the LHS.
5683       unsigned Amt = RHSC->getZExtValue();
5684
5685       // Watch out for shift count overflow though.
5686       if (Amt >= Mask.getBitWidth()) break;
5687       APInt NewMask = Mask << Amt;
5688       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5689       if (SimplifyLHS.getNode())
5690         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5691                            SimplifyLHS, V.getOperand(1));
5692     }
5693   }
5694   return SDValue();
5695 }
5696
5697 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5698 /// bits and then truncated to a narrower type and where N is a multiple
5699 /// of number of bits of the narrower type, transform it to a narrower load
5700 /// from address + N / num of bits of new type. If the result is to be
5701 /// extended, also fold the extension to form a extending load.
5702 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5703   unsigned Opc = N->getOpcode();
5704
5705   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5706   SDValue N0 = N->getOperand(0);
5707   EVT VT = N->getValueType(0);
5708   EVT ExtVT = VT;
5709
5710   // This transformation isn't valid for vector loads.
5711   if (VT.isVector())
5712     return SDValue();
5713
5714   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5715   // extended to VT.
5716   if (Opc == ISD::SIGN_EXTEND_INREG) {
5717     ExtType = ISD::SEXTLOAD;
5718     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5719   } else if (Opc == ISD::SRL) {
5720     // Another special-case: SRL is basically zero-extending a narrower value.
5721     ExtType = ISD::ZEXTLOAD;
5722     N0 = SDValue(N, 0);
5723     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5724     if (!N01) return SDValue();
5725     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5726                               VT.getSizeInBits() - N01->getZExtValue());
5727   }
5728   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5729     return SDValue();
5730
5731   unsigned EVTBits = ExtVT.getSizeInBits();
5732
5733   // Do not generate loads of non-round integer types since these can
5734   // be expensive (and would be wrong if the type is not byte sized).
5735   if (!ExtVT.isRound())
5736     return SDValue();
5737
5738   unsigned ShAmt = 0;
5739   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5740     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5741       ShAmt = N01->getZExtValue();
5742       // Is the shift amount a multiple of size of VT?
5743       if ((ShAmt & (EVTBits-1)) == 0) {
5744         N0 = N0.getOperand(0);
5745         // Is the load width a multiple of size of VT?
5746         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5747           return SDValue();
5748       }
5749
5750       // At this point, we must have a load or else we can't do the transform.
5751       if (!isa<LoadSDNode>(N0)) return SDValue();
5752
5753       // Because a SRL must be assumed to *need* to zero-extend the high bits
5754       // (as opposed to anyext the high bits), we can't combine the zextload
5755       // lowering of SRL and an sextload.
5756       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5757         return SDValue();
5758
5759       // If the shift amount is larger than the input type then we're not
5760       // accessing any of the loaded bytes.  If the load was a zextload/extload
5761       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5762       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5763         return SDValue();
5764     }
5765   }
5766
5767   // If the load is shifted left (and the result isn't shifted back right),
5768   // we can fold the truncate through the shift.
5769   unsigned ShLeftAmt = 0;
5770   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5771       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5772     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5773       ShLeftAmt = N01->getZExtValue();
5774       N0 = N0.getOperand(0);
5775     }
5776   }
5777
5778   // If we haven't found a load, we can't narrow it.  Don't transform one with
5779   // multiple uses, this would require adding a new load.
5780   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5781     return SDValue();
5782
5783   // Don't change the width of a volatile load.
5784   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5785   if (LN0->isVolatile())
5786     return SDValue();
5787
5788   // Verify that we are actually reducing a load width here.
5789   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5790     return SDValue();
5791
5792   // For the transform to be legal, the load must produce only two values
5793   // (the value loaded and the chain).  Don't transform a pre-increment
5794   // load, for example, which produces an extra value.  Otherwise the
5795   // transformation is not equivalent, and the downstream logic to replace
5796   // uses gets things wrong.
5797   if (LN0->getNumValues() > 2)
5798     return SDValue();
5799
5800   // If the load that we're shrinking is an extload and we're not just
5801   // discarding the extension we can't simply shrink the load. Bail.
5802   // TODO: It would be possible to merge the extensions in some cases.
5803   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5804       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5805     return SDValue();
5806
5807   EVT PtrType = N0.getOperand(1).getValueType();
5808
5809   if (PtrType == MVT::Untyped || PtrType.isExtended())
5810     // It's not possible to generate a constant of extended or untyped type.
5811     return SDValue();
5812
5813   // For big endian targets, we need to adjust the offset to the pointer to
5814   // load the correct bytes.
5815   if (TLI.isBigEndian()) {
5816     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5817     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5818     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5819   }
5820
5821   uint64_t PtrOff = ShAmt / 8;
5822   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5823   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5824                                PtrType, LN0->getBasePtr(),
5825                                DAG.getConstant(PtrOff, PtrType));
5826   AddToWorklist(NewPtr.getNode());
5827
5828   SDValue Load;
5829   if (ExtType == ISD::NON_EXTLOAD)
5830     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5831                         LN0->getPointerInfo().getWithOffset(PtrOff),
5832                         LN0->isVolatile(), LN0->isNonTemporal(),
5833                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5834   else
5835     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5836                           LN0->getPointerInfo().getWithOffset(PtrOff),
5837                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5838                           NewAlign, LN0->getAAInfo());
5839
5840   // Replace the old load's chain with the new load's chain.
5841   WorklistRemover DeadNodes(*this);
5842   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5843
5844   // Shift the result left, if we've swallowed a left shift.
5845   SDValue Result = Load;
5846   if (ShLeftAmt != 0) {
5847     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5848     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5849       ShImmTy = VT;
5850     // If the shift amount is as large as the result size (but, presumably,
5851     // no larger than the source) then the useful bits of the result are
5852     // zero; we can't simply return the shortened shift, because the result
5853     // of that operation is undefined.
5854     if (ShLeftAmt >= VT.getSizeInBits())
5855       Result = DAG.getConstant(0, VT);
5856     else
5857       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5858                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5859   }
5860
5861   // Return the new loaded value.
5862   return Result;
5863 }
5864
5865 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5866   SDValue N0 = N->getOperand(0);
5867   SDValue N1 = N->getOperand(1);
5868   EVT VT = N->getValueType(0);
5869   EVT EVT = cast<VTSDNode>(N1)->getVT();
5870   unsigned VTBits = VT.getScalarType().getSizeInBits();
5871   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5872
5873   // fold (sext_in_reg c1) -> c1
5874   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5875     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5876
5877   // If the input is already sign extended, just drop the extension.
5878   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5879     return N0;
5880
5881   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5882   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5883       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5884     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5885                        N0.getOperand(0), N1);
5886
5887   // fold (sext_in_reg (sext x)) -> (sext x)
5888   // fold (sext_in_reg (aext x)) -> (sext x)
5889   // if x is small enough.
5890   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5891     SDValue N00 = N0.getOperand(0);
5892     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5893         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5894       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5895   }
5896
5897   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5898   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5899     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5900
5901   // fold operands of sext_in_reg based on knowledge that the top bits are not
5902   // demanded.
5903   if (SimplifyDemandedBits(SDValue(N, 0)))
5904     return SDValue(N, 0);
5905
5906   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5907   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5908   SDValue NarrowLoad = ReduceLoadWidth(N);
5909   if (NarrowLoad.getNode())
5910     return NarrowLoad;
5911
5912   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5913   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5914   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5915   if (N0.getOpcode() == ISD::SRL) {
5916     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5917       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5918         // We can turn this into an SRA iff the input to the SRL is already sign
5919         // extended enough.
5920         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5921         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5922           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5923                              N0.getOperand(0), N0.getOperand(1));
5924       }
5925   }
5926
5927   // fold (sext_inreg (extload x)) -> (sextload x)
5928   if (ISD::isEXTLoad(N0.getNode()) &&
5929       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5930       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5931       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5932        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5933     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5934     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5935                                      LN0->getChain(),
5936                                      LN0->getBasePtr(), EVT,
5937                                      LN0->getMemOperand());
5938     CombineTo(N, ExtLoad);
5939     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5940     AddToWorklist(ExtLoad.getNode());
5941     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5942   }
5943   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5944   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5945       N0.hasOneUse() &&
5946       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5947       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5948        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5949     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5950     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5951                                      LN0->getChain(),
5952                                      LN0->getBasePtr(), EVT,
5953                                      LN0->getMemOperand());
5954     CombineTo(N, ExtLoad);
5955     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5956     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5957   }
5958
5959   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5960   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5961     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5962                                        N0.getOperand(1), false);
5963     if (BSwap.getNode())
5964       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5965                          BSwap, N1);
5966   }
5967
5968   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5969   // into a build_vector.
5970   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5971     SmallVector<SDValue, 8> Elts;
5972     unsigned NumElts = N0->getNumOperands();
5973     unsigned ShAmt = VTBits - EVTBits;
5974
5975     for (unsigned i = 0; i != NumElts; ++i) {
5976       SDValue Op = N0->getOperand(i);
5977       if (Op->getOpcode() == ISD::UNDEF) {
5978         Elts.push_back(Op);
5979         continue;
5980       }
5981
5982       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5983       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5984       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5985                                      Op.getValueType()));
5986     }
5987
5988     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5989   }
5990
5991   return SDValue();
5992 }
5993
5994 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5995   SDValue N0 = N->getOperand(0);
5996   EVT VT = N->getValueType(0);
5997   bool isLE = TLI.isLittleEndian();
5998
5999   // noop truncate
6000   if (N0.getValueType() == N->getValueType(0))
6001     return N0;
6002   // fold (truncate c1) -> c1
6003   if (isa<ConstantSDNode>(N0))
6004     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6005   // fold (truncate (truncate x)) -> (truncate x)
6006   if (N0.getOpcode() == ISD::TRUNCATE)
6007     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6008   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6009   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6010       N0.getOpcode() == ISD::SIGN_EXTEND ||
6011       N0.getOpcode() == ISD::ANY_EXTEND) {
6012     if (N0.getOperand(0).getValueType().bitsLT(VT))
6013       // if the source is smaller than the dest, we still need an extend
6014       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6015                          N0.getOperand(0));
6016     if (N0.getOperand(0).getValueType().bitsGT(VT))
6017       // if the source is larger than the dest, than we just need the truncate
6018       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6019     // if the source and dest are the same type, we can drop both the extend
6020     // and the truncate.
6021     return N0.getOperand(0);
6022   }
6023
6024   // Fold extract-and-trunc into a narrow extract. For example:
6025   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6026   //   i32 y = TRUNCATE(i64 x)
6027   //        -- becomes --
6028   //   v16i8 b = BITCAST (v2i64 val)
6029   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6030   //
6031   // Note: We only run this optimization after type legalization (which often
6032   // creates this pattern) and before operation legalization after which
6033   // we need to be more careful about the vector instructions that we generate.
6034   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6035       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6036
6037     EVT VecTy = N0.getOperand(0).getValueType();
6038     EVT ExTy = N0.getValueType();
6039     EVT TrTy = N->getValueType(0);
6040
6041     unsigned NumElem = VecTy.getVectorNumElements();
6042     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6043
6044     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6045     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6046
6047     SDValue EltNo = N0->getOperand(1);
6048     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6049       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6050       EVT IndexTy = TLI.getVectorIdxTy();
6051       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6052
6053       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6054                               NVT, N0.getOperand(0));
6055
6056       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6057                          SDLoc(N), TrTy, V,
6058                          DAG.getConstant(Index, IndexTy));
6059     }
6060   }
6061
6062   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6063   if (N0.getOpcode() == ISD::SELECT) {
6064     EVT SrcVT = N0.getValueType();
6065     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6066         TLI.isTruncateFree(SrcVT, VT)) {
6067       SDLoc SL(N0);
6068       SDValue Cond = N0.getOperand(0);
6069       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6070       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6071       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6072     }
6073   }
6074
6075   // Fold a series of buildvector, bitcast, and truncate if possible.
6076   // For example fold
6077   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6078   //   (2xi32 (buildvector x, y)).
6079   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6080       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6081       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6082       N0.getOperand(0).hasOneUse()) {
6083
6084     SDValue BuildVect = N0.getOperand(0);
6085     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6086     EVT TruncVecEltTy = VT.getVectorElementType();
6087
6088     // Check that the element types match.
6089     if (BuildVectEltTy == TruncVecEltTy) {
6090       // Now we only need to compute the offset of the truncated elements.
6091       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6092       unsigned TruncVecNumElts = VT.getVectorNumElements();
6093       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6094
6095       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6096              "Invalid number of elements");
6097
6098       SmallVector<SDValue, 8> Opnds;
6099       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6100         Opnds.push_back(BuildVect.getOperand(i));
6101
6102       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6103     }
6104   }
6105
6106   // See if we can simplify the input to this truncate through knowledge that
6107   // only the low bits are being used.
6108   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6109   // Currently we only perform this optimization on scalars because vectors
6110   // may have different active low bits.
6111   if (!VT.isVector()) {
6112     SDValue Shorter =
6113       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6114                                                VT.getSizeInBits()));
6115     if (Shorter.getNode())
6116       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6117   }
6118   // fold (truncate (load x)) -> (smaller load x)
6119   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6120   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6121     SDValue Reduced = ReduceLoadWidth(N);
6122     if (Reduced.getNode())
6123       return Reduced;
6124     // Handle the case where the load remains an extending load even
6125     // after truncation.
6126     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6127       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6128       if (!LN0->isVolatile() &&
6129           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6130         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6131                                          VT, LN0->getChain(), LN0->getBasePtr(),
6132                                          LN0->getMemoryVT(),
6133                                          LN0->getMemOperand());
6134         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6135         return NewLoad;
6136       }
6137     }
6138   }
6139   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6140   // where ... are all 'undef'.
6141   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6142     SmallVector<EVT, 8> VTs;
6143     SDValue V;
6144     unsigned Idx = 0;
6145     unsigned NumDefs = 0;
6146
6147     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6148       SDValue X = N0.getOperand(i);
6149       if (X.getOpcode() != ISD::UNDEF) {
6150         V = X;
6151         Idx = i;
6152         NumDefs++;
6153       }
6154       // Stop if more than one members are non-undef.
6155       if (NumDefs > 1)
6156         break;
6157       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6158                                      VT.getVectorElementType(),
6159                                      X.getValueType().getVectorNumElements()));
6160     }
6161
6162     if (NumDefs == 0)
6163       return DAG.getUNDEF(VT);
6164
6165     if (NumDefs == 1) {
6166       assert(V.getNode() && "The single defined operand is empty!");
6167       SmallVector<SDValue, 8> Opnds;
6168       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6169         if (i != Idx) {
6170           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6171           continue;
6172         }
6173         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6174         AddToWorklist(NV.getNode());
6175         Opnds.push_back(NV);
6176       }
6177       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6178     }
6179   }
6180
6181   // Simplify the operands using demanded-bits information.
6182   if (!VT.isVector() &&
6183       SimplifyDemandedBits(SDValue(N, 0)))
6184     return SDValue(N, 0);
6185
6186   return SDValue();
6187 }
6188
6189 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6190   SDValue Elt = N->getOperand(i);
6191   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6192     return Elt.getNode();
6193   return Elt.getOperand(Elt.getResNo()).getNode();
6194 }
6195
6196 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6197 /// if load locations are consecutive.
6198 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6199   assert(N->getOpcode() == ISD::BUILD_PAIR);
6200
6201   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6202   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6203   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6204       LD1->getAddressSpace() != LD2->getAddressSpace())
6205     return SDValue();
6206   EVT LD1VT = LD1->getValueType(0);
6207
6208   if (ISD::isNON_EXTLoad(LD2) &&
6209       LD2->hasOneUse() &&
6210       // If both are volatile this would reduce the number of volatile loads.
6211       // If one is volatile it might be ok, but play conservative and bail out.
6212       !LD1->isVolatile() &&
6213       !LD2->isVolatile() &&
6214       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6215     unsigned Align = LD1->getAlignment();
6216     unsigned NewAlign = TLI.getDataLayout()->
6217       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6218
6219     if (NewAlign <= Align &&
6220         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6221       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6222                          LD1->getBasePtr(), LD1->getPointerInfo(),
6223                          false, false, false, Align);
6224   }
6225
6226   return SDValue();
6227 }
6228
6229 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6230   SDValue N0 = N->getOperand(0);
6231   EVT VT = N->getValueType(0);
6232
6233   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6234   // Only do this before legalize, since afterward the target may be depending
6235   // on the bitconvert.
6236   // First check to see if this is all constant.
6237   if (!LegalTypes &&
6238       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6239       VT.isVector()) {
6240     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6241
6242     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6243     assert(!DestEltVT.isVector() &&
6244            "Element type of vector ValueType must not be vector!");
6245     if (isSimple)
6246       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6247   }
6248
6249   // If the input is a constant, let getNode fold it.
6250   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6251     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6252     if (Res.getNode() != N) {
6253       if (!LegalOperations ||
6254           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6255         return Res;
6256
6257       // Folding it resulted in an illegal node, and it's too late to
6258       // do that. Clean up the old node and forego the transformation.
6259       // Ideally this won't happen very often, because instcombine
6260       // and the earlier dagcombine runs (where illegal nodes are
6261       // permitted) should have folded most of them already.
6262       DAG.DeleteNode(Res.getNode());
6263     }
6264   }
6265
6266   // (conv (conv x, t1), t2) -> (conv x, t2)
6267   if (N0.getOpcode() == ISD::BITCAST)
6268     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6269                        N0.getOperand(0));
6270
6271   // fold (conv (load x)) -> (load (conv*)x)
6272   // If the resultant load doesn't need a higher alignment than the original!
6273   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6274       // Do not change the width of a volatile load.
6275       !cast<LoadSDNode>(N0)->isVolatile() &&
6276       // Do not remove the cast if the types differ in endian layout.
6277       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6278       TLI.hasBigEndianPartOrdering(VT) &&
6279       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6280       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6281     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6282     unsigned Align = TLI.getDataLayout()->
6283       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6284     unsigned OrigAlign = LN0->getAlignment();
6285
6286     if (Align <= OrigAlign) {
6287       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6288                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6289                                  LN0->isVolatile(), LN0->isNonTemporal(),
6290                                  LN0->isInvariant(), OrigAlign,
6291                                  LN0->getAAInfo());
6292       AddToWorklist(N);
6293       CombineTo(N0.getNode(),
6294                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6295                             N0.getValueType(), Load),
6296                 Load.getValue(1));
6297       return Load;
6298     }
6299   }
6300
6301   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6302   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6303   // This often reduces constant pool loads.
6304   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6305        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6306       N0.getNode()->hasOneUse() && VT.isInteger() &&
6307       !VT.isVector() && !N0.getValueType().isVector()) {
6308     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6309                                   N0.getOperand(0));
6310     AddToWorklist(NewConv.getNode());
6311
6312     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6313     if (N0.getOpcode() == ISD::FNEG)
6314       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6315                          NewConv, DAG.getConstant(SignBit, VT));
6316     assert(N0.getOpcode() == ISD::FABS);
6317     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6318                        NewConv, DAG.getConstant(~SignBit, VT));
6319   }
6320
6321   // fold (bitconvert (fcopysign cst, x)) ->
6322   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6323   // Note that we don't handle (copysign x, cst) because this can always be
6324   // folded to an fneg or fabs.
6325   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6326       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6327       VT.isInteger() && !VT.isVector()) {
6328     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6329     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6330     if (isTypeLegal(IntXVT)) {
6331       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6332                               IntXVT, N0.getOperand(1));
6333       AddToWorklist(X.getNode());
6334
6335       // If X has a different width than the result/lhs, sext it or truncate it.
6336       unsigned VTWidth = VT.getSizeInBits();
6337       if (OrigXWidth < VTWidth) {
6338         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6339         AddToWorklist(X.getNode());
6340       } else if (OrigXWidth > VTWidth) {
6341         // To get the sign bit in the right place, we have to shift it right
6342         // before truncating.
6343         X = DAG.getNode(ISD::SRL, SDLoc(X),
6344                         X.getValueType(), X,
6345                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6346         AddToWorklist(X.getNode());
6347         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6348         AddToWorklist(X.getNode());
6349       }
6350
6351       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6352       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6353                       X, DAG.getConstant(SignBit, VT));
6354       AddToWorklist(X.getNode());
6355
6356       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6357                                 VT, N0.getOperand(0));
6358       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6359                         Cst, DAG.getConstant(~SignBit, VT));
6360       AddToWorklist(Cst.getNode());
6361
6362       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6363     }
6364   }
6365
6366   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6367   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6368     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6369     if (CombineLD.getNode())
6370       return CombineLD;
6371   }
6372
6373   return SDValue();
6374 }
6375
6376 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6377   EVT VT = N->getValueType(0);
6378   return CombineConsecutiveLoads(N, VT);
6379 }
6380
6381 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6382 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6383 /// destination element value type.
6384 SDValue DAGCombiner::
6385 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6386   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6387
6388   // If this is already the right type, we're done.
6389   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6390
6391   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6392   unsigned DstBitSize = DstEltVT.getSizeInBits();
6393
6394   // If this is a conversion of N elements of one type to N elements of another
6395   // type, convert each element.  This handles FP<->INT cases.
6396   if (SrcBitSize == DstBitSize) {
6397     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6398                               BV->getValueType(0).getVectorNumElements());
6399
6400     // Due to the FP element handling below calling this routine recursively,
6401     // we can end up with a scalar-to-vector node here.
6402     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6403       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6404                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6405                                      DstEltVT, BV->getOperand(0)));
6406
6407     SmallVector<SDValue, 8> Ops;
6408     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6409       SDValue Op = BV->getOperand(i);
6410       // If the vector element type is not legal, the BUILD_VECTOR operands
6411       // are promoted and implicitly truncated.  Make that explicit here.
6412       if (Op.getValueType() != SrcEltVT)
6413         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6414       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6415                                 DstEltVT, Op));
6416       AddToWorklist(Ops.back().getNode());
6417     }
6418     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6419   }
6420
6421   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6422   // handle annoying details of growing/shrinking FP values, we convert them to
6423   // int first.
6424   if (SrcEltVT.isFloatingPoint()) {
6425     // Convert the input float vector to a int vector where the elements are the
6426     // same sizes.
6427     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6428     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6429     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6430     SrcEltVT = IntVT;
6431   }
6432
6433   // Now we know the input is an integer vector.  If the output is a FP type,
6434   // convert to integer first, then to FP of the right size.
6435   if (DstEltVT.isFloatingPoint()) {
6436     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6437     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6438     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6439
6440     // Next, convert to FP elements of the same size.
6441     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6442   }
6443
6444   // Okay, we know the src/dst types are both integers of differing types.
6445   // Handling growing first.
6446   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6447   if (SrcBitSize < DstBitSize) {
6448     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6449
6450     SmallVector<SDValue, 8> Ops;
6451     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6452          i += NumInputsPerOutput) {
6453       bool isLE = TLI.isLittleEndian();
6454       APInt NewBits = APInt(DstBitSize, 0);
6455       bool EltIsUndef = true;
6456       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6457         // Shift the previously computed bits over.
6458         NewBits <<= SrcBitSize;
6459         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6460         if (Op.getOpcode() == ISD::UNDEF) continue;
6461         EltIsUndef = false;
6462
6463         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6464                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6465       }
6466
6467       if (EltIsUndef)
6468         Ops.push_back(DAG.getUNDEF(DstEltVT));
6469       else
6470         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6471     }
6472
6473     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6474     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6475   }
6476
6477   // Finally, this must be the case where we are shrinking elements: each input
6478   // turns into multiple outputs.
6479   bool isS2V = ISD::isScalarToVector(BV);
6480   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6481   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6482                             NumOutputsPerInput*BV->getNumOperands());
6483   SmallVector<SDValue, 8> Ops;
6484
6485   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6486     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6487       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6488         Ops.push_back(DAG.getUNDEF(DstEltVT));
6489       continue;
6490     }
6491
6492     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6493                   getAPIntValue().zextOrTrunc(SrcBitSize);
6494
6495     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6496       APInt ThisVal = OpVal.trunc(DstBitSize);
6497       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6498       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6499         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6500         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6501                            Ops[0]);
6502       OpVal = OpVal.lshr(DstBitSize);
6503     }
6504
6505     // For big endian targets, swap the order of the pieces of each element.
6506     if (TLI.isBigEndian())
6507       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6508   }
6509
6510   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6511 }
6512
6513 SDValue DAGCombiner::visitFADD(SDNode *N) {
6514   SDValue N0 = N->getOperand(0);
6515   SDValue N1 = N->getOperand(1);
6516   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6517   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6518   EVT VT = N->getValueType(0);
6519
6520   // fold vector ops
6521   if (VT.isVector()) {
6522     SDValue FoldedVOp = SimplifyVBinOp(N);
6523     if (FoldedVOp.getNode()) return FoldedVOp;
6524   }
6525
6526   // fold (fadd c1, c2) -> c1 + c2
6527   if (N0CFP && N1CFP)
6528     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6529   // canonicalize constant to RHS
6530   if (N0CFP && !N1CFP)
6531     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6532   // fold (fadd A, 0) -> A
6533   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6534       N1CFP->getValueAPF().isZero())
6535     return N0;
6536   // fold (fadd A, (fneg B)) -> (fsub A, B)
6537   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6538     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6539     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6540                        GetNegatedExpression(N1, DAG, LegalOperations));
6541   // fold (fadd (fneg A), B) -> (fsub B, A)
6542   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6543     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6544     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6545                        GetNegatedExpression(N0, DAG, LegalOperations));
6546
6547   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6548   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6549       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6550       isa<ConstantFPSDNode>(N0.getOperand(1)))
6551     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6552                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6553                                    N0.getOperand(1), N1));
6554
6555   // No FP constant should be created after legalization as Instruction
6556   // Selection pass has hard time in dealing with FP constant.
6557   //
6558   // We don't need test this condition for transformation like following, as
6559   // the DAG being transformed implies it is legal to take FP constant as
6560   // operand.
6561   //
6562   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6563   //
6564   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6565
6566   // If allow, fold (fadd (fneg x), x) -> 0.0
6567   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6568       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6569     return DAG.getConstantFP(0.0, VT);
6570
6571     // If allow, fold (fadd x, (fneg x)) -> 0.0
6572   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6573       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6574     return DAG.getConstantFP(0.0, VT);
6575
6576   // In unsafe math mode, we can fold chains of FADD's of the same value
6577   // into multiplications.  This transform is not safe in general because
6578   // we are reducing the number of rounding steps.
6579   if (DAG.getTarget().Options.UnsafeFPMath &&
6580       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6581       !N0CFP && !N1CFP) {
6582     if (N0.getOpcode() == ISD::FMUL) {
6583       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6584       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6585
6586       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6587       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6588         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6589                                      SDValue(CFP00, 0),
6590                                      DAG.getConstantFP(1.0, VT));
6591         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6592                            N1, NewCFP);
6593       }
6594
6595       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6596       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6597         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6598                                      SDValue(CFP01, 0),
6599                                      DAG.getConstantFP(1.0, VT));
6600         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6601                            N1, NewCFP);
6602       }
6603
6604       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6605       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6606           N1.getOperand(0) == N1.getOperand(1) &&
6607           N0.getOperand(1) == N1.getOperand(0)) {
6608         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6609                                      SDValue(CFP00, 0),
6610                                      DAG.getConstantFP(2.0, VT));
6611         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6612                            N0.getOperand(1), NewCFP);
6613       }
6614
6615       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6616       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6617           N1.getOperand(0) == N1.getOperand(1) &&
6618           N0.getOperand(0) == N1.getOperand(0)) {
6619         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6620                                      SDValue(CFP01, 0),
6621                                      DAG.getConstantFP(2.0, VT));
6622         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6623                            N0.getOperand(0), NewCFP);
6624       }
6625     }
6626
6627     if (N1.getOpcode() == ISD::FMUL) {
6628       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6629       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6630
6631       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6632       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6633         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6634                                      SDValue(CFP10, 0),
6635                                      DAG.getConstantFP(1.0, VT));
6636         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6637                            N0, NewCFP);
6638       }
6639
6640       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6641       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6642         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6643                                      SDValue(CFP11, 0),
6644                                      DAG.getConstantFP(1.0, VT));
6645         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6646                            N0, NewCFP);
6647       }
6648
6649
6650       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6651       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6652           N0.getOperand(0) == N0.getOperand(1) &&
6653           N1.getOperand(1) == N0.getOperand(0)) {
6654         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6655                                      SDValue(CFP10, 0),
6656                                      DAG.getConstantFP(2.0, VT));
6657         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6658                            N1.getOperand(1), NewCFP);
6659       }
6660
6661       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6662       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6663           N0.getOperand(0) == N0.getOperand(1) &&
6664           N1.getOperand(0) == N0.getOperand(0)) {
6665         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6666                                      SDValue(CFP11, 0),
6667                                      DAG.getConstantFP(2.0, VT));
6668         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6669                            N1.getOperand(0), NewCFP);
6670       }
6671     }
6672
6673     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6674       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6675       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6676       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6677           (N0.getOperand(0) == N1))
6678         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6679                            N1, DAG.getConstantFP(3.0, VT));
6680     }
6681
6682     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6683       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6684       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6685       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6686           N1.getOperand(0) == N0)
6687         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6688                            N0, DAG.getConstantFP(3.0, VT));
6689     }
6690
6691     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6692     if (AllowNewFpConst &&
6693         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6694         N0.getOperand(0) == N0.getOperand(1) &&
6695         N1.getOperand(0) == N1.getOperand(1) &&
6696         N0.getOperand(0) == N1.getOperand(0))
6697       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6698                          N0.getOperand(0),
6699                          DAG.getConstantFP(4.0, VT));
6700   }
6701
6702   // FADD -> FMA combines:
6703   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6704        DAG.getTarget().Options.UnsafeFPMath) &&
6705       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6706       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6707
6708     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6709     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6710       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6711                          N0.getOperand(0), N0.getOperand(1), N1);
6712
6713     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6714     // Note: Commutes FADD operands.
6715     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6716       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6717                          N1.getOperand(0), N1.getOperand(1), N0);
6718   }
6719
6720   return SDValue();
6721 }
6722
6723 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6724   SDValue N0 = N->getOperand(0);
6725   SDValue N1 = N->getOperand(1);
6726   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6727   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6728   EVT VT = N->getValueType(0);
6729   SDLoc dl(N);
6730
6731   // fold vector ops
6732   if (VT.isVector()) {
6733     SDValue FoldedVOp = SimplifyVBinOp(N);
6734     if (FoldedVOp.getNode()) return FoldedVOp;
6735   }
6736
6737   // fold (fsub c1, c2) -> c1-c2
6738   if (N0CFP && N1CFP)
6739     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6740   // fold (fsub A, 0) -> A
6741   if (DAG.getTarget().Options.UnsafeFPMath &&
6742       N1CFP && N1CFP->getValueAPF().isZero())
6743     return N0;
6744   // fold (fsub 0, B) -> -B
6745   if (DAG.getTarget().Options.UnsafeFPMath &&
6746       N0CFP && N0CFP->getValueAPF().isZero()) {
6747     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6748       return GetNegatedExpression(N1, DAG, LegalOperations);
6749     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6750       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6751   }
6752   // fold (fsub A, (fneg B)) -> (fadd A, B)
6753   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6754     return DAG.getNode(ISD::FADD, dl, VT, N0,
6755                        GetNegatedExpression(N1, DAG, LegalOperations));
6756
6757   // If 'unsafe math' is enabled, fold
6758   //    (fsub x, x) -> 0.0 &
6759   //    (fsub x, (fadd x, y)) -> (fneg y) &
6760   //    (fsub x, (fadd y, x)) -> (fneg y)
6761   if (DAG.getTarget().Options.UnsafeFPMath) {
6762     if (N0 == N1)
6763       return DAG.getConstantFP(0.0f, VT);
6764
6765     if (N1.getOpcode() == ISD::FADD) {
6766       SDValue N10 = N1->getOperand(0);
6767       SDValue N11 = N1->getOperand(1);
6768
6769       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6770                                           &DAG.getTarget().Options))
6771         return GetNegatedExpression(N11, DAG, LegalOperations);
6772
6773       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6774                                           &DAG.getTarget().Options))
6775         return GetNegatedExpression(N10, DAG, LegalOperations);
6776     }
6777   }
6778
6779   // FSUB -> FMA combines:
6780   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6781        DAG.getTarget().Options.UnsafeFPMath) &&
6782       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6783       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6784
6785     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6786     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6787       return DAG.getNode(ISD::FMA, dl, VT,
6788                          N0.getOperand(0), N0.getOperand(1),
6789                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6790
6791     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6792     // Note: Commutes FSUB operands.
6793     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6794       return DAG.getNode(ISD::FMA, dl, VT,
6795                          DAG.getNode(ISD::FNEG, dl, VT,
6796                          N1.getOperand(0)),
6797                          N1.getOperand(1), N0);
6798
6799     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6800     if (N0.getOpcode() == ISD::FNEG &&
6801         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6802         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6803       SDValue N00 = N0.getOperand(0).getOperand(0);
6804       SDValue N01 = N0.getOperand(0).getOperand(1);
6805       return DAG.getNode(ISD::FMA, dl, VT,
6806                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6807                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6808     }
6809   }
6810
6811   return SDValue();
6812 }
6813
6814 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6815   SDValue N0 = N->getOperand(0);
6816   SDValue N1 = N->getOperand(1);
6817   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6818   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6819   EVT VT = N->getValueType(0);
6820   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6821
6822   // fold vector ops
6823   if (VT.isVector()) {
6824     SDValue FoldedVOp = SimplifyVBinOp(N);
6825     if (FoldedVOp.getNode()) return FoldedVOp;
6826   }
6827
6828   // fold (fmul c1, c2) -> c1*c2
6829   if (N0CFP && N1CFP)
6830     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6831   // canonicalize constant to RHS
6832   if (N0CFP && !N1CFP)
6833     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6834   // fold (fmul A, 0) -> 0
6835   if (DAG.getTarget().Options.UnsafeFPMath &&
6836       N1CFP && N1CFP->getValueAPF().isZero())
6837     return N1;
6838   // fold (fmul A, 0) -> 0, vector edition.
6839   if (DAG.getTarget().Options.UnsafeFPMath &&
6840       ISD::isBuildVectorAllZeros(N1.getNode()))
6841     return N1;
6842   // fold (fmul A, 1.0) -> A
6843   if (N1CFP && N1CFP->isExactlyValue(1.0))
6844     return N0;
6845   // fold (fmul X, 2.0) -> (fadd X, X)
6846   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6847     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6848   // fold (fmul X, -1.0) -> (fneg X)
6849   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6850     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6851       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6852
6853   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6854   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6855                                        &DAG.getTarget().Options)) {
6856     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6857                                          &DAG.getTarget().Options)) {
6858       // Both can be negated for free, check to see if at least one is cheaper
6859       // negated.
6860       if (LHSNeg == 2 || RHSNeg == 2)
6861         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6862                            GetNegatedExpression(N0, DAG, LegalOperations),
6863                            GetNegatedExpression(N1, DAG, LegalOperations));
6864     }
6865   }
6866
6867   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6868   if (DAG.getTarget().Options.UnsafeFPMath &&
6869       N1CFP && N0.getOpcode() == ISD::FMUL &&
6870       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6871     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6872                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6873                                    N0.getOperand(1), N1));
6874
6875   return SDValue();
6876 }
6877
6878 SDValue DAGCombiner::visitFMA(SDNode *N) {
6879   SDValue N0 = N->getOperand(0);
6880   SDValue N1 = N->getOperand(1);
6881   SDValue N2 = N->getOperand(2);
6882   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6883   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6884   EVT VT = N->getValueType(0);
6885   SDLoc dl(N);
6886
6887   if (DAG.getTarget().Options.UnsafeFPMath) {
6888     if (N0CFP && N0CFP->isZero())
6889       return N2;
6890     if (N1CFP && N1CFP->isZero())
6891       return N2;
6892   }
6893   if (N0CFP && N0CFP->isExactlyValue(1.0))
6894     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6895   if (N1CFP && N1CFP->isExactlyValue(1.0))
6896     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6897
6898   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6899   if (N0CFP && !N1CFP)
6900     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6901
6902   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6903   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6904       N2.getOpcode() == ISD::FMUL &&
6905       N0 == N2.getOperand(0) &&
6906       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6907     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6908                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6909   }
6910
6911
6912   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6913   if (DAG.getTarget().Options.UnsafeFPMath &&
6914       N0.getOpcode() == ISD::FMUL && N1CFP &&
6915       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6916     return DAG.getNode(ISD::FMA, dl, VT,
6917                        N0.getOperand(0),
6918                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6919                        N2);
6920   }
6921
6922   // (fma x, 1, y) -> (fadd x, y)
6923   // (fma x, -1, y) -> (fadd (fneg x), y)
6924   if (N1CFP) {
6925     if (N1CFP->isExactlyValue(1.0))
6926       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6927
6928     if (N1CFP->isExactlyValue(-1.0) &&
6929         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6930       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6931       AddToWorklist(RHSNeg.getNode());
6932       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6933     }
6934   }
6935
6936   // (fma x, c, x) -> (fmul x, (c+1))
6937   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6938     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6939                        DAG.getNode(ISD::FADD, dl, VT,
6940                                    N1, DAG.getConstantFP(1.0, VT)));
6941
6942   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6943   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6944       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6945     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6946                        DAG.getNode(ISD::FADD, dl, VT,
6947                                    N1, DAG.getConstantFP(-1.0, VT)));
6948
6949
6950   return SDValue();
6951 }
6952
6953 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6954   SDValue N0 = N->getOperand(0);
6955   SDValue N1 = N->getOperand(1);
6956   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6957   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6958   EVT VT = N->getValueType(0);
6959   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6960
6961   // fold vector ops
6962   if (VT.isVector()) {
6963     SDValue FoldedVOp = SimplifyVBinOp(N);
6964     if (FoldedVOp.getNode()) return FoldedVOp;
6965   }
6966
6967   // fold (fdiv c1, c2) -> c1/c2
6968   if (N0CFP && N1CFP)
6969     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6970
6971   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6972   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6973     // Compute the reciprocal 1.0 / c2.
6974     APFloat N1APF = N1CFP->getValueAPF();
6975     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6976     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6977     // Only do the transform if the reciprocal is a legal fp immediate that
6978     // isn't too nasty (eg NaN, denormal, ...).
6979     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6980         (!LegalOperations ||
6981          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6982          // backend)... we should handle this gracefully after Legalize.
6983          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6984          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6985          TLI.isFPImmLegal(Recip, VT)))
6986       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6987                          DAG.getConstantFP(Recip, VT));
6988   }
6989
6990   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6991   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6992                                        &DAG.getTarget().Options)) {
6993     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6994                                          &DAG.getTarget().Options)) {
6995       // Both can be negated for free, check to see if at least one is cheaper
6996       // negated.
6997       if (LHSNeg == 2 || RHSNeg == 2)
6998         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6999                            GetNegatedExpression(N0, DAG, LegalOperations),
7000                            GetNegatedExpression(N1, DAG, LegalOperations));
7001     }
7002   }
7003
7004   return SDValue();
7005 }
7006
7007 SDValue DAGCombiner::visitFREM(SDNode *N) {
7008   SDValue N0 = N->getOperand(0);
7009   SDValue N1 = N->getOperand(1);
7010   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7011   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7012   EVT VT = N->getValueType(0);
7013
7014   // fold (frem c1, c2) -> fmod(c1,c2)
7015   if (N0CFP && N1CFP)
7016     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7017
7018   return SDValue();
7019 }
7020
7021 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7022   SDValue N0 = N->getOperand(0);
7023   SDValue N1 = N->getOperand(1);
7024   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7025   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7026   EVT VT = N->getValueType(0);
7027
7028   if (N0CFP && N1CFP)  // Constant fold
7029     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7030
7031   if (N1CFP) {
7032     const APFloat& V = N1CFP->getValueAPF();
7033     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7034     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7035     if (!V.isNegative()) {
7036       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7037         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7038     } else {
7039       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7040         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7041                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7042     }
7043   }
7044
7045   // copysign(fabs(x), y) -> copysign(x, y)
7046   // copysign(fneg(x), y) -> copysign(x, y)
7047   // copysign(copysign(x,z), y) -> copysign(x, y)
7048   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7049       N0.getOpcode() == ISD::FCOPYSIGN)
7050     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7051                        N0.getOperand(0), N1);
7052
7053   // copysign(x, abs(y)) -> abs(x)
7054   if (N1.getOpcode() == ISD::FABS)
7055     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7056
7057   // copysign(x, copysign(y,z)) -> copysign(x, z)
7058   if (N1.getOpcode() == ISD::FCOPYSIGN)
7059     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7060                        N0, N1.getOperand(1));
7061
7062   // copysign(x, fp_extend(y)) -> copysign(x, y)
7063   // copysign(x, fp_round(y)) -> copysign(x, y)
7064   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7065     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7066                        N0, N1.getOperand(0));
7067
7068   return SDValue();
7069 }
7070
7071 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7072   SDValue N0 = N->getOperand(0);
7073   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7074   EVT VT = N->getValueType(0);
7075   EVT OpVT = N0.getValueType();
7076
7077   // fold (sint_to_fp c1) -> c1fp
7078   if (N0C &&
7079       // ...but only if the target supports immediate floating-point values
7080       (!LegalOperations ||
7081        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7082     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7083
7084   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7085   // but UINT_TO_FP is legal on this target, try to convert.
7086   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7087       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7088     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7089     if (DAG.SignBitIsZero(N0))
7090       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7091   }
7092
7093   // The next optimizations are desirable only if SELECT_CC can be lowered.
7094   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7095     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7096     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7097         !VT.isVector() &&
7098         (!LegalOperations ||
7099          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7100       SDValue Ops[] =
7101         { N0.getOperand(0), N0.getOperand(1),
7102           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7103           N0.getOperand(2) };
7104       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7105     }
7106
7107     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7108     //      (select_cc x, y, 1.0, 0.0,, cc)
7109     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7110         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7111         (!LegalOperations ||
7112          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7113       SDValue Ops[] =
7114         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7115           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7116           N0.getOperand(0).getOperand(2) };
7117       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7118     }
7119   }
7120
7121   return SDValue();
7122 }
7123
7124 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7125   SDValue N0 = N->getOperand(0);
7126   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7127   EVT VT = N->getValueType(0);
7128   EVT OpVT = N0.getValueType();
7129
7130   // fold (uint_to_fp c1) -> c1fp
7131   if (N0C &&
7132       // ...but only if the target supports immediate floating-point values
7133       (!LegalOperations ||
7134        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7135     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7136
7137   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7138   // but SINT_TO_FP is legal on this target, try to convert.
7139   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7140       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7141     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7142     if (DAG.SignBitIsZero(N0))
7143       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7144   }
7145
7146   // The next optimizations are desirable only if SELECT_CC can be lowered.
7147   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7148     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7149
7150     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7151         (!LegalOperations ||
7152          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7153       SDValue Ops[] =
7154         { N0.getOperand(0), N0.getOperand(1),
7155           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7156           N0.getOperand(2) };
7157       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7158     }
7159   }
7160
7161   return SDValue();
7162 }
7163
7164 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7165   SDValue N0 = N->getOperand(0);
7166   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7167   EVT VT = N->getValueType(0);
7168
7169   // fold (fp_to_sint c1fp) -> c1
7170   if (N0CFP)
7171     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7172
7173   return SDValue();
7174 }
7175
7176 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7177   SDValue N0 = N->getOperand(0);
7178   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7179   EVT VT = N->getValueType(0);
7180
7181   // fold (fp_to_uint c1fp) -> c1
7182   if (N0CFP)
7183     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7184
7185   return SDValue();
7186 }
7187
7188 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7189   SDValue N0 = N->getOperand(0);
7190   SDValue N1 = N->getOperand(1);
7191   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7192   EVT VT = N->getValueType(0);
7193
7194   // fold (fp_round c1fp) -> c1fp
7195   if (N0CFP)
7196     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7197
7198   // fold (fp_round (fp_extend x)) -> x
7199   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7200     return N0.getOperand(0);
7201
7202   // fold (fp_round (fp_round x)) -> (fp_round x)
7203   if (N0.getOpcode() == ISD::FP_ROUND) {
7204     // This is a value preserving truncation if both round's are.
7205     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7206                    N0.getNode()->getConstantOperandVal(1) == 1;
7207     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7208                        DAG.getIntPtrConstant(IsTrunc));
7209   }
7210
7211   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7212   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7213     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7214                               N0.getOperand(0), N1);
7215     AddToWorklist(Tmp.getNode());
7216     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7217                        Tmp, N0.getOperand(1));
7218   }
7219
7220   return SDValue();
7221 }
7222
7223 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7224   SDValue N0 = N->getOperand(0);
7225   EVT VT = N->getValueType(0);
7226   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7227   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7228
7229   // fold (fp_round_inreg c1fp) -> c1fp
7230   if (N0CFP && isTypeLegal(EVT)) {
7231     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7232     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7233   }
7234
7235   return SDValue();
7236 }
7237
7238 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7239   SDValue N0 = N->getOperand(0);
7240   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7241   EVT VT = N->getValueType(0);
7242
7243   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7244   if (N->hasOneUse() &&
7245       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7246     return SDValue();
7247
7248   // fold (fp_extend c1fp) -> c1fp
7249   if (N0CFP)
7250     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7251
7252   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7253   // value of X.
7254   if (N0.getOpcode() == ISD::FP_ROUND
7255       && N0.getNode()->getConstantOperandVal(1) == 1) {
7256     SDValue In = N0.getOperand(0);
7257     if (In.getValueType() == VT) return In;
7258     if (VT.bitsLT(In.getValueType()))
7259       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7260                          In, N0.getOperand(1));
7261     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7262   }
7263
7264   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7265   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7266        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7267     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7268     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7269                                      LN0->getChain(),
7270                                      LN0->getBasePtr(), N0.getValueType(),
7271                                      LN0->getMemOperand());
7272     CombineTo(N, ExtLoad);
7273     CombineTo(N0.getNode(),
7274               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7275                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7276               ExtLoad.getValue(1));
7277     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7278   }
7279
7280   return SDValue();
7281 }
7282
7283 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7284   SDValue N0 = N->getOperand(0);
7285   EVT VT = N->getValueType(0);
7286
7287   if (VT.isVector()) {
7288     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7289     if (FoldedVOp.getNode()) return FoldedVOp;
7290   }
7291
7292   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7293                          &DAG.getTarget().Options))
7294     return GetNegatedExpression(N0, DAG, LegalOperations);
7295
7296   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7297   // constant pool values.
7298   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7299       !VT.isVector() &&
7300       N0.getNode()->hasOneUse() &&
7301       N0.getOperand(0).getValueType().isInteger()) {
7302     SDValue Int = N0.getOperand(0);
7303     EVT IntVT = Int.getValueType();
7304     if (IntVT.isInteger() && !IntVT.isVector()) {
7305       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7306               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7307       AddToWorklist(Int.getNode());
7308       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7309                          VT, Int);
7310     }
7311   }
7312
7313   // (fneg (fmul c, x)) -> (fmul -c, x)
7314   if (N0.getOpcode() == ISD::FMUL) {
7315     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7316     if (CFP1) {
7317       APFloat CVal = CFP1->getValueAPF();
7318       CVal.changeSign();
7319       if (Level >= AfterLegalizeDAG &&
7320           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7321            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7322         return DAG.getNode(
7323             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7324             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7325     }
7326   }
7327
7328   return SDValue();
7329 }
7330
7331 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7332   SDValue N0 = N->getOperand(0);
7333   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7334   EVT VT = N->getValueType(0);
7335
7336   // fold (fceil c1) -> fceil(c1)
7337   if (N0CFP)
7338     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7339
7340   return SDValue();
7341 }
7342
7343 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7344   SDValue N0 = N->getOperand(0);
7345   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7346   EVT VT = N->getValueType(0);
7347
7348   // fold (ftrunc c1) -> ftrunc(c1)
7349   if (N0CFP)
7350     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7351
7352   return SDValue();
7353 }
7354
7355 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7356   SDValue N0 = N->getOperand(0);
7357   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7358   EVT VT = N->getValueType(0);
7359
7360   // fold (ffloor c1) -> ffloor(c1)
7361   if (N0CFP)
7362     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7363
7364   return SDValue();
7365 }
7366
7367 SDValue DAGCombiner::visitFABS(SDNode *N) {
7368   SDValue N0 = N->getOperand(0);
7369   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7370   EVT VT = N->getValueType(0);
7371
7372   if (VT.isVector()) {
7373     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7374     if (FoldedVOp.getNode()) return FoldedVOp;
7375   }
7376
7377   // fold (fabs c1) -> fabs(c1)
7378   if (N0CFP)
7379     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7380   // fold (fabs (fabs x)) -> (fabs x)
7381   if (N0.getOpcode() == ISD::FABS)
7382     return N->getOperand(0);
7383   // fold (fabs (fneg x)) -> (fabs x)
7384   // fold (fabs (fcopysign x, y)) -> (fabs x)
7385   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7386     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7387
7388   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7389   // constant pool values.
7390   if (!TLI.isFAbsFree(VT) &&
7391       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7392       N0.getOperand(0).getValueType().isInteger() &&
7393       !N0.getOperand(0).getValueType().isVector()) {
7394     SDValue Int = N0.getOperand(0);
7395     EVT IntVT = Int.getValueType();
7396     if (IntVT.isInteger() && !IntVT.isVector()) {
7397       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7398              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7399       AddToWorklist(Int.getNode());
7400       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7401                          N->getValueType(0), Int);
7402     }
7403   }
7404
7405   return SDValue();
7406 }
7407
7408 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7409   SDValue Chain = N->getOperand(0);
7410   SDValue N1 = N->getOperand(1);
7411   SDValue N2 = N->getOperand(2);
7412
7413   // If N is a constant we could fold this into a fallthrough or unconditional
7414   // branch. However that doesn't happen very often in normal code, because
7415   // Instcombine/SimplifyCFG should have handled the available opportunities.
7416   // If we did this folding here, it would be necessary to update the
7417   // MachineBasicBlock CFG, which is awkward.
7418
7419   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7420   // on the target.
7421   if (N1.getOpcode() == ISD::SETCC &&
7422       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7423                                    N1.getOperand(0).getValueType())) {
7424     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7425                        Chain, N1.getOperand(2),
7426                        N1.getOperand(0), N1.getOperand(1), N2);
7427   }
7428
7429   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7430       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7431        (N1.getOperand(0).hasOneUse() &&
7432         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7433     SDNode *Trunc = nullptr;
7434     if (N1.getOpcode() == ISD::TRUNCATE) {
7435       // Look pass the truncate.
7436       Trunc = N1.getNode();
7437       N1 = N1.getOperand(0);
7438     }
7439
7440     // Match this pattern so that we can generate simpler code:
7441     //
7442     //   %a = ...
7443     //   %b = and i32 %a, 2
7444     //   %c = srl i32 %b, 1
7445     //   brcond i32 %c ...
7446     //
7447     // into
7448     //
7449     //   %a = ...
7450     //   %b = and i32 %a, 2
7451     //   %c = setcc eq %b, 0
7452     //   brcond %c ...
7453     //
7454     // This applies only when the AND constant value has one bit set and the
7455     // SRL constant is equal to the log2 of the AND constant. The back-end is
7456     // smart enough to convert the result into a TEST/JMP sequence.
7457     SDValue Op0 = N1.getOperand(0);
7458     SDValue Op1 = N1.getOperand(1);
7459
7460     if (Op0.getOpcode() == ISD::AND &&
7461         Op1.getOpcode() == ISD::Constant) {
7462       SDValue AndOp1 = Op0.getOperand(1);
7463
7464       if (AndOp1.getOpcode() == ISD::Constant) {
7465         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7466
7467         if (AndConst.isPowerOf2() &&
7468             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7469           SDValue SetCC =
7470             DAG.getSetCC(SDLoc(N),
7471                          getSetCCResultType(Op0.getValueType()),
7472                          Op0, DAG.getConstant(0, Op0.getValueType()),
7473                          ISD::SETNE);
7474
7475           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7476                                           MVT::Other, Chain, SetCC, N2);
7477           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7478           // will convert it back to (X & C1) >> C2.
7479           CombineTo(N, NewBRCond, false);
7480           // Truncate is dead.
7481           if (Trunc) {
7482             removeFromWorklist(Trunc);
7483             DAG.DeleteNode(Trunc);
7484           }
7485           // Replace the uses of SRL with SETCC
7486           WorklistRemover DeadNodes(*this);
7487           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7488           removeFromWorklist(N1.getNode());
7489           DAG.DeleteNode(N1.getNode());
7490           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7491         }
7492       }
7493     }
7494
7495     if (Trunc)
7496       // Restore N1 if the above transformation doesn't match.
7497       N1 = N->getOperand(1);
7498   }
7499
7500   // Transform br(xor(x, y)) -> br(x != y)
7501   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7502   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7503     SDNode *TheXor = N1.getNode();
7504     SDValue Op0 = TheXor->getOperand(0);
7505     SDValue Op1 = TheXor->getOperand(1);
7506     if (Op0.getOpcode() == Op1.getOpcode()) {
7507       // Avoid missing important xor optimizations.
7508       SDValue Tmp = visitXOR(TheXor);
7509       if (Tmp.getNode()) {
7510         if (Tmp.getNode() != TheXor) {
7511           DEBUG(dbgs() << "\nReplacing.8 ";
7512                 TheXor->dump(&DAG);
7513                 dbgs() << "\nWith: ";
7514                 Tmp.getNode()->dump(&DAG);
7515                 dbgs() << '\n');
7516           WorklistRemover DeadNodes(*this);
7517           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7518           removeFromWorklist(TheXor);
7519           DAG.DeleteNode(TheXor);
7520           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7521                              MVT::Other, Chain, Tmp, N2);
7522         }
7523
7524         // visitXOR has changed XOR's operands or replaced the XOR completely,
7525         // bail out.
7526         return SDValue(N, 0);
7527       }
7528     }
7529
7530     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7531       bool Equal = false;
7532       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7533         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7534             Op0.getOpcode() == ISD::XOR) {
7535           TheXor = Op0.getNode();
7536           Equal = true;
7537         }
7538
7539       EVT SetCCVT = N1.getValueType();
7540       if (LegalTypes)
7541         SetCCVT = getSetCCResultType(SetCCVT);
7542       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7543                                    SetCCVT,
7544                                    Op0, Op1,
7545                                    Equal ? ISD::SETEQ : ISD::SETNE);
7546       // Replace the uses of XOR with SETCC
7547       WorklistRemover DeadNodes(*this);
7548       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7549       removeFromWorklist(N1.getNode());
7550       DAG.DeleteNode(N1.getNode());
7551       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7552                          MVT::Other, Chain, SetCC, N2);
7553     }
7554   }
7555
7556   return SDValue();
7557 }
7558
7559 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7560 //
7561 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7562   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7563   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7564
7565   // If N is a constant we could fold this into a fallthrough or unconditional
7566   // branch. However that doesn't happen very often in normal code, because
7567   // Instcombine/SimplifyCFG should have handled the available opportunities.
7568   // If we did this folding here, it would be necessary to update the
7569   // MachineBasicBlock CFG, which is awkward.
7570
7571   // Use SimplifySetCC to simplify SETCC's.
7572   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7573                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7574                                false);
7575   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7576
7577   // fold to a simpler setcc
7578   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7579     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7580                        N->getOperand(0), Simp.getOperand(2),
7581                        Simp.getOperand(0), Simp.getOperand(1),
7582                        N->getOperand(4));
7583
7584   return SDValue();
7585 }
7586
7587 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7588 /// uses N as its base pointer and that N may be folded in the load / store
7589 /// addressing mode.
7590 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7591                                     SelectionDAG &DAG,
7592                                     const TargetLowering &TLI) {
7593   EVT VT;
7594   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7595     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7596       return false;
7597     VT = Use->getValueType(0);
7598   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7599     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7600       return false;
7601     VT = ST->getValue().getValueType();
7602   } else
7603     return false;
7604
7605   TargetLowering::AddrMode AM;
7606   if (N->getOpcode() == ISD::ADD) {
7607     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7608     if (Offset)
7609       // [reg +/- imm]
7610       AM.BaseOffs = Offset->getSExtValue();
7611     else
7612       // [reg +/- reg]
7613       AM.Scale = 1;
7614   } else if (N->getOpcode() == ISD::SUB) {
7615     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7616     if (Offset)
7617       // [reg +/- imm]
7618       AM.BaseOffs = -Offset->getSExtValue();
7619     else
7620       // [reg +/- reg]
7621       AM.Scale = 1;
7622   } else
7623     return false;
7624
7625   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7626 }
7627
7628 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7629 /// pre-indexed load / store when the base pointer is an add or subtract
7630 /// and it has other uses besides the load / store. After the
7631 /// transformation, the new indexed load / store has effectively folded
7632 /// the add / subtract in and all of its other uses are redirected to the
7633 /// new load / store.
7634 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7635   if (Level < AfterLegalizeDAG)
7636     return false;
7637
7638   bool isLoad = true;
7639   SDValue Ptr;
7640   EVT VT;
7641   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7642     if (LD->isIndexed())
7643       return false;
7644     VT = LD->getMemoryVT();
7645     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7646         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7647       return false;
7648     Ptr = LD->getBasePtr();
7649   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7650     if (ST->isIndexed())
7651       return false;
7652     VT = ST->getMemoryVT();
7653     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7654         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7655       return false;
7656     Ptr = ST->getBasePtr();
7657     isLoad = false;
7658   } else {
7659     return false;
7660   }
7661
7662   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7663   // out.  There is no reason to make this a preinc/predec.
7664   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7665       Ptr.getNode()->hasOneUse())
7666     return false;
7667
7668   // Ask the target to do addressing mode selection.
7669   SDValue BasePtr;
7670   SDValue Offset;
7671   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7672   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7673     return false;
7674
7675   // Backends without true r+i pre-indexed forms may need to pass a
7676   // constant base with a variable offset so that constant coercion
7677   // will work with the patterns in canonical form.
7678   bool Swapped = false;
7679   if (isa<ConstantSDNode>(BasePtr)) {
7680     std::swap(BasePtr, Offset);
7681     Swapped = true;
7682   }
7683
7684   // Don't create a indexed load / store with zero offset.
7685   if (isa<ConstantSDNode>(Offset) &&
7686       cast<ConstantSDNode>(Offset)->isNullValue())
7687     return false;
7688
7689   // Try turning it into a pre-indexed load / store except when:
7690   // 1) The new base ptr is a frame index.
7691   // 2) If N is a store and the new base ptr is either the same as or is a
7692   //    predecessor of the value being stored.
7693   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7694   //    that would create a cycle.
7695   // 4) All uses are load / store ops that use it as old base ptr.
7696
7697   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7698   // (plus the implicit offset) to a register to preinc anyway.
7699   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7700     return false;
7701
7702   // Check #2.
7703   if (!isLoad) {
7704     SDValue Val = cast<StoreSDNode>(N)->getValue();
7705     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7706       return false;
7707   }
7708
7709   // If the offset is a constant, there may be other adds of constants that
7710   // can be folded with this one. We should do this to avoid having to keep
7711   // a copy of the original base pointer.
7712   SmallVector<SDNode *, 16> OtherUses;
7713   if (isa<ConstantSDNode>(Offset))
7714     for (SDNode *Use : BasePtr.getNode()->uses()) {
7715       if (Use == Ptr.getNode())
7716         continue;
7717
7718       if (Use->isPredecessorOf(N))
7719         continue;
7720
7721       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7722         OtherUses.clear();
7723         break;
7724       }
7725
7726       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7727       if (Op1.getNode() == BasePtr.getNode())
7728         std::swap(Op0, Op1);
7729       assert(Op0.getNode() == BasePtr.getNode() &&
7730              "Use of ADD/SUB but not an operand");
7731
7732       if (!isa<ConstantSDNode>(Op1)) {
7733         OtherUses.clear();
7734         break;
7735       }
7736
7737       // FIXME: In some cases, we can be smarter about this.
7738       if (Op1.getValueType() != Offset.getValueType()) {
7739         OtherUses.clear();
7740         break;
7741       }
7742
7743       OtherUses.push_back(Use);
7744     }
7745
7746   if (Swapped)
7747     std::swap(BasePtr, Offset);
7748
7749   // Now check for #3 and #4.
7750   bool RealUse = false;
7751
7752   // Caches for hasPredecessorHelper
7753   SmallPtrSet<const SDNode *, 32> Visited;
7754   SmallVector<const SDNode *, 16> Worklist;
7755
7756   for (SDNode *Use : Ptr.getNode()->uses()) {
7757     if (Use == N)
7758       continue;
7759     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7760       return false;
7761
7762     // If Ptr may be folded in addressing mode of other use, then it's
7763     // not profitable to do this transformation.
7764     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7765       RealUse = true;
7766   }
7767
7768   if (!RealUse)
7769     return false;
7770
7771   SDValue Result;
7772   if (isLoad)
7773     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7774                                 BasePtr, Offset, AM);
7775   else
7776     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7777                                  BasePtr, Offset, AM);
7778   ++PreIndexedNodes;
7779   ++NodesCombined;
7780   DEBUG(dbgs() << "\nReplacing.4 ";
7781         N->dump(&DAG);
7782         dbgs() << "\nWith: ";
7783         Result.getNode()->dump(&DAG);
7784         dbgs() << '\n');
7785   WorklistRemover DeadNodes(*this);
7786   if (isLoad) {
7787     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7788     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7789   } else {
7790     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7791   }
7792
7793   // Finally, since the node is now dead, remove it from the graph.
7794   DAG.DeleteNode(N);
7795
7796   if (Swapped)
7797     std::swap(BasePtr, Offset);
7798
7799   // Replace other uses of BasePtr that can be updated to use Ptr
7800   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7801     unsigned OffsetIdx = 1;
7802     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7803       OffsetIdx = 0;
7804     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7805            BasePtr.getNode() && "Expected BasePtr operand");
7806
7807     // We need to replace ptr0 in the following expression:
7808     //   x0 * offset0 + y0 * ptr0 = t0
7809     // knowing that
7810     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7811     //
7812     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7813     // indexed load/store and the expresion that needs to be re-written.
7814     //
7815     // Therefore, we have:
7816     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7817
7818     ConstantSDNode *CN =
7819       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7820     int X0, X1, Y0, Y1;
7821     APInt Offset0 = CN->getAPIntValue();
7822     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7823
7824     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7825     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7826     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7827     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7828
7829     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7830
7831     APInt CNV = Offset0;
7832     if (X0 < 0) CNV = -CNV;
7833     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7834     else CNV = CNV - Offset1;
7835
7836     // We can now generate the new expression.
7837     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7838     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7839
7840     SDValue NewUse = DAG.getNode(Opcode,
7841                                  SDLoc(OtherUses[i]),
7842                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7843     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7844     removeFromWorklist(OtherUses[i]);
7845     DAG.DeleteNode(OtherUses[i]);
7846   }
7847
7848   // Replace the uses of Ptr with uses of the updated base value.
7849   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7850   removeFromWorklist(Ptr.getNode());
7851   DAG.DeleteNode(Ptr.getNode());
7852
7853   return true;
7854 }
7855
7856 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7857 /// add / sub of the base pointer node into a post-indexed load / store.
7858 /// The transformation folded the add / subtract into the new indexed
7859 /// load / store effectively and all of its uses are redirected to the
7860 /// new load / store.
7861 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7862   if (Level < AfterLegalizeDAG)
7863     return false;
7864
7865   bool isLoad = true;
7866   SDValue Ptr;
7867   EVT VT;
7868   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7869     if (LD->isIndexed())
7870       return false;
7871     VT = LD->getMemoryVT();
7872     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7873         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7874       return false;
7875     Ptr = LD->getBasePtr();
7876   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7877     if (ST->isIndexed())
7878       return false;
7879     VT = ST->getMemoryVT();
7880     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7881         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7882       return false;
7883     Ptr = ST->getBasePtr();
7884     isLoad = false;
7885   } else {
7886     return false;
7887   }
7888
7889   if (Ptr.getNode()->hasOneUse())
7890     return false;
7891
7892   for (SDNode *Op : Ptr.getNode()->uses()) {
7893     if (Op == N ||
7894         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7895       continue;
7896
7897     SDValue BasePtr;
7898     SDValue Offset;
7899     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7900     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7901       // Don't create a indexed load / store with zero offset.
7902       if (isa<ConstantSDNode>(Offset) &&
7903           cast<ConstantSDNode>(Offset)->isNullValue())
7904         continue;
7905
7906       // Try turning it into a post-indexed load / store except when
7907       // 1) All uses are load / store ops that use it as base ptr (and
7908       //    it may be folded as addressing mmode).
7909       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7910       //    nor a successor of N. Otherwise, if Op is folded that would
7911       //    create a cycle.
7912
7913       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7914         continue;
7915
7916       // Check for #1.
7917       bool TryNext = false;
7918       for (SDNode *Use : BasePtr.getNode()->uses()) {
7919         if (Use == Ptr.getNode())
7920           continue;
7921
7922         // If all the uses are load / store addresses, then don't do the
7923         // transformation.
7924         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7925           bool RealUse = false;
7926           for (SDNode *UseUse : Use->uses()) {
7927             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7928               RealUse = true;
7929           }
7930
7931           if (!RealUse) {
7932             TryNext = true;
7933             break;
7934           }
7935         }
7936       }
7937
7938       if (TryNext)
7939         continue;
7940
7941       // Check for #2
7942       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7943         SDValue Result = isLoad
7944           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7945                                BasePtr, Offset, AM)
7946           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7947                                 BasePtr, Offset, AM);
7948         ++PostIndexedNodes;
7949         ++NodesCombined;
7950         DEBUG(dbgs() << "\nReplacing.5 ";
7951               N->dump(&DAG);
7952               dbgs() << "\nWith: ";
7953               Result.getNode()->dump(&DAG);
7954               dbgs() << '\n');
7955         WorklistRemover DeadNodes(*this);
7956         if (isLoad) {
7957           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7958           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7959         } else {
7960           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7961         }
7962
7963         // Finally, since the node is now dead, remove it from the graph.
7964         DAG.DeleteNode(N);
7965
7966         // Replace the uses of Use with uses of the updated base value.
7967         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7968                                       Result.getValue(isLoad ? 1 : 0));
7969         removeFromWorklist(Op);
7970         DAG.DeleteNode(Op);
7971         return true;
7972       }
7973     }
7974   }
7975
7976   return false;
7977 }
7978
7979 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7980   LoadSDNode *LD  = cast<LoadSDNode>(N);
7981   SDValue Chain = LD->getChain();
7982   SDValue Ptr   = LD->getBasePtr();
7983
7984   // If load is not volatile and there are no uses of the loaded value (and
7985   // the updated indexed value in case of indexed loads), change uses of the
7986   // chain value into uses of the chain input (i.e. delete the dead load).
7987   if (!LD->isVolatile()) {
7988     if (N->getValueType(1) == MVT::Other) {
7989       // Unindexed loads.
7990       if (!N->hasAnyUseOfValue(0)) {
7991         // It's not safe to use the two value CombineTo variant here. e.g.
7992         // v1, chain2 = load chain1, loc
7993         // v2, chain3 = load chain2, loc
7994         // v3         = add v2, c
7995         // Now we replace use of chain2 with chain1.  This makes the second load
7996         // isomorphic to the one we are deleting, and thus makes this load live.
7997         DEBUG(dbgs() << "\nReplacing.6 ";
7998               N->dump(&DAG);
7999               dbgs() << "\nWith chain: ";
8000               Chain.getNode()->dump(&DAG);
8001               dbgs() << "\n");
8002         WorklistRemover DeadNodes(*this);
8003         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8004
8005         if (N->use_empty()) {
8006           removeFromWorklist(N);
8007           DAG.DeleteNode(N);
8008         }
8009
8010         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8011       }
8012     } else {
8013       // Indexed loads.
8014       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8015       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
8016         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8017         DEBUG(dbgs() << "\nReplacing.7 ";
8018               N->dump(&DAG);
8019               dbgs() << "\nWith: ";
8020               Undef.getNode()->dump(&DAG);
8021               dbgs() << " and 2 other values\n");
8022         WorklistRemover DeadNodes(*this);
8023         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8024         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
8025                                       DAG.getUNDEF(N->getValueType(1)));
8026         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8027         removeFromWorklist(N);
8028         DAG.DeleteNode(N);
8029         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8030       }
8031     }
8032   }
8033
8034   // If this load is directly stored, replace the load value with the stored
8035   // value.
8036   // TODO: Handle store large -> read small portion.
8037   // TODO: Handle TRUNCSTORE/LOADEXT
8038   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8039     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8040       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8041       if (PrevST->getBasePtr() == Ptr &&
8042           PrevST->getValue().getValueType() == N->getValueType(0))
8043       return CombineTo(N, Chain.getOperand(1), Chain);
8044     }
8045   }
8046
8047   // Try to infer better alignment information than the load already has.
8048   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8049     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8050       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8051         SDValue NewLoad =
8052                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8053                               LD->getValueType(0),
8054                               Chain, Ptr, LD->getPointerInfo(),
8055                               LD->getMemoryVT(),
8056                               LD->isVolatile(), LD->isNonTemporal(), Align,
8057                               LD->getAAInfo());
8058         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8059       }
8060     }
8061   }
8062
8063   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8064     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8065 #ifndef NDEBUG
8066   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8067       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8068     UseAA = false;
8069 #endif
8070   if (UseAA && LD->isUnindexed()) {
8071     // Walk up chain skipping non-aliasing memory nodes.
8072     SDValue BetterChain = FindBetterChain(N, Chain);
8073
8074     // If there is a better chain.
8075     if (Chain != BetterChain) {
8076       SDValue ReplLoad;
8077
8078       // Replace the chain to void dependency.
8079       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8080         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8081                                BetterChain, Ptr, LD->getMemOperand());
8082       } else {
8083         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8084                                   LD->getValueType(0),
8085                                   BetterChain, Ptr, LD->getMemoryVT(),
8086                                   LD->getMemOperand());
8087       }
8088
8089       // Create token factor to keep old chain connected.
8090       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8091                                   MVT::Other, Chain, ReplLoad.getValue(1));
8092
8093       // Make sure the new and old chains are cleaned up.
8094       AddToWorklist(Token.getNode());
8095
8096       // Replace uses with load result and token factor. Don't add users
8097       // to work list.
8098       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8099     }
8100   }
8101
8102   // Try transforming N to an indexed load.
8103   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8104     return SDValue(N, 0);
8105
8106   // Try to slice up N to more direct loads if the slices are mapped to
8107   // different register banks or pairing can take place.
8108   if (SliceUpLoad(N))
8109     return SDValue(N, 0);
8110
8111   return SDValue();
8112 }
8113
8114 namespace {
8115 /// \brief Helper structure used to slice a load in smaller loads.
8116 /// Basically a slice is obtained from the following sequence:
8117 /// Origin = load Ty1, Base
8118 /// Shift = srl Ty1 Origin, CstTy Amount
8119 /// Inst = trunc Shift to Ty2
8120 ///
8121 /// Then, it will be rewriten into:
8122 /// Slice = load SliceTy, Base + SliceOffset
8123 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8124 ///
8125 /// SliceTy is deduced from the number of bits that are actually used to
8126 /// build Inst.
8127 struct LoadedSlice {
8128   /// \brief Helper structure used to compute the cost of a slice.
8129   struct Cost {
8130     /// Are we optimizing for code size.
8131     bool ForCodeSize;
8132     /// Various cost.
8133     unsigned Loads;
8134     unsigned Truncates;
8135     unsigned CrossRegisterBanksCopies;
8136     unsigned ZExts;
8137     unsigned Shift;
8138
8139     Cost(bool ForCodeSize = false)
8140         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8141           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8142
8143     /// \brief Get the cost of one isolated slice.
8144     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8145         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8146           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8147       EVT TruncType = LS.Inst->getValueType(0);
8148       EVT LoadedType = LS.getLoadedType();
8149       if (TruncType != LoadedType &&
8150           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8151         ZExts = 1;
8152     }
8153
8154     /// \brief Account for slicing gain in the current cost.
8155     /// Slicing provide a few gains like removing a shift or a
8156     /// truncate. This method allows to grow the cost of the original
8157     /// load with the gain from this slice.
8158     void addSliceGain(const LoadedSlice &LS) {
8159       // Each slice saves a truncate.
8160       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8161       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8162                               LS.Inst->getOperand(0).getValueType()))
8163         ++Truncates;
8164       // If there is a shift amount, this slice gets rid of it.
8165       if (LS.Shift)
8166         ++Shift;
8167       // If this slice can merge a cross register bank copy, account for it.
8168       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8169         ++CrossRegisterBanksCopies;
8170     }
8171
8172     Cost &operator+=(const Cost &RHS) {
8173       Loads += RHS.Loads;
8174       Truncates += RHS.Truncates;
8175       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8176       ZExts += RHS.ZExts;
8177       Shift += RHS.Shift;
8178       return *this;
8179     }
8180
8181     bool operator==(const Cost &RHS) const {
8182       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8183              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8184              ZExts == RHS.ZExts && Shift == RHS.Shift;
8185     }
8186
8187     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8188
8189     bool operator<(const Cost &RHS) const {
8190       // Assume cross register banks copies are as expensive as loads.
8191       // FIXME: Do we want some more target hooks?
8192       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8193       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8194       // Unless we are optimizing for code size, consider the
8195       // expensive operation first.
8196       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8197         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8198       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8199              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8200     }
8201
8202     bool operator>(const Cost &RHS) const { return RHS < *this; }
8203
8204     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8205
8206     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8207   };
8208   // The last instruction that represent the slice. This should be a
8209   // truncate instruction.
8210   SDNode *Inst;
8211   // The original load instruction.
8212   LoadSDNode *Origin;
8213   // The right shift amount in bits from the original load.
8214   unsigned Shift;
8215   // The DAG from which Origin came from.
8216   // This is used to get some contextual information about legal types, etc.
8217   SelectionDAG *DAG;
8218
8219   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8220               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8221       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8222
8223   LoadedSlice(const LoadedSlice &LS)
8224       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8225
8226   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8227   /// \return Result is \p BitWidth and has used bits set to 1 and
8228   ///         not used bits set to 0.
8229   APInt getUsedBits() const {
8230     // Reproduce the trunc(lshr) sequence:
8231     // - Start from the truncated value.
8232     // - Zero extend to the desired bit width.
8233     // - Shift left.
8234     assert(Origin && "No original load to compare against.");
8235     unsigned BitWidth = Origin->getValueSizeInBits(0);
8236     assert(Inst && "This slice is not bound to an instruction");
8237     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8238            "Extracted slice is bigger than the whole type!");
8239     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8240     UsedBits.setAllBits();
8241     UsedBits = UsedBits.zext(BitWidth);
8242     UsedBits <<= Shift;
8243     return UsedBits;
8244   }
8245
8246   /// \brief Get the size of the slice to be loaded in bytes.
8247   unsigned getLoadedSize() const {
8248     unsigned SliceSize = getUsedBits().countPopulation();
8249     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8250     return SliceSize / 8;
8251   }
8252
8253   /// \brief Get the type that will be loaded for this slice.
8254   /// Note: This may not be the final type for the slice.
8255   EVT getLoadedType() const {
8256     assert(DAG && "Missing context");
8257     LLVMContext &Ctxt = *DAG->getContext();
8258     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8259   }
8260
8261   /// \brief Get the alignment of the load used for this slice.
8262   unsigned getAlignment() const {
8263     unsigned Alignment = Origin->getAlignment();
8264     unsigned Offset = getOffsetFromBase();
8265     if (Offset != 0)
8266       Alignment = MinAlign(Alignment, Alignment + Offset);
8267     return Alignment;
8268   }
8269
8270   /// \brief Check if this slice can be rewritten with legal operations.
8271   bool isLegal() const {
8272     // An invalid slice is not legal.
8273     if (!Origin || !Inst || !DAG)
8274       return false;
8275
8276     // Offsets are for indexed load only, we do not handle that.
8277     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8278       return false;
8279
8280     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8281
8282     // Check that the type is legal.
8283     EVT SliceType = getLoadedType();
8284     if (!TLI.isTypeLegal(SliceType))
8285       return false;
8286
8287     // Check that the load is legal for this type.
8288     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8289       return false;
8290
8291     // Check that the offset can be computed.
8292     // 1. Check its type.
8293     EVT PtrType = Origin->getBasePtr().getValueType();
8294     if (PtrType == MVT::Untyped || PtrType.isExtended())
8295       return false;
8296
8297     // 2. Check that it fits in the immediate.
8298     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8299       return false;
8300
8301     // 3. Check that the computation is legal.
8302     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8303       return false;
8304
8305     // Check that the zext is legal if it needs one.
8306     EVT TruncateType = Inst->getValueType(0);
8307     if (TruncateType != SliceType &&
8308         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8309       return false;
8310
8311     return true;
8312   }
8313
8314   /// \brief Get the offset in bytes of this slice in the original chunk of
8315   /// bits.
8316   /// \pre DAG != nullptr.
8317   uint64_t getOffsetFromBase() const {
8318     assert(DAG && "Missing context.");
8319     bool IsBigEndian =
8320         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8321     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8322     uint64_t Offset = Shift / 8;
8323     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8324     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8325            "The size of the original loaded type is not a multiple of a"
8326            " byte.");
8327     // If Offset is bigger than TySizeInBytes, it means we are loading all
8328     // zeros. This should have been optimized before in the process.
8329     assert(TySizeInBytes > Offset &&
8330            "Invalid shift amount for given loaded size");
8331     if (IsBigEndian)
8332       Offset = TySizeInBytes - Offset - getLoadedSize();
8333     return Offset;
8334   }
8335
8336   /// \brief Generate the sequence of instructions to load the slice
8337   /// represented by this object and redirect the uses of this slice to
8338   /// this new sequence of instructions.
8339   /// \pre this->Inst && this->Origin are valid Instructions and this
8340   /// object passed the legal check: LoadedSlice::isLegal returned true.
8341   /// \return The last instruction of the sequence used to load the slice.
8342   SDValue loadSlice() const {
8343     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8344     const SDValue &OldBaseAddr = Origin->getBasePtr();
8345     SDValue BaseAddr = OldBaseAddr;
8346     // Get the offset in that chunk of bytes w.r.t. the endianess.
8347     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8348     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8349     if (Offset) {
8350       // BaseAddr = BaseAddr + Offset.
8351       EVT ArithType = BaseAddr.getValueType();
8352       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8353                               DAG->getConstant(Offset, ArithType));
8354     }
8355
8356     // Create the type of the loaded slice according to its size.
8357     EVT SliceType = getLoadedType();
8358
8359     // Create the load for the slice.
8360     SDValue LastInst = DAG->getLoad(
8361         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8362         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8363         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8364     // If the final type is not the same as the loaded type, this means that
8365     // we have to pad with zero. Create a zero extend for that.
8366     EVT FinalType = Inst->getValueType(0);
8367     if (SliceType != FinalType)
8368       LastInst =
8369           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8370     return LastInst;
8371   }
8372
8373   /// \brief Check if this slice can be merged with an expensive cross register
8374   /// bank copy. E.g.,
8375   /// i = load i32
8376   /// f = bitcast i32 i to float
8377   bool canMergeExpensiveCrossRegisterBankCopy() const {
8378     if (!Inst || !Inst->hasOneUse())
8379       return false;
8380     SDNode *Use = *Inst->use_begin();
8381     if (Use->getOpcode() != ISD::BITCAST)
8382       return false;
8383     assert(DAG && "Missing context");
8384     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8385     EVT ResVT = Use->getValueType(0);
8386     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8387     const TargetRegisterClass *ArgRC =
8388         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8389     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8390       return false;
8391
8392     // At this point, we know that we perform a cross-register-bank copy.
8393     // Check if it is expensive.
8394     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8395     // Assume bitcasts are cheap, unless both register classes do not
8396     // explicitly share a common sub class.
8397     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8398       return false;
8399
8400     // Check if it will be merged with the load.
8401     // 1. Check the alignment constraint.
8402     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8403         ResVT.getTypeForEVT(*DAG->getContext()));
8404
8405     if (RequiredAlignment > getAlignment())
8406       return false;
8407
8408     // 2. Check that the load is a legal operation for that type.
8409     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8410       return false;
8411
8412     // 3. Check that we do not have a zext in the way.
8413     if (Inst->getValueType(0) != getLoadedType())
8414       return false;
8415
8416     return true;
8417   }
8418 };
8419 }
8420
8421 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8422 /// \p UsedBits looks like 0..0 1..1 0..0.
8423 static bool areUsedBitsDense(const APInt &UsedBits) {
8424   // If all the bits are one, this is dense!
8425   if (UsedBits.isAllOnesValue())
8426     return true;
8427
8428   // Get rid of the unused bits on the right.
8429   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8430   // Get rid of the unused bits on the left.
8431   if (NarrowedUsedBits.countLeadingZeros())
8432     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8433   // Check that the chunk of bits is completely used.
8434   return NarrowedUsedBits.isAllOnesValue();
8435 }
8436
8437 /// \brief Check whether or not \p First and \p Second are next to each other
8438 /// in memory. This means that there is no hole between the bits loaded
8439 /// by \p First and the bits loaded by \p Second.
8440 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8441                                      const LoadedSlice &Second) {
8442   assert(First.Origin == Second.Origin && First.Origin &&
8443          "Unable to match different memory origins.");
8444   APInt UsedBits = First.getUsedBits();
8445   assert((UsedBits & Second.getUsedBits()) == 0 &&
8446          "Slices are not supposed to overlap.");
8447   UsedBits |= Second.getUsedBits();
8448   return areUsedBitsDense(UsedBits);
8449 }
8450
8451 /// \brief Adjust the \p GlobalLSCost according to the target
8452 /// paring capabilities and the layout of the slices.
8453 /// \pre \p GlobalLSCost should account for at least as many loads as
8454 /// there is in the slices in \p LoadedSlices.
8455 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8456                                  LoadedSlice::Cost &GlobalLSCost) {
8457   unsigned NumberOfSlices = LoadedSlices.size();
8458   // If there is less than 2 elements, no pairing is possible.
8459   if (NumberOfSlices < 2)
8460     return;
8461
8462   // Sort the slices so that elements that are likely to be next to each
8463   // other in memory are next to each other in the list.
8464   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8465             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8466     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8467     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8468   });
8469   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8470   // First (resp. Second) is the first (resp. Second) potentially candidate
8471   // to be placed in a paired load.
8472   const LoadedSlice *First = nullptr;
8473   const LoadedSlice *Second = nullptr;
8474   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8475                 // Set the beginning of the pair.
8476                                                            First = Second) {
8477
8478     Second = &LoadedSlices[CurrSlice];
8479
8480     // If First is NULL, it means we start a new pair.
8481     // Get to the next slice.
8482     if (!First)
8483       continue;
8484
8485     EVT LoadedType = First->getLoadedType();
8486
8487     // If the types of the slices are different, we cannot pair them.
8488     if (LoadedType != Second->getLoadedType())
8489       continue;
8490
8491     // Check if the target supplies paired loads for this type.
8492     unsigned RequiredAlignment = 0;
8493     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8494       // move to the next pair, this type is hopeless.
8495       Second = nullptr;
8496       continue;
8497     }
8498     // Check if we meet the alignment requirement.
8499     if (RequiredAlignment > First->getAlignment())
8500       continue;
8501
8502     // Check that both loads are next to each other in memory.
8503     if (!areSlicesNextToEachOther(*First, *Second))
8504       continue;
8505
8506     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8507     --GlobalLSCost.Loads;
8508     // Move to the next pair.
8509     Second = nullptr;
8510   }
8511 }
8512
8513 /// \brief Check the profitability of all involved LoadedSlice.
8514 /// Currently, it is considered profitable if there is exactly two
8515 /// involved slices (1) which are (2) next to each other in memory, and
8516 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8517 ///
8518 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8519 /// the elements themselves.
8520 ///
8521 /// FIXME: When the cost model will be mature enough, we can relax
8522 /// constraints (1) and (2).
8523 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8524                                 const APInt &UsedBits, bool ForCodeSize) {
8525   unsigned NumberOfSlices = LoadedSlices.size();
8526   if (StressLoadSlicing)
8527     return NumberOfSlices > 1;
8528
8529   // Check (1).
8530   if (NumberOfSlices != 2)
8531     return false;
8532
8533   // Check (2).
8534   if (!areUsedBitsDense(UsedBits))
8535     return false;
8536
8537   // Check (3).
8538   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8539   // The original code has one big load.
8540   OrigCost.Loads = 1;
8541   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8542     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8543     // Accumulate the cost of all the slices.
8544     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8545     GlobalSlicingCost += SliceCost;
8546
8547     // Account as cost in the original configuration the gain obtained
8548     // with the current slices.
8549     OrigCost.addSliceGain(LS);
8550   }
8551
8552   // If the target supports paired load, adjust the cost accordingly.
8553   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8554   return OrigCost > GlobalSlicingCost;
8555 }
8556
8557 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8558 /// operations, split it in the various pieces being extracted.
8559 ///
8560 /// This sort of thing is introduced by SROA.
8561 /// This slicing takes care not to insert overlapping loads.
8562 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8563 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8564   if (Level < AfterLegalizeDAG)
8565     return false;
8566
8567   LoadSDNode *LD = cast<LoadSDNode>(N);
8568   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8569       !LD->getValueType(0).isInteger())
8570     return false;
8571
8572   // Keep track of already used bits to detect overlapping values.
8573   // In that case, we will just abort the transformation.
8574   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8575
8576   SmallVector<LoadedSlice, 4> LoadedSlices;
8577
8578   // Check if this load is used as several smaller chunks of bits.
8579   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8580   // of computation for each trunc.
8581   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8582        UI != UIEnd; ++UI) {
8583     // Skip the uses of the chain.
8584     if (UI.getUse().getResNo() != 0)
8585       continue;
8586
8587     SDNode *User = *UI;
8588     unsigned Shift = 0;
8589
8590     // Check if this is a trunc(lshr).
8591     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8592         isa<ConstantSDNode>(User->getOperand(1))) {
8593       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8594       User = *User->use_begin();
8595     }
8596
8597     // At this point, User is a Truncate, iff we encountered, trunc or
8598     // trunc(lshr).
8599     if (User->getOpcode() != ISD::TRUNCATE)
8600       return false;
8601
8602     // The width of the type must be a power of 2 and greater than 8-bits.
8603     // Otherwise the load cannot be represented in LLVM IR.
8604     // Moreover, if we shifted with a non-8-bits multiple, the slice
8605     // will be across several bytes. We do not support that.
8606     unsigned Width = User->getValueSizeInBits(0);
8607     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8608       return 0;
8609
8610     // Build the slice for this chain of computations.
8611     LoadedSlice LS(User, LD, Shift, &DAG);
8612     APInt CurrentUsedBits = LS.getUsedBits();
8613
8614     // Check if this slice overlaps with another.
8615     if ((CurrentUsedBits & UsedBits) != 0)
8616       return false;
8617     // Update the bits used globally.
8618     UsedBits |= CurrentUsedBits;
8619
8620     // Check if the new slice would be legal.
8621     if (!LS.isLegal())
8622       return false;
8623
8624     // Record the slice.
8625     LoadedSlices.push_back(LS);
8626   }
8627
8628   // Abort slicing if it does not seem to be profitable.
8629   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8630     return false;
8631
8632   ++SlicedLoads;
8633
8634   // Rewrite each chain to use an independent load.
8635   // By construction, each chain can be represented by a unique load.
8636
8637   // Prepare the argument for the new token factor for all the slices.
8638   SmallVector<SDValue, 8> ArgChains;
8639   for (SmallVectorImpl<LoadedSlice>::const_iterator
8640            LSIt = LoadedSlices.begin(),
8641            LSItEnd = LoadedSlices.end();
8642        LSIt != LSItEnd; ++LSIt) {
8643     SDValue SliceInst = LSIt->loadSlice();
8644     CombineTo(LSIt->Inst, SliceInst, true);
8645     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8646       SliceInst = SliceInst.getOperand(0);
8647     assert(SliceInst->getOpcode() == ISD::LOAD &&
8648            "It takes more than a zext to get to the loaded slice!!");
8649     ArgChains.push_back(SliceInst.getValue(1));
8650   }
8651
8652   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8653                               ArgChains);
8654   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8655   return true;
8656 }
8657
8658 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8659 /// load is having specific bytes cleared out.  If so, return the byte size
8660 /// being masked out and the shift amount.
8661 static std::pair<unsigned, unsigned>
8662 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8663   std::pair<unsigned, unsigned> Result(0, 0);
8664
8665   // Check for the structure we're looking for.
8666   if (V->getOpcode() != ISD::AND ||
8667       !isa<ConstantSDNode>(V->getOperand(1)) ||
8668       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8669     return Result;
8670
8671   // Check the chain and pointer.
8672   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8673   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8674
8675   // The store should be chained directly to the load or be an operand of a
8676   // tokenfactor.
8677   if (LD == Chain.getNode())
8678     ; // ok.
8679   else if (Chain->getOpcode() != ISD::TokenFactor)
8680     return Result; // Fail.
8681   else {
8682     bool isOk = false;
8683     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8684       if (Chain->getOperand(i).getNode() == LD) {
8685         isOk = true;
8686         break;
8687       }
8688     if (!isOk) return Result;
8689   }
8690
8691   // This only handles simple types.
8692   if (V.getValueType() != MVT::i16 &&
8693       V.getValueType() != MVT::i32 &&
8694       V.getValueType() != MVT::i64)
8695     return Result;
8696
8697   // Check the constant mask.  Invert it so that the bits being masked out are
8698   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8699   // follow the sign bit for uniformity.
8700   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8701   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8702   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8703   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8704   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8705   if (NotMaskLZ == 64) return Result;  // All zero mask.
8706
8707   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8708   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8709     return Result;
8710
8711   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8712   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8713     NotMaskLZ -= 64-V.getValueSizeInBits();
8714
8715   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8716   switch (MaskedBytes) {
8717   case 1:
8718   case 2:
8719   case 4: break;
8720   default: return Result; // All one mask, or 5-byte mask.
8721   }
8722
8723   // Verify that the first bit starts at a multiple of mask so that the access
8724   // is aligned the same as the access width.
8725   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8726
8727   Result.first = MaskedBytes;
8728   Result.second = NotMaskTZ/8;
8729   return Result;
8730 }
8731
8732
8733 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8734 /// provides a value as specified by MaskInfo.  If so, replace the specified
8735 /// store with a narrower store of truncated IVal.
8736 static SDNode *
8737 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8738                                 SDValue IVal, StoreSDNode *St,
8739                                 DAGCombiner *DC) {
8740   unsigned NumBytes = MaskInfo.first;
8741   unsigned ByteShift = MaskInfo.second;
8742   SelectionDAG &DAG = DC->getDAG();
8743
8744   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8745   // that uses this.  If not, this is not a replacement.
8746   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8747                                   ByteShift*8, (ByteShift+NumBytes)*8);
8748   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8749
8750   // Check that it is legal on the target to do this.  It is legal if the new
8751   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8752   // legalization.
8753   MVT VT = MVT::getIntegerVT(NumBytes*8);
8754   if (!DC->isTypeLegal(VT))
8755     return nullptr;
8756
8757   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8758   // shifted by ByteShift and truncated down to NumBytes.
8759   if (ByteShift)
8760     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8761                        DAG.getConstant(ByteShift*8,
8762                                     DC->getShiftAmountTy(IVal.getValueType())));
8763
8764   // Figure out the offset for the store and the alignment of the access.
8765   unsigned StOffset;
8766   unsigned NewAlign = St->getAlignment();
8767
8768   if (DAG.getTargetLoweringInfo().isLittleEndian())
8769     StOffset = ByteShift;
8770   else
8771     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8772
8773   SDValue Ptr = St->getBasePtr();
8774   if (StOffset) {
8775     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8776                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8777     NewAlign = MinAlign(NewAlign, StOffset);
8778   }
8779
8780   // Truncate down to the new size.
8781   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8782
8783   ++OpsNarrowed;
8784   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8785                       St->getPointerInfo().getWithOffset(StOffset),
8786                       false, false, NewAlign).getNode();
8787 }
8788
8789
8790 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8791 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8792 /// of the loaded bits, try narrowing the load and store if it would end up
8793 /// being a win for performance or code size.
8794 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8795   StoreSDNode *ST  = cast<StoreSDNode>(N);
8796   if (ST->isVolatile())
8797     return SDValue();
8798
8799   SDValue Chain = ST->getChain();
8800   SDValue Value = ST->getValue();
8801   SDValue Ptr   = ST->getBasePtr();
8802   EVT VT = Value.getValueType();
8803
8804   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8805     return SDValue();
8806
8807   unsigned Opc = Value.getOpcode();
8808
8809   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8810   // is a byte mask indicating a consecutive number of bytes, check to see if
8811   // Y is known to provide just those bytes.  If so, we try to replace the
8812   // load + replace + store sequence with a single (narrower) store, which makes
8813   // the load dead.
8814   if (Opc == ISD::OR) {
8815     std::pair<unsigned, unsigned> MaskedLoad;
8816     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8817     if (MaskedLoad.first)
8818       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8819                                                   Value.getOperand(1), ST,this))
8820         return SDValue(NewST, 0);
8821
8822     // Or is commutative, so try swapping X and Y.
8823     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8824     if (MaskedLoad.first)
8825       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8826                                                   Value.getOperand(0), ST,this))
8827         return SDValue(NewST, 0);
8828   }
8829
8830   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8831       Value.getOperand(1).getOpcode() != ISD::Constant)
8832     return SDValue();
8833
8834   SDValue N0 = Value.getOperand(0);
8835   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8836       Chain == SDValue(N0.getNode(), 1)) {
8837     LoadSDNode *LD = cast<LoadSDNode>(N0);
8838     if (LD->getBasePtr() != Ptr ||
8839         LD->getPointerInfo().getAddrSpace() !=
8840         ST->getPointerInfo().getAddrSpace())
8841       return SDValue();
8842
8843     // Find the type to narrow it the load / op / store to.
8844     SDValue N1 = Value.getOperand(1);
8845     unsigned BitWidth = N1.getValueSizeInBits();
8846     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8847     if (Opc == ISD::AND)
8848       Imm ^= APInt::getAllOnesValue(BitWidth);
8849     if (Imm == 0 || Imm.isAllOnesValue())
8850       return SDValue();
8851     unsigned ShAmt = Imm.countTrailingZeros();
8852     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8853     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8854     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8855     while (NewBW < BitWidth &&
8856            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8857              TLI.isNarrowingProfitable(VT, NewVT))) {
8858       NewBW = NextPowerOf2(NewBW);
8859       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8860     }
8861     if (NewBW >= BitWidth)
8862       return SDValue();
8863
8864     // If the lsb changed does not start at the type bitwidth boundary,
8865     // start at the previous one.
8866     if (ShAmt % NewBW)
8867       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8868     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8869                                    std::min(BitWidth, ShAmt + NewBW));
8870     if ((Imm & Mask) == Imm) {
8871       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8872       if (Opc == ISD::AND)
8873         NewImm ^= APInt::getAllOnesValue(NewBW);
8874       uint64_t PtrOff = ShAmt / 8;
8875       // For big endian targets, we need to adjust the offset to the pointer to
8876       // load the correct bytes.
8877       if (TLI.isBigEndian())
8878         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8879
8880       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8881       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8882       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8883         return SDValue();
8884
8885       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8886                                    Ptr.getValueType(), Ptr,
8887                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8888       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8889                                   LD->getChain(), NewPtr,
8890                                   LD->getPointerInfo().getWithOffset(PtrOff),
8891                                   LD->isVolatile(), LD->isNonTemporal(),
8892                                   LD->isInvariant(), NewAlign,
8893                                   LD->getAAInfo());
8894       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8895                                    DAG.getConstant(NewImm, NewVT));
8896       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8897                                    NewVal, NewPtr,
8898                                    ST->getPointerInfo().getWithOffset(PtrOff),
8899                                    false, false, NewAlign);
8900
8901       AddToWorklist(NewPtr.getNode());
8902       AddToWorklist(NewLD.getNode());
8903       AddToWorklist(NewVal.getNode());
8904       WorklistRemover DeadNodes(*this);
8905       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8906       ++OpsNarrowed;
8907       return NewST;
8908     }
8909   }
8910
8911   return SDValue();
8912 }
8913
8914 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8915 /// if the load value isn't used by any other operations, then consider
8916 /// transforming the pair to integer load / store operations if the target
8917 /// deems the transformation profitable.
8918 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8919   StoreSDNode *ST  = cast<StoreSDNode>(N);
8920   SDValue Chain = ST->getChain();
8921   SDValue Value = ST->getValue();
8922   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8923       Value.hasOneUse() &&
8924       Chain == SDValue(Value.getNode(), 1)) {
8925     LoadSDNode *LD = cast<LoadSDNode>(Value);
8926     EVT VT = LD->getMemoryVT();
8927     if (!VT.isFloatingPoint() ||
8928         VT != ST->getMemoryVT() ||
8929         LD->isNonTemporal() ||
8930         ST->isNonTemporal() ||
8931         LD->getPointerInfo().getAddrSpace() != 0 ||
8932         ST->getPointerInfo().getAddrSpace() != 0)
8933       return SDValue();
8934
8935     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8936     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8937         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8938         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8939         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8940       return SDValue();
8941
8942     unsigned LDAlign = LD->getAlignment();
8943     unsigned STAlign = ST->getAlignment();
8944     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8945     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8946     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8947       return SDValue();
8948
8949     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8950                                 LD->getChain(), LD->getBasePtr(),
8951                                 LD->getPointerInfo(),
8952                                 false, false, false, LDAlign);
8953
8954     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8955                                  NewLD, ST->getBasePtr(),
8956                                  ST->getPointerInfo(),
8957                                  false, false, STAlign);
8958
8959     AddToWorklist(NewLD.getNode());
8960     AddToWorklist(NewST.getNode());
8961     WorklistRemover DeadNodes(*this);
8962     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8963     ++LdStFP2Int;
8964     return NewST;
8965   }
8966
8967   return SDValue();
8968 }
8969
8970 /// Helper struct to parse and store a memory address as base + index + offset.
8971 /// We ignore sign extensions when it is safe to do so.
8972 /// The following two expressions are not equivalent. To differentiate we need
8973 /// to store whether there was a sign extension involved in the index
8974 /// computation.
8975 ///  (load (i64 add (i64 copyfromreg %c)
8976 ///                 (i64 signextend (add (i8 load %index)
8977 ///                                      (i8 1))))
8978 /// vs
8979 ///
8980 /// (load (i64 add (i64 copyfromreg %c)
8981 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8982 ///                                         (i32 1)))))
8983 struct BaseIndexOffset {
8984   SDValue Base;
8985   SDValue Index;
8986   int64_t Offset;
8987   bool IsIndexSignExt;
8988
8989   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8990
8991   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8992                   bool IsIndexSignExt) :
8993     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8994
8995   bool equalBaseIndex(const BaseIndexOffset &Other) {
8996     return Other.Base == Base && Other.Index == Index &&
8997       Other.IsIndexSignExt == IsIndexSignExt;
8998   }
8999
9000   /// Parses tree in Ptr for base, index, offset addresses.
9001   static BaseIndexOffset match(SDValue Ptr) {
9002     bool IsIndexSignExt = false;
9003
9004     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9005     // instruction, then it could be just the BASE or everything else we don't
9006     // know how to handle. Just use Ptr as BASE and give up.
9007     if (Ptr->getOpcode() != ISD::ADD)
9008       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9009
9010     // We know that we have at least an ADD instruction. Try to pattern match
9011     // the simple case of BASE + OFFSET.
9012     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9013       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9014       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9015                               IsIndexSignExt);
9016     }
9017
9018     // Inside a loop the current BASE pointer is calculated using an ADD and a
9019     // MUL instruction. In this case Ptr is the actual BASE pointer.
9020     // (i64 add (i64 %array_ptr)
9021     //          (i64 mul (i64 %induction_var)
9022     //                   (i64 %element_size)))
9023     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9024       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9025
9026     // Look at Base + Index + Offset cases.
9027     SDValue Base = Ptr->getOperand(0);
9028     SDValue IndexOffset = Ptr->getOperand(1);
9029
9030     // Skip signextends.
9031     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9032       IndexOffset = IndexOffset->getOperand(0);
9033       IsIndexSignExt = true;
9034     }
9035
9036     // Either the case of Base + Index (no offset) or something else.
9037     if (IndexOffset->getOpcode() != ISD::ADD)
9038       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9039
9040     // Now we have the case of Base + Index + offset.
9041     SDValue Index = IndexOffset->getOperand(0);
9042     SDValue Offset = IndexOffset->getOperand(1);
9043
9044     if (!isa<ConstantSDNode>(Offset))
9045       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9046
9047     // Ignore signextends.
9048     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9049       Index = Index->getOperand(0);
9050       IsIndexSignExt = true;
9051     } else IsIndexSignExt = false;
9052
9053     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9054     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9055   }
9056 };
9057
9058 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9059 /// is located in a sequence of memory operations connected by a chain.
9060 struct MemOpLink {
9061   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9062     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9063   // Ptr to the mem node.
9064   LSBaseSDNode *MemNode;
9065   // Offset from the base ptr.
9066   int64_t OffsetFromBase;
9067   // What is the sequence number of this mem node.
9068   // Lowest mem operand in the DAG starts at zero.
9069   unsigned SequenceNum;
9070 };
9071
9072 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9073   EVT MemVT = St->getMemoryVT();
9074   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9075   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9076     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9077
9078   // Don't merge vectors into wider inputs.
9079   if (MemVT.isVector() || !MemVT.isSimple())
9080     return false;
9081
9082   // Perform an early exit check. Do not bother looking at stored values that
9083   // are not constants or loads.
9084   SDValue StoredVal = St->getValue();
9085   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9086   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9087       !IsLoadSrc)
9088     return false;
9089
9090   // Only look at ends of store sequences.
9091   SDValue Chain = SDValue(St, 0);
9092   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9093     return false;
9094
9095   // This holds the base pointer, index, and the offset in bytes from the base
9096   // pointer.
9097   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9098
9099   // We must have a base and an offset.
9100   if (!BasePtr.Base.getNode())
9101     return false;
9102
9103   // Do not handle stores to undef base pointers.
9104   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9105     return false;
9106
9107   // Save the LoadSDNodes that we find in the chain.
9108   // We need to make sure that these nodes do not interfere with
9109   // any of the store nodes.
9110   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9111
9112   // Save the StoreSDNodes that we find in the chain.
9113   SmallVector<MemOpLink, 8> StoreNodes;
9114
9115   // Walk up the chain and look for nodes with offsets from the same
9116   // base pointer. Stop when reaching an instruction with a different kind
9117   // or instruction which has a different base pointer.
9118   unsigned Seq = 0;
9119   StoreSDNode *Index = St;
9120   while (Index) {
9121     // If the chain has more than one use, then we can't reorder the mem ops.
9122     if (Index != St && !SDValue(Index, 1)->hasOneUse())
9123       break;
9124
9125     // Find the base pointer and offset for this memory node.
9126     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9127
9128     // Check that the base pointer is the same as the original one.
9129     if (!Ptr.equalBaseIndex(BasePtr))
9130       break;
9131
9132     // Check that the alignment is the same.
9133     if (Index->getAlignment() != St->getAlignment())
9134       break;
9135
9136     // The memory operands must not be volatile.
9137     if (Index->isVolatile() || Index->isIndexed())
9138       break;
9139
9140     // No truncation.
9141     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9142       if (St->isTruncatingStore())
9143         break;
9144
9145     // The stored memory type must be the same.
9146     if (Index->getMemoryVT() != MemVT)
9147       break;
9148
9149     // We do not allow unaligned stores because we want to prevent overriding
9150     // stores.
9151     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9152       break;
9153
9154     // We found a potential memory operand to merge.
9155     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9156
9157     // Find the next memory operand in the chain. If the next operand in the
9158     // chain is a store then move up and continue the scan with the next
9159     // memory operand. If the next operand is a load save it and use alias
9160     // information to check if it interferes with anything.
9161     SDNode *NextInChain = Index->getChain().getNode();
9162     while (1) {
9163       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9164         // We found a store node. Use it for the next iteration.
9165         Index = STn;
9166         break;
9167       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9168         if (Ldn->isVolatile()) {
9169           Index = nullptr;
9170           break;
9171         }
9172
9173         // Save the load node for later. Continue the scan.
9174         AliasLoadNodes.push_back(Ldn);
9175         NextInChain = Ldn->getChain().getNode();
9176         continue;
9177       } else {
9178         Index = nullptr;
9179         break;
9180       }
9181     }
9182   }
9183
9184   // Check if there is anything to merge.
9185   if (StoreNodes.size() < 2)
9186     return false;
9187
9188   // Sort the memory operands according to their distance from the base pointer.
9189   std::sort(StoreNodes.begin(), StoreNodes.end(),
9190             [](MemOpLink LHS, MemOpLink RHS) {
9191     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9192            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9193             LHS.SequenceNum > RHS.SequenceNum);
9194   });
9195
9196   // Scan the memory operations on the chain and find the first non-consecutive
9197   // store memory address.
9198   unsigned LastConsecutiveStore = 0;
9199   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9200   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9201
9202     // Check that the addresses are consecutive starting from the second
9203     // element in the list of stores.
9204     if (i > 0) {
9205       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9206       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9207         break;
9208     }
9209
9210     bool Alias = false;
9211     // Check if this store interferes with any of the loads that we found.
9212     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9213       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9214         Alias = true;
9215         break;
9216       }
9217     // We found a load that alias with this store. Stop the sequence.
9218     if (Alias)
9219       break;
9220
9221     // Mark this node as useful.
9222     LastConsecutiveStore = i;
9223   }
9224
9225   // The node with the lowest store address.
9226   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9227
9228   // Store the constants into memory as one consecutive store.
9229   if (!IsLoadSrc) {
9230     unsigned LastLegalType = 0;
9231     unsigned LastLegalVectorType = 0;
9232     bool NonZero = false;
9233     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9234       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9235       SDValue StoredVal = St->getValue();
9236
9237       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9238         NonZero |= !C->isNullValue();
9239       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9240         NonZero |= !C->getConstantFPValue()->isNullValue();
9241       } else {
9242         // Non-constant.
9243         break;
9244       }
9245
9246       // Find a legal type for the constant store.
9247       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9248       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9249       if (TLI.isTypeLegal(StoreTy))
9250         LastLegalType = i+1;
9251       // Or check whether a truncstore is legal.
9252       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9253                TargetLowering::TypePromoteInteger) {
9254         EVT LegalizedStoredValueTy =
9255           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9256         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9257           LastLegalType = i+1;
9258       }
9259
9260       // Find a legal type for the vector store.
9261       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9262       if (TLI.isTypeLegal(Ty))
9263         LastLegalVectorType = i + 1;
9264     }
9265
9266     // We only use vectors if the constant is known to be zero and the
9267     // function is not marked with the noimplicitfloat attribute.
9268     if (NonZero || NoVectors)
9269       LastLegalVectorType = 0;
9270
9271     // Check if we found a legal integer type to store.
9272     if (LastLegalType == 0 && LastLegalVectorType == 0)
9273       return false;
9274
9275     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9276     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9277
9278     // Make sure we have something to merge.
9279     if (NumElem < 2)
9280       return false;
9281
9282     unsigned EarliestNodeUsed = 0;
9283     for (unsigned i=0; i < NumElem; ++i) {
9284       // Find a chain for the new wide-store operand. Notice that some
9285       // of the store nodes that we found may not be selected for inclusion
9286       // in the wide store. The chain we use needs to be the chain of the
9287       // earliest store node which is *used* and replaced by the wide store.
9288       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9289         EarliestNodeUsed = i;
9290     }
9291
9292     // The earliest Node in the DAG.
9293     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9294     SDLoc DL(StoreNodes[0].MemNode);
9295
9296     SDValue StoredVal;
9297     if (UseVector) {
9298       // Find a legal type for the vector store.
9299       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9300       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9301       StoredVal = DAG.getConstant(0, Ty);
9302     } else {
9303       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9304       APInt StoreInt(StoreBW, 0);
9305
9306       // Construct a single integer constant which is made of the smaller
9307       // constant inputs.
9308       bool IsLE = TLI.isLittleEndian();
9309       for (unsigned i = 0; i < NumElem ; ++i) {
9310         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9311         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9312         SDValue Val = St->getValue();
9313         StoreInt<<=ElementSizeBytes*8;
9314         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9315           StoreInt|=C->getAPIntValue().zext(StoreBW);
9316         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9317           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9318         } else {
9319           assert(false && "Invalid constant element type");
9320         }
9321       }
9322
9323       // Create the new Load and Store operations.
9324       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9325       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9326     }
9327
9328     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9329                                     FirstInChain->getBasePtr(),
9330                                     FirstInChain->getPointerInfo(),
9331                                     false, false,
9332                                     FirstInChain->getAlignment());
9333
9334     // Replace the first store with the new store
9335     CombineTo(EarliestOp, NewStore);
9336     // Erase all other stores.
9337     for (unsigned i = 0; i < NumElem ; ++i) {
9338       if (StoreNodes[i].MemNode == EarliestOp)
9339         continue;
9340       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9341       // ReplaceAllUsesWith will replace all uses that existed when it was
9342       // called, but graph optimizations may cause new ones to appear. For
9343       // example, the case in pr14333 looks like
9344       //
9345       //  St's chain -> St -> another store -> X
9346       //
9347       // And the only difference from St to the other store is the chain.
9348       // When we change it's chain to be St's chain they become identical,
9349       // get CSEed and the net result is that X is now a use of St.
9350       // Since we know that St is redundant, just iterate.
9351       while (!St->use_empty())
9352         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9353       removeFromWorklist(St);
9354       DAG.DeleteNode(St);
9355     }
9356
9357     return true;
9358   }
9359
9360   // Below we handle the case of multiple consecutive stores that
9361   // come from multiple consecutive loads. We merge them into a single
9362   // wide load and a single wide store.
9363
9364   // Look for load nodes which are used by the stored values.
9365   SmallVector<MemOpLink, 8> LoadNodes;
9366
9367   // Find acceptable loads. Loads need to have the same chain (token factor),
9368   // must not be zext, volatile, indexed, and they must be consecutive.
9369   BaseIndexOffset LdBasePtr;
9370   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9371     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9372     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9373     if (!Ld) break;
9374
9375     // Loads must only have one use.
9376     if (!Ld->hasNUsesOfValue(1, 0))
9377       break;
9378
9379     // Check that the alignment is the same as the stores.
9380     if (Ld->getAlignment() != St->getAlignment())
9381       break;
9382
9383     // The memory operands must not be volatile.
9384     if (Ld->isVolatile() || Ld->isIndexed())
9385       break;
9386
9387     // We do not accept ext loads.
9388     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9389       break;
9390
9391     // The stored memory type must be the same.
9392     if (Ld->getMemoryVT() != MemVT)
9393       break;
9394
9395     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9396     // If this is not the first ptr that we check.
9397     if (LdBasePtr.Base.getNode()) {
9398       // The base ptr must be the same.
9399       if (!LdPtr.equalBaseIndex(LdBasePtr))
9400         break;
9401     } else {
9402       // Check that all other base pointers are the same as this one.
9403       LdBasePtr = LdPtr;
9404     }
9405
9406     // We found a potential memory operand to merge.
9407     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9408   }
9409
9410   if (LoadNodes.size() < 2)
9411     return false;
9412
9413   // Scan the memory operations on the chain and find the first non-consecutive
9414   // load memory address. These variables hold the index in the store node
9415   // array.
9416   unsigned LastConsecutiveLoad = 0;
9417   // This variable refers to the size and not index in the array.
9418   unsigned LastLegalVectorType = 0;
9419   unsigned LastLegalIntegerType = 0;
9420   StartAddress = LoadNodes[0].OffsetFromBase;
9421   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9422   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9423     // All loads much share the same chain.
9424     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9425       break;
9426
9427     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9428     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9429       break;
9430     LastConsecutiveLoad = i;
9431
9432     // Find a legal type for the vector store.
9433     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9434     if (TLI.isTypeLegal(StoreTy))
9435       LastLegalVectorType = i + 1;
9436
9437     // Find a legal type for the integer store.
9438     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9439     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9440     if (TLI.isTypeLegal(StoreTy))
9441       LastLegalIntegerType = i + 1;
9442     // Or check whether a truncstore and extload is legal.
9443     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9444              TargetLowering::TypePromoteInteger) {
9445       EVT LegalizedStoredValueTy =
9446         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9447       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9448           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9449           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9450           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9451         LastLegalIntegerType = i+1;
9452     }
9453   }
9454
9455   // Only use vector types if the vector type is larger than the integer type.
9456   // If they are the same, use integers.
9457   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9458   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9459
9460   // We add +1 here because the LastXXX variables refer to location while
9461   // the NumElem refers to array/index size.
9462   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9463   NumElem = std::min(LastLegalType, NumElem);
9464
9465   if (NumElem < 2)
9466     return false;
9467
9468   // The earliest Node in the DAG.
9469   unsigned EarliestNodeUsed = 0;
9470   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9471   for (unsigned i=1; i<NumElem; ++i) {
9472     // Find a chain for the new wide-store operand. Notice that some
9473     // of the store nodes that we found may not be selected for inclusion
9474     // in the wide store. The chain we use needs to be the chain of the
9475     // earliest store node which is *used* and replaced by the wide store.
9476     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9477       EarliestNodeUsed = i;
9478   }
9479
9480   // Find if it is better to use vectors or integers to load and store
9481   // to memory.
9482   EVT JointMemOpVT;
9483   if (UseVectorTy) {
9484     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9485   } else {
9486     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9487     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9488   }
9489
9490   SDLoc LoadDL(LoadNodes[0].MemNode);
9491   SDLoc StoreDL(StoreNodes[0].MemNode);
9492
9493   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9494   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9495                                 FirstLoad->getChain(),
9496                                 FirstLoad->getBasePtr(),
9497                                 FirstLoad->getPointerInfo(),
9498                                 false, false, false,
9499                                 FirstLoad->getAlignment());
9500
9501   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9502                                   FirstInChain->getBasePtr(),
9503                                   FirstInChain->getPointerInfo(), false, false,
9504                                   FirstInChain->getAlignment());
9505
9506   // Replace one of the loads with the new load.
9507   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9508   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9509                                 SDValue(NewLoad.getNode(), 1));
9510
9511   // Remove the rest of the load chains.
9512   for (unsigned i = 1; i < NumElem ; ++i) {
9513     // Replace all chain users of the old load nodes with the chain of the new
9514     // load node.
9515     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9516     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9517   }
9518
9519   // Replace the first store with the new store.
9520   CombineTo(EarliestOp, NewStore);
9521   // Erase all other stores.
9522   for (unsigned i = 0; i < NumElem ; ++i) {
9523     // Remove all Store nodes.
9524     if (StoreNodes[i].MemNode == EarliestOp)
9525       continue;
9526     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9527     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9528     removeFromWorklist(St);
9529     DAG.DeleteNode(St);
9530   }
9531
9532   return true;
9533 }
9534
9535 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9536   StoreSDNode *ST  = cast<StoreSDNode>(N);
9537   SDValue Chain = ST->getChain();
9538   SDValue Value = ST->getValue();
9539   SDValue Ptr   = ST->getBasePtr();
9540
9541   // If this is a store of a bit convert, store the input value if the
9542   // resultant store does not need a higher alignment than the original.
9543   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9544       ST->isUnindexed()) {
9545     unsigned OrigAlign = ST->getAlignment();
9546     EVT SVT = Value.getOperand(0).getValueType();
9547     unsigned Align = TLI.getDataLayout()->
9548       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9549     if (Align <= OrigAlign &&
9550         ((!LegalOperations && !ST->isVolatile()) ||
9551          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9552       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9553                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9554                           ST->isNonTemporal(), OrigAlign,
9555                           ST->getAAInfo());
9556   }
9557
9558   // Turn 'store undef, Ptr' -> nothing.
9559   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9560     return Chain;
9561
9562   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9563   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9564     // NOTE: If the original store is volatile, this transform must not increase
9565     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9566     // processor operation but an i64 (which is not legal) requires two.  So the
9567     // transform should not be done in this case.
9568     if (Value.getOpcode() != ISD::TargetConstantFP) {
9569       SDValue Tmp;
9570       switch (CFP->getSimpleValueType(0).SimpleTy) {
9571       default: llvm_unreachable("Unknown FP type");
9572       case MVT::f16:    // We don't do this for these yet.
9573       case MVT::f80:
9574       case MVT::f128:
9575       case MVT::ppcf128:
9576         break;
9577       case MVT::f32:
9578         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9579             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9580           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9581                               bitcastToAPInt().getZExtValue(), MVT::i32);
9582           return DAG.getStore(Chain, SDLoc(N), Tmp,
9583                               Ptr, ST->getMemOperand());
9584         }
9585         break;
9586       case MVT::f64:
9587         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9588              !ST->isVolatile()) ||
9589             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9590           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9591                                 getZExtValue(), MVT::i64);
9592           return DAG.getStore(Chain, SDLoc(N), Tmp,
9593                               Ptr, ST->getMemOperand());
9594         }
9595
9596         if (!ST->isVolatile() &&
9597             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9598           // Many FP stores are not made apparent until after legalize, e.g. for
9599           // argument passing.  Since this is so common, custom legalize the
9600           // 64-bit integer store into two 32-bit stores.
9601           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9602           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9603           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9604           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9605
9606           unsigned Alignment = ST->getAlignment();
9607           bool isVolatile = ST->isVolatile();
9608           bool isNonTemporal = ST->isNonTemporal();
9609           AAMDNodes AAInfo = ST->getAAInfo();
9610
9611           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9612                                      Ptr, ST->getPointerInfo(),
9613                                      isVolatile, isNonTemporal,
9614                                      ST->getAlignment(), AAInfo);
9615           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9616                             DAG.getConstant(4, Ptr.getValueType()));
9617           Alignment = MinAlign(Alignment, 4U);
9618           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9619                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9620                                      isVolatile, isNonTemporal,
9621                                      Alignment, AAInfo);
9622           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9623                              St0, St1);
9624         }
9625
9626         break;
9627       }
9628     }
9629   }
9630
9631   // Try to infer better alignment information than the store already has.
9632   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9633     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9634       if (Align > ST->getAlignment())
9635         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9636                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9637                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9638                                  ST->getAAInfo());
9639     }
9640   }
9641
9642   // Try transforming a pair floating point load / store ops to integer
9643   // load / store ops.
9644   SDValue NewST = TransformFPLoadStorePair(N);
9645   if (NewST.getNode())
9646     return NewST;
9647
9648   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9649     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9650 #ifndef NDEBUG
9651   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9652       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9653     UseAA = false;
9654 #endif
9655   if (UseAA && ST->isUnindexed()) {
9656     // Walk up chain skipping non-aliasing memory nodes.
9657     SDValue BetterChain = FindBetterChain(N, Chain);
9658
9659     // If there is a better chain.
9660     if (Chain != BetterChain) {
9661       SDValue ReplStore;
9662
9663       // Replace the chain to avoid dependency.
9664       if (ST->isTruncatingStore()) {
9665         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9666                                       ST->getMemoryVT(), ST->getMemOperand());
9667       } else {
9668         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9669                                  ST->getMemOperand());
9670       }
9671
9672       // Create token to keep both nodes around.
9673       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9674                                   MVT::Other, Chain, ReplStore);
9675
9676       // Make sure the new and old chains are cleaned up.
9677       AddToWorklist(Token.getNode());
9678
9679       // Don't add users to work list.
9680       return CombineTo(N, Token, false);
9681     }
9682   }
9683
9684   // Try transforming N to an indexed store.
9685   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9686     return SDValue(N, 0);
9687
9688   // FIXME: is there such a thing as a truncating indexed store?
9689   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9690       Value.getValueType().isInteger()) {
9691     // See if we can simplify the input to this truncstore with knowledge that
9692     // only the low bits are being used.  For example:
9693     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9694     SDValue Shorter =
9695       GetDemandedBits(Value,
9696                       APInt::getLowBitsSet(
9697                         Value.getValueType().getScalarType().getSizeInBits(),
9698                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9699     AddToWorklist(Value.getNode());
9700     if (Shorter.getNode())
9701       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9702                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9703
9704     // Otherwise, see if we can simplify the operation with
9705     // SimplifyDemandedBits, which only works if the value has a single use.
9706     if (SimplifyDemandedBits(Value,
9707                         APInt::getLowBitsSet(
9708                           Value.getValueType().getScalarType().getSizeInBits(),
9709                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9710       return SDValue(N, 0);
9711   }
9712
9713   // If this is a load followed by a store to the same location, then the store
9714   // is dead/noop.
9715   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9716     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9717         ST->isUnindexed() && !ST->isVolatile() &&
9718         // There can't be any side effects between the load and store, such as
9719         // a call or store.
9720         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9721       // The store is dead, remove it.
9722       return Chain;
9723     }
9724   }
9725
9726   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9727   // truncating store.  We can do this even if this is already a truncstore.
9728   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9729       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9730       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9731                             ST->getMemoryVT())) {
9732     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9733                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9734   }
9735
9736   // Only perform this optimization before the types are legal, because we
9737   // don't want to perform this optimization on every DAGCombine invocation.
9738   if (!LegalTypes) {
9739     bool EverChanged = false;
9740
9741     do {
9742       // There can be multiple store sequences on the same chain.
9743       // Keep trying to merge store sequences until we are unable to do so
9744       // or until we merge the last store on the chain.
9745       bool Changed = MergeConsecutiveStores(ST);
9746       EverChanged |= Changed;
9747       if (!Changed) break;
9748     } while (ST->getOpcode() != ISD::DELETED_NODE);
9749
9750     if (EverChanged)
9751       return SDValue(N, 0);
9752   }
9753
9754   return ReduceLoadOpStoreWidth(N);
9755 }
9756
9757 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9758   SDValue InVec = N->getOperand(0);
9759   SDValue InVal = N->getOperand(1);
9760   SDValue EltNo = N->getOperand(2);
9761   SDLoc dl(N);
9762
9763   // If the inserted element is an UNDEF, just use the input vector.
9764   if (InVal.getOpcode() == ISD::UNDEF)
9765     return InVec;
9766
9767   EVT VT = InVec.getValueType();
9768
9769   // If we can't generate a legal BUILD_VECTOR, exit
9770   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9771     return SDValue();
9772
9773   // Check that we know which element is being inserted
9774   if (!isa<ConstantSDNode>(EltNo))
9775     return SDValue();
9776   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9777
9778   // Canonicalize insert_vector_elt dag nodes.
9779   // Example:
9780   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9781   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9782   //
9783   // Do this only if the child insert_vector node has one use; also
9784   // do this only if indices are both constants and Idx1 < Idx0.
9785   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9786       && isa<ConstantSDNode>(InVec.getOperand(2))) {
9787     unsigned OtherElt =
9788       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9789     if (Elt < OtherElt) {
9790       // Swap nodes.
9791       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9792                                   InVec.getOperand(0), InVal, EltNo);
9793       AddToWorklist(NewOp.getNode());
9794       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9795                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9796     }
9797   }
9798
9799   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9800   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9801   // vector elements.
9802   SmallVector<SDValue, 8> Ops;
9803   // Do not combine these two vectors if the output vector will not replace
9804   // the input vector.
9805   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9806     Ops.append(InVec.getNode()->op_begin(),
9807                InVec.getNode()->op_end());
9808   } else if (InVec.getOpcode() == ISD::UNDEF) {
9809     unsigned NElts = VT.getVectorNumElements();
9810     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9811   } else {
9812     return SDValue();
9813   }
9814
9815   // Insert the element
9816   if (Elt < Ops.size()) {
9817     // All the operands of BUILD_VECTOR must have the same type;
9818     // we enforce that here.
9819     EVT OpVT = Ops[0].getValueType();
9820     if (InVal.getValueType() != OpVT)
9821       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9822                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9823                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9824     Ops[Elt] = InVal;
9825   }
9826
9827   // Return the new vector
9828   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9829 }
9830
9831 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9832   // (vextract (scalar_to_vector val, 0) -> val
9833   SDValue InVec = N->getOperand(0);
9834   EVT VT = InVec.getValueType();
9835   EVT NVT = N->getValueType(0);
9836
9837   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9838     // Check if the result type doesn't match the inserted element type. A
9839     // SCALAR_TO_VECTOR may truncate the inserted element and the
9840     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9841     SDValue InOp = InVec.getOperand(0);
9842     if (InOp.getValueType() != NVT) {
9843       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9844       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9845     }
9846     return InOp;
9847   }
9848
9849   SDValue EltNo = N->getOperand(1);
9850   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9851
9852   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9853   // We only perform this optimization before the op legalization phase because
9854   // we may introduce new vector instructions which are not backed by TD
9855   // patterns. For example on AVX, extracting elements from a wide vector
9856   // without using extract_subvector. However, if we can find an underlying
9857   // scalar value, then we can always use that.
9858   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9859       && ConstEltNo) {
9860     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9861     int NumElem = VT.getVectorNumElements();
9862     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9863     // Find the new index to extract from.
9864     int OrigElt = SVOp->getMaskElt(Elt);
9865
9866     // Extracting an undef index is undef.
9867     if (OrigElt == -1)
9868       return DAG.getUNDEF(NVT);
9869
9870     // Select the right vector half to extract from.
9871     SDValue SVInVec;
9872     if (OrigElt < NumElem) {
9873       SVInVec = InVec->getOperand(0);
9874     } else {
9875       SVInVec = InVec->getOperand(1);
9876       OrigElt -= NumElem;
9877     }
9878
9879     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9880       SDValue InOp = SVInVec.getOperand(OrigElt);
9881       if (InOp.getValueType() != NVT) {
9882         assert(InOp.getValueType().isInteger() && NVT.isInteger());
9883         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9884       }
9885
9886       return InOp;
9887     }
9888
9889     // FIXME: We should handle recursing on other vector shuffles and
9890     // scalar_to_vector here as well.
9891
9892     if (!LegalOperations) {
9893       EVT IndexTy = TLI.getVectorIdxTy();
9894       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9895                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
9896     }
9897   }
9898
9899   // Perform only after legalization to ensure build_vector / vector_shuffle
9900   // optimizations have already been done.
9901   if (!LegalOperations) return SDValue();
9902
9903   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9904   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9905   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9906
9907   if (ConstEltNo) {
9908     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9909     bool NewLoad = false;
9910     bool BCNumEltsChanged = false;
9911     EVT ExtVT = VT.getVectorElementType();
9912     EVT LVT = ExtVT;
9913
9914     // If the result of load has to be truncated, then it's not necessarily
9915     // profitable.
9916     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9917       return SDValue();
9918
9919     if (InVec.getOpcode() == ISD::BITCAST) {
9920       // Don't duplicate a load with other uses.
9921       if (!InVec.hasOneUse())
9922         return SDValue();
9923
9924       EVT BCVT = InVec.getOperand(0).getValueType();
9925       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9926         return SDValue();
9927       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9928         BCNumEltsChanged = true;
9929       InVec = InVec.getOperand(0);
9930       ExtVT = BCVT.getVectorElementType();
9931       NewLoad = true;
9932     }
9933
9934     LoadSDNode *LN0 = nullptr;
9935     const ShuffleVectorSDNode *SVN = nullptr;
9936     if (ISD::isNormalLoad(InVec.getNode())) {
9937       LN0 = cast<LoadSDNode>(InVec);
9938     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9939                InVec.getOperand(0).getValueType() == ExtVT &&
9940                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9941       // Don't duplicate a load with other uses.
9942       if (!InVec.hasOneUse())
9943         return SDValue();
9944
9945       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9946     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9947       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9948       // =>
9949       // (load $addr+1*size)
9950
9951       // Don't duplicate a load with other uses.
9952       if (!InVec.hasOneUse())
9953         return SDValue();
9954
9955       // If the bit convert changed the number of elements, it is unsafe
9956       // to examine the mask.
9957       if (BCNumEltsChanged)
9958         return SDValue();
9959
9960       // Select the input vector, guarding against out of range extract vector.
9961       unsigned NumElems = VT.getVectorNumElements();
9962       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9963       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9964
9965       if (InVec.getOpcode() == ISD::BITCAST) {
9966         // Don't duplicate a load with other uses.
9967         if (!InVec.hasOneUse())
9968           return SDValue();
9969
9970         InVec = InVec.getOperand(0);
9971       }
9972       if (ISD::isNormalLoad(InVec.getNode())) {
9973         LN0 = cast<LoadSDNode>(InVec);
9974         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9975       }
9976     }
9977
9978     // Make sure we found a non-volatile load and the extractelement is
9979     // the only use.
9980     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9981       return SDValue();
9982
9983     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9984     if (Elt == -1)
9985       return DAG.getUNDEF(LVT);
9986
9987     unsigned Align = LN0->getAlignment();
9988     if (NewLoad) {
9989       // Check the resultant load doesn't need a higher alignment than the
9990       // original load.
9991       unsigned NewAlign =
9992         TLI.getDataLayout()
9993             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9994
9995       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9996         return SDValue();
9997
9998       Align = NewAlign;
9999     }
10000
10001     SDValue NewPtr = LN0->getBasePtr();
10002     unsigned PtrOff = 0;
10003
10004     if (Elt) {
10005       PtrOff = LVT.getSizeInBits() * Elt / 8;
10006       EVT PtrType = NewPtr.getValueType();
10007       if (TLI.isBigEndian())
10008         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
10009       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
10010                            DAG.getConstant(PtrOff, PtrType));
10011     }
10012
10013     // The replacement we need to do here is a little tricky: we need to
10014     // replace an extractelement of a load with a load.
10015     // Use ReplaceAllUsesOfValuesWith to do the replacement.
10016     // Note that this replacement assumes that the extractvalue is the only
10017     // use of the load; that's okay because we don't want to perform this
10018     // transformation in other cases anyway.
10019     SDValue Load;
10020     SDValue Chain;
10021     if (NVT.bitsGT(LVT)) {
10022       // If the result type of vextract is wider than the load, then issue an
10023       // extending load instead.
10024       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
10025         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
10026       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
10027                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
10028                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
10029                             Align, LN0->getAAInfo());
10030       Chain = Load.getValue(1);
10031     } else {
10032       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
10033                          LN0->getPointerInfo().getWithOffset(PtrOff),
10034                          LN0->isVolatile(), LN0->isNonTemporal(),
10035                          LN0->isInvariant(), Align, LN0->getAAInfo());
10036       Chain = Load.getValue(1);
10037       if (NVT.bitsLT(LVT))
10038         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
10039       else
10040         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
10041     }
10042     WorklistRemover DeadNodes(*this);
10043     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
10044     SDValue To[] = { Load, Chain };
10045     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10046     // Since we're explcitly calling ReplaceAllUses, add the new node to the
10047     // worklist explicitly as well.
10048     AddToWorklist(Load.getNode());
10049     AddUsersToWorklist(Load.getNode()); // Add users too
10050     // Make sure to revisit this node to clean it up; it will usually be dead.
10051     AddToWorklist(N);
10052     return SDValue(N, 0);
10053   }
10054
10055   return SDValue();
10056 }
10057
10058 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10059 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10060   // We perform this optimization post type-legalization because
10061   // the type-legalizer often scalarizes integer-promoted vectors.
10062   // Performing this optimization before may create bit-casts which
10063   // will be type-legalized to complex code sequences.
10064   // We perform this optimization only before the operation legalizer because we
10065   // may introduce illegal operations.
10066   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10067     return SDValue();
10068
10069   unsigned NumInScalars = N->getNumOperands();
10070   SDLoc dl(N);
10071   EVT VT = N->getValueType(0);
10072
10073   // Check to see if this is a BUILD_VECTOR of a bunch of values
10074   // which come from any_extend or zero_extend nodes. If so, we can create
10075   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10076   // optimizations. We do not handle sign-extend because we can't fill the sign
10077   // using shuffles.
10078   EVT SourceType = MVT::Other;
10079   bool AllAnyExt = true;
10080
10081   for (unsigned i = 0; i != NumInScalars; ++i) {
10082     SDValue In = N->getOperand(i);
10083     // Ignore undef inputs.
10084     if (In.getOpcode() == ISD::UNDEF) continue;
10085
10086     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10087     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10088
10089     // Abort if the element is not an extension.
10090     if (!ZeroExt && !AnyExt) {
10091       SourceType = MVT::Other;
10092       break;
10093     }
10094
10095     // The input is a ZeroExt or AnyExt. Check the original type.
10096     EVT InTy = In.getOperand(0).getValueType();
10097
10098     // Check that all of the widened source types are the same.
10099     if (SourceType == MVT::Other)
10100       // First time.
10101       SourceType = InTy;
10102     else if (InTy != SourceType) {
10103       // Multiple income types. Abort.
10104       SourceType = MVT::Other;
10105       break;
10106     }
10107
10108     // Check if all of the extends are ANY_EXTENDs.
10109     AllAnyExt &= AnyExt;
10110   }
10111
10112   // In order to have valid types, all of the inputs must be extended from the
10113   // same source type and all of the inputs must be any or zero extend.
10114   // Scalar sizes must be a power of two.
10115   EVT OutScalarTy = VT.getScalarType();
10116   bool ValidTypes = SourceType != MVT::Other &&
10117                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10118                  isPowerOf2_32(SourceType.getSizeInBits());
10119
10120   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10121   // turn into a single shuffle instruction.
10122   if (!ValidTypes)
10123     return SDValue();
10124
10125   bool isLE = TLI.isLittleEndian();
10126   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10127   assert(ElemRatio > 1 && "Invalid element size ratio");
10128   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10129                                DAG.getConstant(0, SourceType);
10130
10131   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10132   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10133
10134   // Populate the new build_vector
10135   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10136     SDValue Cast = N->getOperand(i);
10137     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10138             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10139             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10140     SDValue In;
10141     if (Cast.getOpcode() == ISD::UNDEF)
10142       In = DAG.getUNDEF(SourceType);
10143     else
10144       In = Cast->getOperand(0);
10145     unsigned Index = isLE ? (i * ElemRatio) :
10146                             (i * ElemRatio + (ElemRatio - 1));
10147
10148     assert(Index < Ops.size() && "Invalid index");
10149     Ops[Index] = In;
10150   }
10151
10152   // The type of the new BUILD_VECTOR node.
10153   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10154   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10155          "Invalid vector size");
10156   // Check if the new vector type is legal.
10157   if (!isTypeLegal(VecVT)) return SDValue();
10158
10159   // Make the new BUILD_VECTOR.
10160   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10161
10162   // The new BUILD_VECTOR node has the potential to be further optimized.
10163   AddToWorklist(BV.getNode());
10164   // Bitcast to the desired type.
10165   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10166 }
10167
10168 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10169   EVT VT = N->getValueType(0);
10170
10171   unsigned NumInScalars = N->getNumOperands();
10172   SDLoc dl(N);
10173
10174   EVT SrcVT = MVT::Other;
10175   unsigned Opcode = ISD::DELETED_NODE;
10176   unsigned NumDefs = 0;
10177
10178   for (unsigned i = 0; i != NumInScalars; ++i) {
10179     SDValue In = N->getOperand(i);
10180     unsigned Opc = In.getOpcode();
10181
10182     if (Opc == ISD::UNDEF)
10183       continue;
10184
10185     // If all scalar values are floats and converted from integers.
10186     if (Opcode == ISD::DELETED_NODE &&
10187         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10188       Opcode = Opc;
10189     }
10190
10191     if (Opc != Opcode)
10192       return SDValue();
10193
10194     EVT InVT = In.getOperand(0).getValueType();
10195
10196     // If all scalar values are typed differently, bail out. It's chosen to
10197     // simplify BUILD_VECTOR of integer types.
10198     if (SrcVT == MVT::Other)
10199       SrcVT = InVT;
10200     if (SrcVT != InVT)
10201       return SDValue();
10202     NumDefs++;
10203   }
10204
10205   // If the vector has just one element defined, it's not worth to fold it into
10206   // a vectorized one.
10207   if (NumDefs < 2)
10208     return SDValue();
10209
10210   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10211          && "Should only handle conversion from integer to float.");
10212   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10213
10214   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10215
10216   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10217     return SDValue();
10218
10219   SmallVector<SDValue, 8> Opnds;
10220   for (unsigned i = 0; i != NumInScalars; ++i) {
10221     SDValue In = N->getOperand(i);
10222
10223     if (In.getOpcode() == ISD::UNDEF)
10224       Opnds.push_back(DAG.getUNDEF(SrcVT));
10225     else
10226       Opnds.push_back(In.getOperand(0));
10227   }
10228   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10229   AddToWorklist(BV.getNode());
10230
10231   return DAG.getNode(Opcode, dl, VT, BV);
10232 }
10233
10234 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10235   unsigned NumInScalars = N->getNumOperands();
10236   SDLoc dl(N);
10237   EVT VT = N->getValueType(0);
10238
10239   // A vector built entirely of undefs is undef.
10240   if (ISD::allOperandsUndef(N))
10241     return DAG.getUNDEF(VT);
10242
10243   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10244   if (V.getNode())
10245     return V;
10246
10247   V = reduceBuildVecConvertToConvertBuildVec(N);
10248   if (V.getNode())
10249     return V;
10250
10251   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10252   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10253   // at most two distinct vectors, turn this into a shuffle node.
10254
10255   // May only combine to shuffle after legalize if shuffle is legal.
10256   if (LegalOperations &&
10257       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10258     return SDValue();
10259
10260   SDValue VecIn1, VecIn2;
10261   for (unsigned i = 0; i != NumInScalars; ++i) {
10262     // Ignore undef inputs.
10263     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10264
10265     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10266     // constant index, bail out.
10267     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10268         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10269       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10270       break;
10271     }
10272
10273     // We allow up to two distinct input vectors.
10274     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10275     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10276       continue;
10277
10278     if (!VecIn1.getNode()) {
10279       VecIn1 = ExtractedFromVec;
10280     } else if (!VecIn2.getNode()) {
10281       VecIn2 = ExtractedFromVec;
10282     } else {
10283       // Too many inputs.
10284       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10285       break;
10286     }
10287   }
10288
10289   // If everything is good, we can make a shuffle operation.
10290   if (VecIn1.getNode()) {
10291     SmallVector<int, 8> Mask;
10292     for (unsigned i = 0; i != NumInScalars; ++i) {
10293       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10294         Mask.push_back(-1);
10295         continue;
10296       }
10297
10298       // If extracting from the first vector, just use the index directly.
10299       SDValue Extract = N->getOperand(i);
10300       SDValue ExtVal = Extract.getOperand(1);
10301       if (Extract.getOperand(0) == VecIn1) {
10302         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10303         if (ExtIndex > VT.getVectorNumElements())
10304           return SDValue();
10305
10306         Mask.push_back(ExtIndex);
10307         continue;
10308       }
10309
10310       // Otherwise, use InIdx + VecSize
10311       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10312       Mask.push_back(Idx+NumInScalars);
10313     }
10314
10315     // We can't generate a shuffle node with mismatched input and output types.
10316     // Attempt to transform a single input vector to the correct type.
10317     if ((VT != VecIn1.getValueType())) {
10318       // We don't support shuffeling between TWO values of different types.
10319       if (VecIn2.getNode())
10320         return SDValue();
10321
10322       // We only support widening of vectors which are half the size of the
10323       // output registers. For example XMM->YMM widening on X86 with AVX.
10324       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10325         return SDValue();
10326
10327       // If the input vector type has a different base type to the output
10328       // vector type, bail out.
10329       if (VecIn1.getValueType().getVectorElementType() !=
10330           VT.getVectorElementType())
10331         return SDValue();
10332
10333       // Widen the input vector by adding undef values.
10334       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10335                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10336     }
10337
10338     // If VecIn2 is unused then change it to undef.
10339     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10340
10341     // Check that we were able to transform all incoming values to the same
10342     // type.
10343     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10344         VecIn1.getValueType() != VT)
10345           return SDValue();
10346
10347     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10348     if (!isTypeLegal(VT))
10349       return SDValue();
10350
10351     // Return the new VECTOR_SHUFFLE node.
10352     SDValue Ops[2];
10353     Ops[0] = VecIn1;
10354     Ops[1] = VecIn2;
10355     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10356   }
10357
10358   return SDValue();
10359 }
10360
10361 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10362   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10363   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10364   // inputs come from at most two distinct vectors, turn this into a shuffle
10365   // node.
10366
10367   // If we only have one input vector, we don't need to do any concatenation.
10368   if (N->getNumOperands() == 1)
10369     return N->getOperand(0);
10370
10371   // Check if all of the operands are undefs.
10372   EVT VT = N->getValueType(0);
10373   if (ISD::allOperandsUndef(N))
10374     return DAG.getUNDEF(VT);
10375
10376   // Optimize concat_vectors where one of the vectors is undef.
10377   if (N->getNumOperands() == 2 &&
10378       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10379     SDValue In = N->getOperand(0);
10380     assert(In.getValueType().isVector() && "Must concat vectors");
10381
10382     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10383     if (In->getOpcode() == ISD::BITCAST &&
10384         !In->getOperand(0)->getValueType(0).isVector()) {
10385       SDValue Scalar = In->getOperand(0);
10386       EVT SclTy = Scalar->getValueType(0);
10387
10388       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10389         return SDValue();
10390
10391       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10392                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10393       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10394         return SDValue();
10395
10396       SDLoc dl = SDLoc(N);
10397       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10398       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10399     }
10400   }
10401
10402   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10403   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10404   if (N->getNumOperands() == 2 &&
10405       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10406       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10407     EVT VT = N->getValueType(0);
10408     SDValue N0 = N->getOperand(0);
10409     SDValue N1 = N->getOperand(1);
10410     SmallVector<SDValue, 8> Opnds;
10411     unsigned BuildVecNumElts =  N0.getNumOperands();
10412
10413     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10414     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10415     if (SclTy0.isFloatingPoint()) {
10416       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10417         Opnds.push_back(N0.getOperand(i));
10418       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10419         Opnds.push_back(N1.getOperand(i));
10420     } else {
10421       // If BUILD_VECTOR are from built from integer, they may have different
10422       // operand types. Get the smaller type and truncate all operands to it.
10423       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10424       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10425         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10426                         N0.getOperand(i)));
10427       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10428         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10429                         N1.getOperand(i)));
10430     }
10431
10432     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10433   }
10434
10435   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10436   // nodes often generate nop CONCAT_VECTOR nodes.
10437   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10438   // place the incoming vectors at the exact same location.
10439   SDValue SingleSource = SDValue();
10440   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10441
10442   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10443     SDValue Op = N->getOperand(i);
10444
10445     if (Op.getOpcode() == ISD::UNDEF)
10446       continue;
10447
10448     // Check if this is the identity extract:
10449     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10450       return SDValue();
10451
10452     // Find the single incoming vector for the extract_subvector.
10453     if (SingleSource.getNode()) {
10454       if (Op.getOperand(0) != SingleSource)
10455         return SDValue();
10456     } else {
10457       SingleSource = Op.getOperand(0);
10458
10459       // Check the source type is the same as the type of the result.
10460       // If not, this concat may extend the vector, so we can not
10461       // optimize it away.
10462       if (SingleSource.getValueType() != N->getValueType(0))
10463         return SDValue();
10464     }
10465
10466     unsigned IdentityIndex = i * PartNumElem;
10467     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10468     // The extract index must be constant.
10469     if (!CS)
10470       return SDValue();
10471
10472     // Check that we are reading from the identity index.
10473     if (CS->getZExtValue() != IdentityIndex)
10474       return SDValue();
10475   }
10476
10477   if (SingleSource.getNode())
10478     return SingleSource;
10479
10480   return SDValue();
10481 }
10482
10483 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10484   EVT NVT = N->getValueType(0);
10485   SDValue V = N->getOperand(0);
10486
10487   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10488     // Combine:
10489     //    (extract_subvec (concat V1, V2, ...), i)
10490     // Into:
10491     //    Vi if possible
10492     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10493     // type.
10494     if (V->getOperand(0).getValueType() != NVT)
10495       return SDValue();
10496     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10497     unsigned NumElems = NVT.getVectorNumElements();
10498     assert((Idx % NumElems) == 0 &&
10499            "IDX in concat is not a multiple of the result vector length.");
10500     return V->getOperand(Idx / NumElems);
10501   }
10502
10503   // Skip bitcasting
10504   if (V->getOpcode() == ISD::BITCAST)
10505     V = V.getOperand(0);
10506
10507   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10508     SDLoc dl(N);
10509     // Handle only simple case where vector being inserted and vector
10510     // being extracted are of same type, and are half size of larger vectors.
10511     EVT BigVT = V->getOperand(0).getValueType();
10512     EVT SmallVT = V->getOperand(1).getValueType();
10513     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10514       return SDValue();
10515
10516     // Only handle cases where both indexes are constants with the same type.
10517     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10518     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10519
10520     if (InsIdx && ExtIdx &&
10521         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10522         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10523       // Combine:
10524       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10525       // Into:
10526       //    indices are equal or bit offsets are equal => V1
10527       //    otherwise => (extract_subvec V1, ExtIdx)
10528       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10529           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10530         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10531       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10532                          DAG.getNode(ISD::BITCAST, dl,
10533                                      N->getOperand(0).getValueType(),
10534                                      V->getOperand(0)), N->getOperand(1));
10535     }
10536   }
10537
10538   return SDValue();
10539 }
10540
10541 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10542 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10543   EVT VT = N->getValueType(0);
10544   unsigned NumElts = VT.getVectorNumElements();
10545
10546   SDValue N0 = N->getOperand(0);
10547   SDValue N1 = N->getOperand(1);
10548   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10549
10550   SmallVector<SDValue, 4> Ops;
10551   EVT ConcatVT = N0.getOperand(0).getValueType();
10552   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10553   unsigned NumConcats = NumElts / NumElemsPerConcat;
10554
10555   // Look at every vector that's inserted. We're looking for exact
10556   // subvector-sized copies from a concatenated vector
10557   for (unsigned I = 0; I != NumConcats; ++I) {
10558     // Make sure we're dealing with a copy.
10559     unsigned Begin = I * NumElemsPerConcat;
10560     bool AllUndef = true, NoUndef = true;
10561     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10562       if (SVN->getMaskElt(J) >= 0)
10563         AllUndef = false;
10564       else
10565         NoUndef = false;
10566     }
10567
10568     if (NoUndef) {
10569       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10570         return SDValue();
10571
10572       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10573         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10574           return SDValue();
10575
10576       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10577       if (FirstElt < N0.getNumOperands())
10578         Ops.push_back(N0.getOperand(FirstElt));
10579       else
10580         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10581
10582     } else if (AllUndef) {
10583       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10584     } else { // Mixed with general masks and undefs, can't do optimization.
10585       return SDValue();
10586     }
10587   }
10588
10589   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10590 }
10591
10592 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10593   EVT VT = N->getValueType(0);
10594   unsigned NumElts = VT.getVectorNumElements();
10595
10596   SDValue N0 = N->getOperand(0);
10597   SDValue N1 = N->getOperand(1);
10598
10599   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10600
10601   // Canonicalize shuffle undef, undef -> undef
10602   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10603     return DAG.getUNDEF(VT);
10604
10605   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10606
10607   // Canonicalize shuffle v, v -> v, undef
10608   if (N0 == N1) {
10609     SmallVector<int, 8> NewMask;
10610     for (unsigned i = 0; i != NumElts; ++i) {
10611       int Idx = SVN->getMaskElt(i);
10612       if (Idx >= (int)NumElts) Idx -= NumElts;
10613       NewMask.push_back(Idx);
10614     }
10615     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10616                                 &NewMask[0]);
10617   }
10618
10619   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10620   if (N0.getOpcode() == ISD::UNDEF) {
10621     SmallVector<int, 8> NewMask;
10622     for (unsigned i = 0; i != NumElts; ++i) {
10623       int Idx = SVN->getMaskElt(i);
10624       if (Idx >= 0) {
10625         if (Idx >= (int)NumElts)
10626           Idx -= NumElts;
10627         else
10628           Idx = -1; // remove reference to lhs
10629       }
10630       NewMask.push_back(Idx);
10631     }
10632     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10633                                 &NewMask[0]);
10634   }
10635
10636   // Remove references to rhs if it is undef
10637   if (N1.getOpcode() == ISD::UNDEF) {
10638     bool Changed = false;
10639     SmallVector<int, 8> NewMask;
10640     for (unsigned i = 0; i != NumElts; ++i) {
10641       int Idx = SVN->getMaskElt(i);
10642       if (Idx >= (int)NumElts) {
10643         Idx = -1;
10644         Changed = true;
10645       }
10646       NewMask.push_back(Idx);
10647     }
10648     if (Changed)
10649       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10650   }
10651
10652   // If it is a splat, check if the argument vector is another splat or a
10653   // build_vector with all scalar elements the same.
10654   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10655     SDNode *V = N0.getNode();
10656
10657     // If this is a bit convert that changes the element type of the vector but
10658     // not the number of vector elements, look through it.  Be careful not to
10659     // look though conversions that change things like v4f32 to v2f64.
10660     if (V->getOpcode() == ISD::BITCAST) {
10661       SDValue ConvInput = V->getOperand(0);
10662       if (ConvInput.getValueType().isVector() &&
10663           ConvInput.getValueType().getVectorNumElements() == NumElts)
10664         V = ConvInput.getNode();
10665     }
10666
10667     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10668       assert(V->getNumOperands() == NumElts &&
10669              "BUILD_VECTOR has wrong number of operands");
10670       SDValue Base;
10671       bool AllSame = true;
10672       for (unsigned i = 0; i != NumElts; ++i) {
10673         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10674           Base = V->getOperand(i);
10675           break;
10676         }
10677       }
10678       // Splat of <u, u, u, u>, return <u, u, u, u>
10679       if (!Base.getNode())
10680         return N0;
10681       for (unsigned i = 0; i != NumElts; ++i) {
10682         if (V->getOperand(i) != Base) {
10683           AllSame = false;
10684           break;
10685         }
10686       }
10687       // Splat of <x, x, x, x>, return <x, x, x, x>
10688       if (AllSame)
10689         return N0;
10690     }
10691   }
10692
10693   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10694       Level < AfterLegalizeVectorOps &&
10695       (N1.getOpcode() == ISD::UNDEF ||
10696       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10697        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10698     SDValue V = partitionShuffleOfConcats(N, DAG);
10699
10700     if (V.getNode())
10701       return V;
10702   }
10703
10704   // If this shuffle node is simply a swizzle of another shuffle node,
10705   // then try to simplify it.
10706   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10707       N1.getOpcode() == ISD::UNDEF) {
10708
10709     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10710
10711     // The incoming shuffle must be of the same type as the result of the
10712     // current shuffle.
10713     assert(OtherSV->getOperand(0).getValueType() == VT &&
10714            "Shuffle types don't match");
10715
10716     SmallVector<int, 4> Mask;
10717     // Compute the combined shuffle mask.
10718     for (unsigned i = 0; i != NumElts; ++i) {
10719       int Idx = SVN->getMaskElt(i);
10720       assert(Idx < (int)NumElts && "Index references undef operand");
10721       // Next, this index comes from the first value, which is the incoming
10722       // shuffle. Adopt the incoming index.
10723       if (Idx >= 0)
10724         Idx = OtherSV->getMaskElt(Idx);
10725       Mask.push_back(Idx);
10726     }
10727     
10728     bool CommuteOperands = false;
10729     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10730       // To be valid, the combine shuffle mask should only reference elements
10731       // from one of the two vectors in input to the inner shufflevector.
10732       bool IsValidMask = true;
10733       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10734         // See if the combined mask only reference undefs or elements coming
10735         // from the first shufflevector operand.
10736         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10737
10738       if (!IsValidMask) {
10739         IsValidMask = true;
10740         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10741           // Check that all the elements come from the second shuffle operand.
10742           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10743         CommuteOperands = IsValidMask;
10744       }
10745
10746       // Early exit if the combined shuffle mask is not valid.
10747       if (!IsValidMask)
10748         return SDValue();
10749     }
10750
10751     // See if this pair of shuffles can be safely folded according to either
10752     // of the following rules:
10753     //   shuffle(shuffle(x, y), undef) -> x
10754     //   shuffle(shuffle(x, undef), undef) -> x
10755     //   shuffle(shuffle(x, y), undef) -> y
10756     bool IsIdentityMask = true;
10757     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10758     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10759       // Skip Undefs.
10760       if (Mask[i] < 0)
10761         continue;
10762
10763       // The combined shuffle must map each index to itself.
10764       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10765     }
10766     
10767     if (IsIdentityMask) {
10768       if (CommuteOperands)
10769         // optimize shuffle(shuffle(x, y), undef) -> y.
10770         return OtherSV->getOperand(1);
10771       
10772       // optimize shuffle(shuffle(x, undef), undef) -> x
10773       // optimize shuffle(shuffle(x, y), undef) -> x
10774       return OtherSV->getOperand(0);
10775     }
10776
10777     // It may still be beneficial to combine the two shuffles if the
10778     // resulting shuffle is legal.
10779     if (TLI.isTypeLegal(VT) && TLI.isShuffleMaskLegal(Mask, VT)) {
10780       if (!CommuteOperands)
10781         // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10782         // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10783         return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10784                                     &Mask[0]);
10785       
10786       //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(undef, y, M3)
10787       return DAG.getVectorShuffle(VT, SDLoc(N), N1, N0->getOperand(1),
10788                                   &Mask[0]);
10789     }
10790   }
10791
10792   // Canonicalize shuffles according to rules:
10793   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10794   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10795   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10796   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10797       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10798       TLI.isTypeLegal(VT)) {
10799     // The incoming shuffle must be of the same type as the result of the
10800     // current shuffle.
10801     assert(N1->getOperand(0).getValueType() == VT &&
10802            "Shuffle types don't match");
10803
10804     SDValue SV0 = N1->getOperand(0);
10805     SDValue SV1 = N1->getOperand(1);
10806     bool HasSameOp0 = N0 == SV0;
10807     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10808     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10809       // Commute the operands of this shuffle so that next rule
10810       // will trigger.
10811       return DAG.getCommutedVectorShuffle(*SVN);
10812   }
10813
10814   // Try to fold according to rules:
10815   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10816   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10817   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10818   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10819   // Don't try to fold shuffles with illegal type.
10820   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10821       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10822     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10823
10824     // The incoming shuffle must be of the same type as the result of the
10825     // current shuffle.
10826     assert(OtherSV->getOperand(0).getValueType() == VT &&
10827            "Shuffle types don't match");
10828
10829     SDValue SV0 = OtherSV->getOperand(0);
10830     SDValue SV1 = OtherSV->getOperand(1);
10831     bool HasSameOp0 = N1 == SV0;
10832     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10833     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10834       // Early exit.
10835       return SDValue();
10836
10837     SmallVector<int, 4> Mask;
10838     // Compute the combined shuffle mask for a shuffle with SV0 as the first
10839     // operand, and SV1 as the second operand.
10840     for (unsigned i = 0; i != NumElts; ++i) {
10841       int Idx = SVN->getMaskElt(i);
10842       if (Idx < 0) {
10843         // Propagate Undef.
10844         Mask.push_back(Idx);
10845         continue;
10846       }
10847
10848       if (Idx < (int)NumElts) {
10849         Idx = OtherSV->getMaskElt(Idx);
10850         if (IsSV1Undef && Idx >= (int) NumElts)
10851           Idx = -1;  // Propagate Undef.
10852       } else
10853         Idx = HasSameOp0 ? Idx - NumElts : Idx;
10854
10855       Mask.push_back(Idx);
10856     }
10857
10858     // Avoid introducing shuffles with illegal mask.
10859     if (TLI.isShuffleMaskLegal(Mask, VT)) {
10860       if (IsSV1Undef)
10861         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10862         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10863         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10864       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10865     }
10866   }
10867
10868   return SDValue();
10869 }
10870
10871 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10872   SDValue N0 = N->getOperand(0);
10873   SDValue N2 = N->getOperand(2);
10874
10875   // If the input vector is a concatenation, and the insert replaces
10876   // one of the halves, we can optimize into a single concat_vectors.
10877   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10878       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10879     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10880     EVT VT = N->getValueType(0);
10881
10882     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10883     // (concat_vectors Z, Y)
10884     if (InsIdx == 0)
10885       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10886                          N->getOperand(1), N0.getOperand(1));
10887
10888     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10889     // (concat_vectors X, Z)
10890     if (InsIdx == VT.getVectorNumElements()/2)
10891       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10892                          N0.getOperand(0), N->getOperand(1));
10893   }
10894
10895   return SDValue();
10896 }
10897
10898 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10899 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10900 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10901 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10902 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10903   EVT VT = N->getValueType(0);
10904   SDLoc dl(N);
10905   SDValue LHS = N->getOperand(0);
10906   SDValue RHS = N->getOperand(1);
10907   if (N->getOpcode() == ISD::AND) {
10908     if (RHS.getOpcode() == ISD::BITCAST)
10909       RHS = RHS.getOperand(0);
10910     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10911       SmallVector<int, 8> Indices;
10912       unsigned NumElts = RHS.getNumOperands();
10913       for (unsigned i = 0; i != NumElts; ++i) {
10914         SDValue Elt = RHS.getOperand(i);
10915         if (!isa<ConstantSDNode>(Elt))
10916           return SDValue();
10917
10918         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10919           Indices.push_back(i);
10920         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10921           Indices.push_back(NumElts);
10922         else
10923           return SDValue();
10924       }
10925
10926       // Let's see if the target supports this vector_shuffle.
10927       EVT RVT = RHS.getValueType();
10928       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10929         return SDValue();
10930
10931       // Return the new VECTOR_SHUFFLE node.
10932       EVT EltVT = RVT.getVectorElementType();
10933       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10934                                      DAG.getConstant(0, EltVT));
10935       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10936       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10937       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10938       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10939     }
10940   }
10941
10942   return SDValue();
10943 }
10944
10945 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10946 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10947   assert(N->getValueType(0).isVector() &&
10948          "SimplifyVBinOp only works on vectors!");
10949
10950   SDValue LHS = N->getOperand(0);
10951   SDValue RHS = N->getOperand(1);
10952   SDValue Shuffle = XformToShuffleWithZero(N);
10953   if (Shuffle.getNode()) return Shuffle;
10954
10955   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10956   // this operation.
10957   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10958       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10959     // Check if both vectors are constants. If not bail out.
10960     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10961           cast<BuildVectorSDNode>(RHS)->isConstant()))
10962       return SDValue();
10963
10964     SmallVector<SDValue, 8> Ops;
10965     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10966       SDValue LHSOp = LHS.getOperand(i);
10967       SDValue RHSOp = RHS.getOperand(i);
10968
10969       // Can't fold divide by zero.
10970       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10971           N->getOpcode() == ISD::FDIV) {
10972         if ((RHSOp.getOpcode() == ISD::Constant &&
10973              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10974             (RHSOp.getOpcode() == ISD::ConstantFP &&
10975              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10976           break;
10977       }
10978
10979       EVT VT = LHSOp.getValueType();
10980       EVT RVT = RHSOp.getValueType();
10981       if (RVT != VT) {
10982         // Integer BUILD_VECTOR operands may have types larger than the element
10983         // size (e.g., when the element type is not legal).  Prior to type
10984         // legalization, the types may not match between the two BUILD_VECTORS.
10985         // Truncate one of the operands to make them match.
10986         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10987           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10988         } else {
10989           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10990           VT = RVT;
10991         }
10992       }
10993       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10994                                    LHSOp, RHSOp);
10995       if (FoldOp.getOpcode() != ISD::UNDEF &&
10996           FoldOp.getOpcode() != ISD::Constant &&
10997           FoldOp.getOpcode() != ISD::ConstantFP)
10998         break;
10999       Ops.push_back(FoldOp);
11000       AddToWorklist(FoldOp.getNode());
11001     }
11002
11003     if (Ops.size() == LHS.getNumOperands())
11004       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11005   }
11006
11007   // Type legalization might introduce new shuffles in the DAG.
11008   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11009   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11010   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11011       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11012       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11013       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11014     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11015     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11016
11017     if (SVN0->getMask().equals(SVN1->getMask())) {
11018       EVT VT = N->getValueType(0);
11019       SDValue UndefVector = LHS.getOperand(1);
11020       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11021                                      LHS.getOperand(0), RHS.getOperand(0));
11022       AddUsersToWorklist(N);
11023       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11024                                   &SVN0->getMask()[0]);
11025     }
11026   }
11027
11028   return SDValue();
11029 }
11030
11031 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
11032 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11033   assert(N->getValueType(0).isVector() &&
11034          "SimplifyVUnaryOp only works on vectors!");
11035
11036   SDValue N0 = N->getOperand(0);
11037
11038   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11039     return SDValue();
11040
11041   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11042   SmallVector<SDValue, 8> Ops;
11043   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11044     SDValue Op = N0.getOperand(i);
11045     if (Op.getOpcode() != ISD::UNDEF &&
11046         Op.getOpcode() != ISD::ConstantFP)
11047       break;
11048     EVT EltVT = Op.getValueType();
11049     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11050     if (FoldOp.getOpcode() != ISD::UNDEF &&
11051         FoldOp.getOpcode() != ISD::ConstantFP)
11052       break;
11053     Ops.push_back(FoldOp);
11054     AddToWorklist(FoldOp.getNode());
11055   }
11056
11057   if (Ops.size() != N0.getNumOperands())
11058     return SDValue();
11059
11060   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11061 }
11062
11063 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11064                                     SDValue N1, SDValue N2){
11065   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11066
11067   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11068                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11069
11070   // If we got a simplified select_cc node back from SimplifySelectCC, then
11071   // break it down into a new SETCC node, and a new SELECT node, and then return
11072   // the SELECT node, since we were called with a SELECT node.
11073   if (SCC.getNode()) {
11074     // Check to see if we got a select_cc back (to turn into setcc/select).
11075     // Otherwise, just return whatever node we got back, like fabs.
11076     if (SCC.getOpcode() == ISD::SELECT_CC) {
11077       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11078                                   N0.getValueType(),
11079                                   SCC.getOperand(0), SCC.getOperand(1),
11080                                   SCC.getOperand(4));
11081       AddToWorklist(SETCC.getNode());
11082       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
11083                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
11084     }
11085
11086     return SCC;
11087   }
11088   return SDValue();
11089 }
11090
11091 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11092 /// are the two values being selected between, see if we can simplify the
11093 /// select.  Callers of this should assume that TheSelect is deleted if this
11094 /// returns true.  As such, they should return the appropriate thing (e.g. the
11095 /// node) back to the top-level of the DAG combiner loop to avoid it being
11096 /// looked at.
11097 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11098                                     SDValue RHS) {
11099
11100   // Cannot simplify select with vector condition
11101   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11102
11103   // If this is a select from two identical things, try to pull the operation
11104   // through the select.
11105   if (LHS.getOpcode() != RHS.getOpcode() ||
11106       !LHS.hasOneUse() || !RHS.hasOneUse())
11107     return false;
11108
11109   // If this is a load and the token chain is identical, replace the select
11110   // of two loads with a load through a select of the address to load from.
11111   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11112   // constants have been dropped into the constant pool.
11113   if (LHS.getOpcode() == ISD::LOAD) {
11114     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11115     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11116
11117     // Token chains must be identical.
11118     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11119         // Do not let this transformation reduce the number of volatile loads.
11120         LLD->isVolatile() || RLD->isVolatile() ||
11121         // If this is an EXTLOAD, the VT's must match.
11122         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11123         // If this is an EXTLOAD, the kind of extension must match.
11124         (LLD->getExtensionType() != RLD->getExtensionType() &&
11125          // The only exception is if one of the extensions is anyext.
11126          LLD->getExtensionType() != ISD::EXTLOAD &&
11127          RLD->getExtensionType() != ISD::EXTLOAD) ||
11128         // FIXME: this discards src value information.  This is
11129         // over-conservative. It would be beneficial to be able to remember
11130         // both potential memory locations.  Since we are discarding
11131         // src value info, don't do the transformation if the memory
11132         // locations are not in the default address space.
11133         LLD->getPointerInfo().getAddrSpace() != 0 ||
11134         RLD->getPointerInfo().getAddrSpace() != 0 ||
11135         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11136                                       LLD->getBasePtr().getValueType()))
11137       return false;
11138
11139     // Check that the select condition doesn't reach either load.  If so,
11140     // folding this will induce a cycle into the DAG.  If not, this is safe to
11141     // xform, so create a select of the addresses.
11142     SDValue Addr;
11143     if (TheSelect->getOpcode() == ISD::SELECT) {
11144       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11145       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11146           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11147         return false;
11148       // The loads must not depend on one another.
11149       if (LLD->isPredecessorOf(RLD) ||
11150           RLD->isPredecessorOf(LLD))
11151         return false;
11152       Addr = DAG.getSelect(SDLoc(TheSelect),
11153                            LLD->getBasePtr().getValueType(),
11154                            TheSelect->getOperand(0), LLD->getBasePtr(),
11155                            RLD->getBasePtr());
11156     } else {  // Otherwise SELECT_CC
11157       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11158       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11159
11160       if ((LLD->hasAnyUseOfValue(1) &&
11161            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11162           (RLD->hasAnyUseOfValue(1) &&
11163            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11164         return false;
11165
11166       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11167                          LLD->getBasePtr().getValueType(),
11168                          TheSelect->getOperand(0),
11169                          TheSelect->getOperand(1),
11170                          LLD->getBasePtr(), RLD->getBasePtr(),
11171                          TheSelect->getOperand(4));
11172     }
11173
11174     SDValue Load;
11175     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11176       Load = DAG.getLoad(TheSelect->getValueType(0),
11177                          SDLoc(TheSelect),
11178                          // FIXME: Discards pointer and AA info.
11179                          LLD->getChain(), Addr, MachinePointerInfo(),
11180                          LLD->isVolatile(), LLD->isNonTemporal(),
11181                          LLD->isInvariant(), LLD->getAlignment());
11182     } else {
11183       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11184                             RLD->getExtensionType() : LLD->getExtensionType(),
11185                             SDLoc(TheSelect),
11186                             TheSelect->getValueType(0),
11187                             // FIXME: Discards pointer and AA info.
11188                             LLD->getChain(), Addr, MachinePointerInfo(),
11189                             LLD->getMemoryVT(), LLD->isVolatile(),
11190                             LLD->isNonTemporal(), LLD->getAlignment());
11191     }
11192
11193     // Users of the select now use the result of the load.
11194     CombineTo(TheSelect, Load);
11195
11196     // Users of the old loads now use the new load's chain.  We know the
11197     // old-load value is dead now.
11198     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11199     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11200     return true;
11201   }
11202
11203   return false;
11204 }
11205
11206 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11207 /// where 'cond' is the comparison specified by CC.
11208 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11209                                       SDValue N2, SDValue N3,
11210                                       ISD::CondCode CC, bool NotExtCompare) {
11211   // (x ? y : y) -> y.
11212   if (N2 == N3) return N2;
11213
11214   EVT VT = N2.getValueType();
11215   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11216   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11217   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11218
11219   // Determine if the condition we're dealing with is constant
11220   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11221                               N0, N1, CC, DL, false);
11222   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11223   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11224
11225   // fold select_cc true, x, y -> x
11226   if (SCCC && !SCCC->isNullValue())
11227     return N2;
11228   // fold select_cc false, x, y -> y
11229   if (SCCC && SCCC->isNullValue())
11230     return N3;
11231
11232   // Check to see if we can simplify the select into an fabs node
11233   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11234     // Allow either -0.0 or 0.0
11235     if (CFP->getValueAPF().isZero()) {
11236       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11237       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11238           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11239           N2 == N3.getOperand(0))
11240         return DAG.getNode(ISD::FABS, DL, VT, N0);
11241
11242       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11243       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11244           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11245           N2.getOperand(0) == N3)
11246         return DAG.getNode(ISD::FABS, DL, VT, N3);
11247     }
11248   }
11249
11250   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11251   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11252   // in it.  This is a win when the constant is not otherwise available because
11253   // it replaces two constant pool loads with one.  We only do this if the FP
11254   // type is known to be legal, because if it isn't, then we are before legalize
11255   // types an we want the other legalization to happen first (e.g. to avoid
11256   // messing with soft float) and if the ConstantFP is not legal, because if
11257   // it is legal, we may not need to store the FP constant in a constant pool.
11258   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11259     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11260       if (TLI.isTypeLegal(N2.getValueType()) &&
11261           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11262                TargetLowering::Legal &&
11263            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11264            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11265           // If both constants have multiple uses, then we won't need to do an
11266           // extra load, they are likely around in registers for other users.
11267           (TV->hasOneUse() || FV->hasOneUse())) {
11268         Constant *Elts[] = {
11269           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11270           const_cast<ConstantFP*>(TV->getConstantFPValue())
11271         };
11272         Type *FPTy = Elts[0]->getType();
11273         const DataLayout &TD = *TLI.getDataLayout();
11274
11275         // Create a ConstantArray of the two constants.
11276         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11277         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11278                                             TD.getPrefTypeAlignment(FPTy));
11279         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11280
11281         // Get the offsets to the 0 and 1 element of the array so that we can
11282         // select between them.
11283         SDValue Zero = DAG.getIntPtrConstant(0);
11284         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11285         SDValue One = DAG.getIntPtrConstant(EltSize);
11286
11287         SDValue Cond = DAG.getSetCC(DL,
11288                                     getSetCCResultType(N0.getValueType()),
11289                                     N0, N1, CC);
11290         AddToWorklist(Cond.getNode());
11291         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11292                                           Cond, One, Zero);
11293         AddToWorklist(CstOffset.getNode());
11294         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11295                             CstOffset);
11296         AddToWorklist(CPIdx.getNode());
11297         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11298                            MachinePointerInfo::getConstantPool(), false,
11299                            false, false, Alignment);
11300
11301       }
11302     }
11303
11304   // Check to see if we can perform the "gzip trick", transforming
11305   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11306   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11307       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11308        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11309     EVT XType = N0.getValueType();
11310     EVT AType = N2.getValueType();
11311     if (XType.bitsGE(AType)) {
11312       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11313       // single-bit constant.
11314       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11315         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11316         ShCtV = XType.getSizeInBits()-ShCtV-1;
11317         SDValue ShCt = DAG.getConstant(ShCtV,
11318                                        getShiftAmountTy(N0.getValueType()));
11319         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11320                                     XType, N0, ShCt);
11321         AddToWorklist(Shift.getNode());
11322
11323         if (XType.bitsGT(AType)) {
11324           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11325           AddToWorklist(Shift.getNode());
11326         }
11327
11328         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11329       }
11330
11331       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11332                                   XType, N0,
11333                                   DAG.getConstant(XType.getSizeInBits()-1,
11334                                          getShiftAmountTy(N0.getValueType())));
11335       AddToWorklist(Shift.getNode());
11336
11337       if (XType.bitsGT(AType)) {
11338         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11339         AddToWorklist(Shift.getNode());
11340       }
11341
11342       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11343     }
11344   }
11345
11346   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11347   // where y is has a single bit set.
11348   // A plaintext description would be, we can turn the SELECT_CC into an AND
11349   // when the condition can be materialized as an all-ones register.  Any
11350   // single bit-test can be materialized as an all-ones register with
11351   // shift-left and shift-right-arith.
11352   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11353       N0->getValueType(0) == VT &&
11354       N1C && N1C->isNullValue() &&
11355       N2C && N2C->isNullValue()) {
11356     SDValue AndLHS = N0->getOperand(0);
11357     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11358     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11359       // Shift the tested bit over the sign bit.
11360       APInt AndMask = ConstAndRHS->getAPIntValue();
11361       SDValue ShlAmt =
11362         DAG.getConstant(AndMask.countLeadingZeros(),
11363                         getShiftAmountTy(AndLHS.getValueType()));
11364       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11365
11366       // Now arithmetic right shift it all the way over, so the result is either
11367       // all-ones, or zero.
11368       SDValue ShrAmt =
11369         DAG.getConstant(AndMask.getBitWidth()-1,
11370                         getShiftAmountTy(Shl.getValueType()));
11371       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11372
11373       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11374     }
11375   }
11376
11377   // fold select C, 16, 0 -> shl C, 4
11378   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11379       TLI.getBooleanContents(N0.getValueType()) ==
11380           TargetLowering::ZeroOrOneBooleanContent) {
11381
11382     // If the caller doesn't want us to simplify this into a zext of a compare,
11383     // don't do it.
11384     if (NotExtCompare && N2C->getAPIntValue() == 1)
11385       return SDValue();
11386
11387     // Get a SetCC of the condition
11388     // NOTE: Don't create a SETCC if it's not legal on this target.
11389     if (!LegalOperations ||
11390         TLI.isOperationLegal(ISD::SETCC,
11391           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11392       SDValue Temp, SCC;
11393       // cast from setcc result type to select result type
11394       if (LegalTypes) {
11395         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11396                             N0, N1, CC);
11397         if (N2.getValueType().bitsLT(SCC.getValueType()))
11398           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11399                                         N2.getValueType());
11400         else
11401           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11402                              N2.getValueType(), SCC);
11403       } else {
11404         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11405         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11406                            N2.getValueType(), SCC);
11407       }
11408
11409       AddToWorklist(SCC.getNode());
11410       AddToWorklist(Temp.getNode());
11411
11412       if (N2C->getAPIntValue() == 1)
11413         return Temp;
11414
11415       // shl setcc result by log2 n2c
11416       return DAG.getNode(
11417           ISD::SHL, DL, N2.getValueType(), Temp,
11418           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11419                           getShiftAmountTy(Temp.getValueType())));
11420     }
11421   }
11422
11423   // Check to see if this is the equivalent of setcc
11424   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11425   // otherwise, go ahead with the folds.
11426   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11427     EVT XType = N0.getValueType();
11428     if (!LegalOperations ||
11429         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11430       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11431       if (Res.getValueType() != VT)
11432         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11433       return Res;
11434     }
11435
11436     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11437     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11438         (!LegalOperations ||
11439          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11440       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11441       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11442                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11443                                        getShiftAmountTy(Ctlz.getValueType())));
11444     }
11445     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11446     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11447       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11448                                   XType, DAG.getConstant(0, XType), N0);
11449       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11450       return DAG.getNode(ISD::SRL, DL, XType,
11451                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11452                          DAG.getConstant(XType.getSizeInBits()-1,
11453                                          getShiftAmountTy(XType)));
11454     }
11455     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11456     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11457       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11458                                  DAG.getConstant(XType.getSizeInBits()-1,
11459                                          getShiftAmountTy(N0.getValueType())));
11460       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11461     }
11462   }
11463
11464   // Check to see if this is an integer abs.
11465   // select_cc setg[te] X,  0,  X, -X ->
11466   // select_cc setgt    X, -1,  X, -X ->
11467   // select_cc setl[te] X,  0, -X,  X ->
11468   // select_cc setlt    X,  1, -X,  X ->
11469   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11470   if (N1C) {
11471     ConstantSDNode *SubC = nullptr;
11472     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11473          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11474         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11475       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11476     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11477               (N1C->isOne() && CC == ISD::SETLT)) &&
11478              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11479       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11480
11481     EVT XType = N0.getValueType();
11482     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11483       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11484                                   N0,
11485                                   DAG.getConstant(XType.getSizeInBits()-1,
11486                                          getShiftAmountTy(N0.getValueType())));
11487       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11488                                 XType, N0, Shift);
11489       AddToWorklist(Shift.getNode());
11490       AddToWorklist(Add.getNode());
11491       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11492     }
11493   }
11494
11495   return SDValue();
11496 }
11497
11498 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11499 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11500                                    SDValue N1, ISD::CondCode Cond,
11501                                    SDLoc DL, bool foldBooleans) {
11502   TargetLowering::DAGCombinerInfo
11503     DagCombineInfo(DAG, Level, false, this);
11504   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11505 }
11506
11507 /// BuildSDIV - Given an ISD::SDIV node expressing a divide by constant, return
11508 /// a DAG expression to select that will generate the same value by multiplying
11509 /// by a magic number.  See:
11510 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11511 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11512   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11513   if (!C)
11514     return SDValue();
11515
11516   // Avoid division by zero.
11517   if (!C->getAPIntValue())
11518     return SDValue();
11519
11520   std::vector<SDNode*> Built;
11521   SDValue S =
11522       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11523
11524   for (SDNode *N : Built)
11525     AddToWorklist(N);
11526   return S;
11527 }
11528
11529 /// BuildSDIVPow2 - Given an ISD::SDIV node expressing a divide by constant
11530 /// power of 2, return a DAG expression to select that will generate the same
11531 /// value by right shifting.
11532 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11533   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11534   if (!C)
11535     return SDValue();
11536
11537   // Avoid division by zero.
11538   if (!C->getAPIntValue())
11539     return SDValue();
11540
11541   std::vector<SDNode *> Built;
11542   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11543
11544   for (SDNode *N : Built)
11545     AddToWorklist(N);
11546   return S;
11547 }
11548
11549 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11550 /// return a DAG expression to select that will generate the same value by
11551 /// multiplying by a magic number.  See:
11552 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11553 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11554   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11555   if (!C)
11556     return SDValue();
11557
11558   // Avoid division by zero.
11559   if (!C->getAPIntValue())
11560     return SDValue();
11561
11562   std::vector<SDNode*> Built;
11563   SDValue S =
11564       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11565
11566   for (SDNode *N : Built)
11567     AddToWorklist(N);
11568   return S;
11569 }
11570
11571 /// FindBaseOffset - Return true if base is a frame index, which is known not
11572 // to alias with anything but itself.  Provides base object and offset as
11573 // results.
11574 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11575                            const GlobalValue *&GV, const void *&CV) {
11576   // Assume it is a primitive operation.
11577   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11578
11579   // If it's an adding a simple constant then integrate the offset.
11580   if (Base.getOpcode() == ISD::ADD) {
11581     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11582       Base = Base.getOperand(0);
11583       Offset += C->getZExtValue();
11584     }
11585   }
11586
11587   // Return the underlying GlobalValue, and update the Offset.  Return false
11588   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11589   // by multiple nodes with different offsets.
11590   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11591     GV = G->getGlobal();
11592     Offset += G->getOffset();
11593     return false;
11594   }
11595
11596   // Return the underlying Constant value, and update the Offset.  Return false
11597   // for ConstantSDNodes since the same constant pool entry may be represented
11598   // by multiple nodes with different offsets.
11599   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11600     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11601                                          : (const void *)C->getConstVal();
11602     Offset += C->getOffset();
11603     return false;
11604   }
11605   // If it's any of the following then it can't alias with anything but itself.
11606   return isa<FrameIndexSDNode>(Base);
11607 }
11608
11609 /// isAlias - Return true if there is any possibility that the two addresses
11610 /// overlap.
11611 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11612   // If they are the same then they must be aliases.
11613   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11614
11615   // If they are both volatile then they cannot be reordered.
11616   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11617
11618   // Gather base node and offset information.
11619   SDValue Base1, Base2;
11620   int64_t Offset1, Offset2;
11621   const GlobalValue *GV1, *GV2;
11622   const void *CV1, *CV2;
11623   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11624                                       Base1, Offset1, GV1, CV1);
11625   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11626                                       Base2, Offset2, GV2, CV2);
11627
11628   // If they have a same base address then check to see if they overlap.
11629   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11630     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11631              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11632
11633   // It is possible for different frame indices to alias each other, mostly
11634   // when tail call optimization reuses return address slots for arguments.
11635   // To catch this case, look up the actual index of frame indices to compute
11636   // the real alias relationship.
11637   if (isFrameIndex1 && isFrameIndex2) {
11638     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11639     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11640     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11641     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11642              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11643   }
11644
11645   // Otherwise, if we know what the bases are, and they aren't identical, then
11646   // we know they cannot alias.
11647   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11648     return false;
11649
11650   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11651   // compared to the size and offset of the access, we may be able to prove they
11652   // do not alias.  This check is conservative for now to catch cases created by
11653   // splitting vector types.
11654   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11655       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11656       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11657        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11658       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11659     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11660     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11661
11662     // There is no overlap between these relatively aligned accesses of similar
11663     // size, return no alias.
11664     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11665         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11666       return false;
11667   }
11668
11669   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11670     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11671 #ifndef NDEBUG
11672   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11673       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11674     UseAA = false;
11675 #endif
11676   if (UseAA &&
11677       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11678     // Use alias analysis information.
11679     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11680                                  Op1->getSrcValueOffset());
11681     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11682         Op0->getSrcValueOffset() - MinOffset;
11683     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11684         Op1->getSrcValueOffset() - MinOffset;
11685     AliasAnalysis::AliasResult AAResult =
11686         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11687                                          Overlap1,
11688                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11689                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11690                                          Overlap2,
11691                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11692     if (AAResult == AliasAnalysis::NoAlias)
11693       return false;
11694   }
11695
11696   // Otherwise we have to assume they alias.
11697   return true;
11698 }
11699
11700 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11701 /// looking for aliasing nodes and adding them to the Aliases vector.
11702 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11703                                    SmallVectorImpl<SDValue> &Aliases) {
11704   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11705   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11706
11707   // Get alias information for node.
11708   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11709
11710   // Starting off.
11711   Chains.push_back(OriginalChain);
11712   unsigned Depth = 0;
11713
11714   // Look at each chain and determine if it is an alias.  If so, add it to the
11715   // aliases list.  If not, then continue up the chain looking for the next
11716   // candidate.
11717   while (!Chains.empty()) {
11718     SDValue Chain = Chains.back();
11719     Chains.pop_back();
11720
11721     // For TokenFactor nodes, look at each operand and only continue up the
11722     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11723     // find more and revert to original chain since the xform is unlikely to be
11724     // profitable.
11725     //
11726     // FIXME: The depth check could be made to return the last non-aliasing
11727     // chain we found before we hit a tokenfactor rather than the original
11728     // chain.
11729     if (Depth > 6 || Aliases.size() == 2) {
11730       Aliases.clear();
11731       Aliases.push_back(OriginalChain);
11732       return;
11733     }
11734
11735     // Don't bother if we've been before.
11736     if (!Visited.insert(Chain.getNode()))
11737       continue;
11738
11739     switch (Chain.getOpcode()) {
11740     case ISD::EntryToken:
11741       // Entry token is ideal chain operand, but handled in FindBetterChain.
11742       break;
11743
11744     case ISD::LOAD:
11745     case ISD::STORE: {
11746       // Get alias information for Chain.
11747       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11748           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11749
11750       // If chain is alias then stop here.
11751       if (!(IsLoad && IsOpLoad) &&
11752           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11753         Aliases.push_back(Chain);
11754       } else {
11755         // Look further up the chain.
11756         Chains.push_back(Chain.getOperand(0));
11757         ++Depth;
11758       }
11759       break;
11760     }
11761
11762     case ISD::TokenFactor:
11763       // We have to check each of the operands of the token factor for "small"
11764       // token factors, so we queue them up.  Adding the operands to the queue
11765       // (stack) in reverse order maintains the original order and increases the
11766       // likelihood that getNode will find a matching token factor (CSE.)
11767       if (Chain.getNumOperands() > 16) {
11768         Aliases.push_back(Chain);
11769         break;
11770       }
11771       for (unsigned n = Chain.getNumOperands(); n;)
11772         Chains.push_back(Chain.getOperand(--n));
11773       ++Depth;
11774       break;
11775
11776     default:
11777       // For all other instructions we will just have to take what we can get.
11778       Aliases.push_back(Chain);
11779       break;
11780     }
11781   }
11782
11783   // We need to be careful here to also search for aliases through the
11784   // value operand of a store, etc. Consider the following situation:
11785   //   Token1 = ...
11786   //   L1 = load Token1, %52
11787   //   S1 = store Token1, L1, %51
11788   //   L2 = load Token1, %52+8
11789   //   S2 = store Token1, L2, %51+8
11790   //   Token2 = Token(S1, S2)
11791   //   L3 = load Token2, %53
11792   //   S3 = store Token2, L3, %52
11793   //   L4 = load Token2, %53+8
11794   //   S4 = store Token2, L4, %52+8
11795   // If we search for aliases of S3 (which loads address %52), and we look
11796   // only through the chain, then we'll miss the trivial dependence on L1
11797   // (which also loads from %52). We then might change all loads and
11798   // stores to use Token1 as their chain operand, which could result in
11799   // copying %53 into %52 before copying %52 into %51 (which should
11800   // happen first).
11801   //
11802   // The problem is, however, that searching for such data dependencies
11803   // can become expensive, and the cost is not directly related to the
11804   // chain depth. Instead, we'll rule out such configurations here by
11805   // insisting that we've visited all chain users (except for users
11806   // of the original chain, which is not necessary). When doing this,
11807   // we need to look through nodes we don't care about (otherwise, things
11808   // like register copies will interfere with trivial cases).
11809
11810   SmallVector<const SDNode *, 16> Worklist;
11811   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11812        IE = Visited.end(); I != IE; ++I)
11813     if (*I != OriginalChain.getNode())
11814       Worklist.push_back(*I);
11815
11816   while (!Worklist.empty()) {
11817     const SDNode *M = Worklist.pop_back_val();
11818
11819     // We have already visited M, and want to make sure we've visited any uses
11820     // of M that we care about. For uses that we've not visisted, and don't
11821     // care about, queue them to the worklist.
11822
11823     for (SDNode::use_iterator UI = M->use_begin(),
11824          UIE = M->use_end(); UI != UIE; ++UI)
11825       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11826         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11827           // We've not visited this use, and we care about it (it could have an
11828           // ordering dependency with the original node).
11829           Aliases.clear();
11830           Aliases.push_back(OriginalChain);
11831           return;
11832         }
11833
11834         // We've not visited this use, but we don't care about it. Mark it as
11835         // visited and enqueue it to the worklist.
11836         Worklist.push_back(*UI);
11837       }
11838   }
11839 }
11840
11841 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11842 /// for a better chain (aliasing node.)
11843 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11844   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11845
11846   // Accumulate all the aliases to this node.
11847   GatherAllAliases(N, OldChain, Aliases);
11848
11849   // If no operands then chain to entry token.
11850   if (Aliases.size() == 0)
11851     return DAG.getEntryNode();
11852
11853   // If a single operand then chain to it.  We don't need to revisit it.
11854   if (Aliases.size() == 1)
11855     return Aliases[0];
11856
11857   // Construct a custom tailored token factor.
11858   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11859 }
11860
11861 // SelectionDAG::Combine - This is the entry point for the file.
11862 //
11863 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11864                            CodeGenOpt::Level OptLevel) {
11865   /// run - This is the main entry point to this class.
11866   ///
11867   DAGCombiner(*this, AA, OptLevel).Run(Level);
11868 }