[X86] Add two combine rules to simplify dag nodes introduced during type legalization...
[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/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
39 #include <algorithm>
40 using namespace llvm;
41
42 #define DEBUG_TYPE "dagcombine"
43
44 STATISTIC(NodesCombined   , "Number of dag nodes combined");
45 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
46 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
47 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
48 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
49 STATISTIC(SlicedLoads, "Number of load sliced");
50
51 namespace {
52   static cl::opt<bool>
53     CombinerAA("combiner-alias-analysis", cl::Hidden,
54                cl::desc("Enable DAG combiner alias-analysis heuristics"));
55
56   static cl::opt<bool>
57     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
58                cl::desc("Enable DAG combiner's use of IR alias analysis"));
59
60   static cl::opt<bool>
61     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
62                cl::desc("Enable DAG combiner's use of TBAA"));
63
64 #ifndef NDEBUG
65   static cl::opt<std::string>
66     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
67                cl::desc("Only use DAG-combiner alias analysis in this"
68                         " function"));
69 #endif
70
71   /// Hidden option to stress test load slicing, i.e., when this option
72   /// is enabled, load slicing bypasses most of its profitability guards.
73   static cl::opt<bool>
74   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
75                     cl::desc("Bypass the profitability model of load "
76                              "slicing"),
77                     cl::init(false));
78
79 //------------------------------ DAGCombiner ---------------------------------//
80
81   class DAGCombiner {
82     SelectionDAG &DAG;
83     const TargetLowering &TLI;
84     CombineLevel Level;
85     CodeGenOpt::Level OptLevel;
86     bool LegalOperations;
87     bool LegalTypes;
88     bool ForCodeSize;
89
90     // Worklist of all of the nodes that need to be simplified.
91     //
92     // This has the semantics that when adding to the worklist,
93     // the item added must be next to be processed. It should
94     // also only appear once. The naive approach to this takes
95     // linear time.
96     //
97     // To reduce the insert/remove time to logarithmic, we use
98     // a set and a vector to maintain our worklist.
99     //
100     // The set contains the items on the worklist, but does not
101     // maintain the order they should be visited.
102     //
103     // The vector maintains the order nodes should be visited, but may
104     // contain duplicate or removed nodes. When choosing a node to
105     // visit, we pop off the order stack until we find an item that is
106     // also in the contents set. All operations are O(log N).
107     SmallPtrSet<SDNode*, 64> WorkListContents;
108     SmallVector<SDNode*, 64> WorkListOrder;
109
110     // AA - Used for DAG load/store alias analysis.
111     AliasAnalysis &AA;
112
113     /// AddUsersToWorkList - When an instruction is simplified, add all users of
114     /// the instruction to the work lists because they might get more simplified
115     /// now.
116     ///
117     void AddUsersToWorkList(SDNode *N) {
118       for (SDNode *Node : N->uses())
119         AddToWorkList(Node);
120     }
121
122     /// visit - call the node-specific routine that knows how to fold each
123     /// particular type of node.
124     SDValue visit(SDNode *N);
125
126   public:
127     /// AddToWorkList - Add to the work list making sure its instance is at the
128     /// back (next to be processed.)
129     void AddToWorkList(SDNode *N) {
130       WorkListContents.insert(N);
131       WorkListOrder.push_back(N);
132     }
133
134     /// removeFromWorkList - remove all instances of N from the worklist.
135     ///
136     void removeFromWorkList(SDNode *N) {
137       WorkListContents.erase(N);
138     }
139
140     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
141                       bool AddTo = true);
142
143     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
144       return CombineTo(N, &Res, 1, AddTo);
145     }
146
147     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
148                       bool AddTo = true) {
149       SDValue To[] = { Res0, Res1 };
150       return CombineTo(N, To, 2, AddTo);
151     }
152
153     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
154
155   private:
156
157     /// SimplifyDemandedBits - Check the specified integer node value to see if
158     /// it can be simplified or if things it uses can be simplified by bit
159     /// propagation.  If so, return true.
160     bool SimplifyDemandedBits(SDValue Op) {
161       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
162       APInt Demanded = APInt::getAllOnesValue(BitWidth);
163       return SimplifyDemandedBits(Op, Demanded);
164     }
165
166     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
167
168     bool CombineToPreIndexedLoadStore(SDNode *N);
169     bool CombineToPostIndexedLoadStore(SDNode *N);
170     bool SliceUpLoad(SDNode *N);
171
172     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
173     ///   load.
174     ///
175     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
176     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
177     /// \param EltNo index of the vector element to load.
178     /// \param OriginalLoad load that EVE came from to be replaced.
179     /// \returns EVE on success SDValue() on failure.
180     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
181         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
182     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
183     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
184     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
185     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
186     SDValue PromoteIntBinOp(SDValue Op);
187     SDValue PromoteIntShiftOp(SDValue Op);
188     SDValue PromoteExtend(SDValue Op);
189     bool PromoteLoad(SDValue Op);
190
191     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
192                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
193                          ISD::NodeType ExtType);
194
195     /// combine - call the node-specific routine that knows how to fold each
196     /// particular type of node. If that doesn't do anything, try the
197     /// target-specific DAG combines.
198     SDValue combine(SDNode *N);
199
200     // Visitation implementation - Implement dag node combining for different
201     // node types.  The semantics are as follows:
202     // Return Value:
203     //   SDValue.getNode() == 0 - No change was made
204     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
205     //   otherwise              - N should be replaced by the returned Operand.
206     //
207     SDValue visitTokenFactor(SDNode *N);
208     SDValue visitMERGE_VALUES(SDNode *N);
209     SDValue visitADD(SDNode *N);
210     SDValue visitSUB(SDNode *N);
211     SDValue visitADDC(SDNode *N);
212     SDValue visitSUBC(SDNode *N);
213     SDValue visitADDE(SDNode *N);
214     SDValue visitSUBE(SDNode *N);
215     SDValue visitMUL(SDNode *N);
216     SDValue visitSDIV(SDNode *N);
217     SDValue visitUDIV(SDNode *N);
218     SDValue visitSREM(SDNode *N);
219     SDValue visitUREM(SDNode *N);
220     SDValue visitMULHU(SDNode *N);
221     SDValue visitMULHS(SDNode *N);
222     SDValue visitSMUL_LOHI(SDNode *N);
223     SDValue visitUMUL_LOHI(SDNode *N);
224     SDValue visitSMULO(SDNode *N);
225     SDValue visitUMULO(SDNode *N);
226     SDValue visitSDIVREM(SDNode *N);
227     SDValue visitUDIVREM(SDNode *N);
228     SDValue visitAND(SDNode *N);
229     SDValue visitOR(SDNode *N);
230     SDValue visitXOR(SDNode *N);
231     SDValue SimplifyVBinOp(SDNode *N);
232     SDValue SimplifyVUnaryOp(SDNode *N);
233     SDValue visitSHL(SDNode *N);
234     SDValue visitSRA(SDNode *N);
235     SDValue visitSRL(SDNode *N);
236     SDValue visitRotate(SDNode *N);
237     SDValue visitCTLZ(SDNode *N);
238     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
239     SDValue visitCTTZ(SDNode *N);
240     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
241     SDValue visitCTPOP(SDNode *N);
242     SDValue visitSELECT(SDNode *N);
243     SDValue visitVSELECT(SDNode *N);
244     SDValue visitSELECT_CC(SDNode *N);
245     SDValue visitSETCC(SDNode *N);
246     SDValue visitSIGN_EXTEND(SDNode *N);
247     SDValue visitZERO_EXTEND(SDNode *N);
248     SDValue visitANY_EXTEND(SDNode *N);
249     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
250     SDValue visitTRUNCATE(SDNode *N);
251     SDValue visitBITCAST(SDNode *N);
252     SDValue visitBUILD_PAIR(SDNode *N);
253     SDValue visitFADD(SDNode *N);
254     SDValue visitFSUB(SDNode *N);
255     SDValue visitFMUL(SDNode *N);
256     SDValue visitFMA(SDNode *N);
257     SDValue visitFDIV(SDNode *N);
258     SDValue visitFREM(SDNode *N);
259     SDValue visitFCOPYSIGN(SDNode *N);
260     SDValue visitSINT_TO_FP(SDNode *N);
261     SDValue visitUINT_TO_FP(SDNode *N);
262     SDValue visitFP_TO_SINT(SDNode *N);
263     SDValue visitFP_TO_UINT(SDNode *N);
264     SDValue visitFP_ROUND(SDNode *N);
265     SDValue visitFP_ROUND_INREG(SDNode *N);
266     SDValue visitFP_EXTEND(SDNode *N);
267     SDValue visitFNEG(SDNode *N);
268     SDValue visitFABS(SDNode *N);
269     SDValue visitFCEIL(SDNode *N);
270     SDValue visitFTRUNC(SDNode *N);
271     SDValue visitFFLOOR(SDNode *N);
272     SDValue visitBRCOND(SDNode *N);
273     SDValue visitBR_CC(SDNode *N);
274     SDValue visitLOAD(SDNode *N);
275     SDValue visitSTORE(SDNode *N);
276     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
277     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
278     SDValue visitBUILD_VECTOR(SDNode *N);
279     SDValue visitCONCAT_VECTORS(SDNode *N);
280     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
281     SDValue visitVECTOR_SHUFFLE(SDNode *N);
282     SDValue visitINSERT_SUBVECTOR(SDNode *N);
283
284     SDValue XformToShuffleWithZero(SDNode *N);
285     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
286
287     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
288
289     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
290     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
291     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
292     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
293                              SDValue N3, ISD::CondCode CC,
294                              bool NotExtCompare = false);
295     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
296                           SDLoc DL, bool foldBooleans = true);
297
298     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
299                            SDValue &CC) const;
300     bool isOneUseSetCC(SDValue N) const;
301
302     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
303                                          unsigned HiOp);
304     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
305     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
306     SDValue BuildSDIV(SDNode *N);
307     SDValue BuildUDIV(SDNode *N);
308     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
309                                bool DemandHighBits = true);
310     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
311     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
312                               SDValue InnerPos, SDValue InnerNeg,
313                               unsigned PosOpcode, unsigned NegOpcode,
314                               SDLoc DL);
315     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
316     SDValue ReduceLoadWidth(SDNode *N);
317     SDValue ReduceLoadOpStoreWidth(SDNode *N);
318     SDValue TransformFPLoadStorePair(SDNode *N);
319     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
320     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
321
322     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
323
324     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
325     /// looking for aliasing nodes and adding them to the Aliases vector.
326     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
327                           SmallVectorImpl<SDValue> &Aliases);
328
329     /// isAlias - Return true if there is any possibility that the two addresses
330     /// overlap.
331     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
332
333     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
334     /// looking for a better chain (aliasing node.)
335     SDValue FindBetterChain(SDNode *N, SDValue Chain);
336
337     /// Merge consecutive store operations into a wide store.
338     /// This optimization uses wide integers or vectors when possible.
339     /// \return True if some memory operations were changed.
340     bool MergeConsecutiveStores(StoreSDNode *N);
341
342     /// \brief Try to transform a truncation where C is a constant:
343     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
344     ///
345     /// \p N needs to be a truncation and its first operand an AND. Other
346     /// requirements are checked by the function (e.g. that trunc is
347     /// single-use) and if missed an empty SDValue is returned.
348     SDValue distributeTruncateThroughAnd(SDNode *N);
349
350   public:
351     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
352         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
353           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
354       AttributeSet FnAttrs =
355           DAG.getMachineFunction().getFunction()->getAttributes();
356       ForCodeSize =
357           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
358                                Attribute::OptimizeForSize) ||
359           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
360     }
361
362     /// Run - runs the dag combiner on all nodes in the work list
363     void Run(CombineLevel AtLevel);
364
365     SelectionDAG &getDAG() const { return DAG; }
366
367     /// getShiftAmountTy - Returns a type large enough to hold any valid
368     /// shift amount - before type legalization these can be huge.
369     EVT getShiftAmountTy(EVT LHSTy) {
370       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
371       if (LHSTy.isVector())
372         return LHSTy;
373       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
374                         : TLI.getPointerTy();
375     }
376
377     /// isTypeLegal - This method returns true if we are running before type
378     /// legalization or if the specified VT is legal.
379     bool isTypeLegal(const EVT &VT) {
380       if (!LegalTypes) return true;
381       return TLI.isTypeLegal(VT);
382     }
383
384     /// getSetCCResultType - Convenience wrapper around
385     /// TargetLowering::getSetCCResultType
386     EVT getSetCCResultType(EVT VT) const {
387       return TLI.getSetCCResultType(*DAG.getContext(), VT);
388     }
389   };
390 }
391
392
393 namespace {
394 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
395 /// nodes from the worklist.
396 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
397   DAGCombiner &DC;
398 public:
399   explicit WorkListRemover(DAGCombiner &dc)
400     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
401
402   void NodeDeleted(SDNode *N, SDNode *E) override {
403     DC.removeFromWorkList(N);
404   }
405 };
406 }
407
408 //===----------------------------------------------------------------------===//
409 //  TargetLowering::DAGCombinerInfo implementation
410 //===----------------------------------------------------------------------===//
411
412 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
413   ((DAGCombiner*)DC)->AddToWorkList(N);
414 }
415
416 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
417   ((DAGCombiner*)DC)->removeFromWorkList(N);
418 }
419
420 SDValue TargetLowering::DAGCombinerInfo::
421 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
422   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
423 }
424
425 SDValue TargetLowering::DAGCombinerInfo::
426 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
427   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
428 }
429
430
431 SDValue TargetLowering::DAGCombinerInfo::
432 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
433   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
434 }
435
436 void TargetLowering::DAGCombinerInfo::
437 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
438   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
439 }
440
441 //===----------------------------------------------------------------------===//
442 // Helper Functions
443 //===----------------------------------------------------------------------===//
444
445 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
446 /// specified expression for the same cost as the expression itself, or 2 if we
447 /// can compute the negated form more cheaply than the expression itself.
448 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
449                                const TargetLowering &TLI,
450                                const TargetOptions *Options,
451                                unsigned Depth = 0) {
452   // fneg is removable even if it has multiple uses.
453   if (Op.getOpcode() == ISD::FNEG) return 2;
454
455   // Don't allow anything with multiple uses.
456   if (!Op.hasOneUse()) return 0;
457
458   // Don't recurse exponentially.
459   if (Depth > 6) return 0;
460
461   switch (Op.getOpcode()) {
462   default: return false;
463   case ISD::ConstantFP:
464     // Don't invert constant FP values after legalize.  The negated constant
465     // isn't necessarily legal.
466     return LegalOperations ? 0 : 1;
467   case ISD::FADD:
468     // FIXME: determine better conditions for this xform.
469     if (!Options->UnsafeFPMath) return 0;
470
471     // After operation legalization, it might not be legal to create new FSUBs.
472     if (LegalOperations &&
473         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
474       return 0;
475
476     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
477     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
478                                     Options, Depth + 1))
479       return V;
480     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
481     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
482                               Depth + 1);
483   case ISD::FSUB:
484     // We can't turn -(A-B) into B-A when we honor signed zeros.
485     if (!Options->UnsafeFPMath) return 0;
486
487     // fold (fneg (fsub A, B)) -> (fsub B, A)
488     return 1;
489
490   case ISD::FMUL:
491   case ISD::FDIV:
492     if (Options->HonorSignDependentRoundingFPMath()) return 0;
493
494     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
495     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
496                                     Options, Depth + 1))
497       return V;
498
499     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
500                               Depth + 1);
501
502   case ISD::FP_EXTEND:
503   case ISD::FP_ROUND:
504   case ISD::FSIN:
505     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
506                               Depth + 1);
507   }
508 }
509
510 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
511 /// returns the newly negated expression.
512 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
513                                     bool LegalOperations, unsigned Depth = 0) {
514   // fneg is removable even if it has multiple uses.
515   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
516
517   // Don't allow anything with multiple uses.
518   assert(Op.hasOneUse() && "Unknown reuse!");
519
520   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
521   switch (Op.getOpcode()) {
522   default: llvm_unreachable("Unknown code");
523   case ISD::ConstantFP: {
524     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
525     V.changeSign();
526     return DAG.getConstantFP(V, Op.getValueType());
527   }
528   case ISD::FADD:
529     // FIXME: determine better conditions for this xform.
530     assert(DAG.getTarget().Options.UnsafeFPMath);
531
532     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
533     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
534                            DAG.getTargetLoweringInfo(),
535                            &DAG.getTarget().Options, Depth+1))
536       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
537                          GetNegatedExpression(Op.getOperand(0), DAG,
538                                               LegalOperations, Depth+1),
539                          Op.getOperand(1));
540     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
541     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
542                        GetNegatedExpression(Op.getOperand(1), DAG,
543                                             LegalOperations, Depth+1),
544                        Op.getOperand(0));
545   case ISD::FSUB:
546     // We can't turn -(A-B) into B-A when we honor signed zeros.
547     assert(DAG.getTarget().Options.UnsafeFPMath);
548
549     // fold (fneg (fsub 0, B)) -> B
550     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
551       if (N0CFP->getValueAPF().isZero())
552         return Op.getOperand(1);
553
554     // fold (fneg (fsub A, B)) -> (fsub B, A)
555     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
556                        Op.getOperand(1), Op.getOperand(0));
557
558   case ISD::FMUL:
559   case ISD::FDIV:
560     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
561
562     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
563     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
564                            DAG.getTargetLoweringInfo(),
565                            &DAG.getTarget().Options, Depth+1))
566       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
567                          GetNegatedExpression(Op.getOperand(0), DAG,
568                                               LegalOperations, Depth+1),
569                          Op.getOperand(1));
570
571     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
572     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
573                        Op.getOperand(0),
574                        GetNegatedExpression(Op.getOperand(1), DAG,
575                                             LegalOperations, Depth+1));
576
577   case ISD::FP_EXTEND:
578   case ISD::FSIN:
579     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
580                        GetNegatedExpression(Op.getOperand(0), DAG,
581                                             LegalOperations, Depth+1));
582   case ISD::FP_ROUND:
583       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
584                          GetNegatedExpression(Op.getOperand(0), DAG,
585                                               LegalOperations, Depth+1),
586                          Op.getOperand(1));
587   }
588 }
589
590 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
591 // that selects between the target values used for true and false, making it
592 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
593 // the appropriate nodes based on the type of node we are checking. This
594 // simplifies life a bit for the callers.
595 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
596                                     SDValue &CC) const {
597   if (N.getOpcode() == ISD::SETCC) {
598     LHS = N.getOperand(0);
599     RHS = N.getOperand(1);
600     CC  = N.getOperand(2);
601     return true;
602   }
603
604   if (N.getOpcode() != ISD::SELECT_CC ||
605       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
606       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
607     return false;
608
609   LHS = N.getOperand(0);
610   RHS = N.getOperand(1);
611   CC  = N.getOperand(4);
612   return true;
613 }
614
615 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
616 // one use.  If this is true, it allows the users to invert the operation for
617 // free when it is profitable to do so.
618 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
619   SDValue N0, N1, N2;
620   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
621     return true;
622   return false;
623 }
624
625 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
626 /// elements are all the same constant or undefined.
627 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
628   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
629   if (!C)
630     return false;
631
632   APInt SplatUndef;
633   unsigned SplatBitSize;
634   bool HasAnyUndefs;
635   EVT EltVT = N->getValueType(0).getVectorElementType();
636   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
637                              HasAnyUndefs) &&
638           EltVT.getSizeInBits() >= SplatBitSize);
639 }
640
641 // \brief Returns the SDNode if it is a constant BuildVector or constant.
642 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
643   if (isa<ConstantSDNode>(N))
644     return N.getNode();
645   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
646   if(BV && BV->isConstant())
647     return BV;
648   return nullptr;
649 }
650
651 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
652 // int.
653 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
654   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
655     return CN;
656
657   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
658     ConstantSDNode *CN = BV->getConstantSplatValue();
659
660     // BuildVectors can truncate their operands. Ignore that case here.
661     if (CN && CN->getValueType(0) == N.getValueType().getScalarType())
662       return CN;
663   }
664
665   return nullptr;
666 }
667
668 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
669                                     SDValue N0, SDValue N1) {
670   EVT VT = N0.getValueType();
671   if (N0.getOpcode() == Opc) {
672     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
673       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
674         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
675         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
676         if (!OpNode.getNode())
677           return SDValue();
678         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
679       }
680       if (N0.hasOneUse()) {
681         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
682         // use
683         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
684         if (!OpNode.getNode())
685           return SDValue();
686         AddToWorkList(OpNode.getNode());
687         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
688       }
689     }
690   }
691
692   if (N1.getOpcode() == Opc) {
693     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
694       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
695         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
696         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
697         if (!OpNode.getNode())
698           return SDValue();
699         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
700       }
701       if (N1.hasOneUse()) {
702         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
703         // use
704         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
705         if (!OpNode.getNode())
706           return SDValue();
707         AddToWorkList(OpNode.getNode());
708         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
709       }
710     }
711   }
712
713   return SDValue();
714 }
715
716 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
717                                bool AddTo) {
718   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
719   ++NodesCombined;
720   DEBUG(dbgs() << "\nReplacing.1 ";
721         N->dump(&DAG);
722         dbgs() << "\nWith: ";
723         To[0].getNode()->dump(&DAG);
724         dbgs() << " and " << NumTo-1 << " other values\n";
725         for (unsigned i = 0, e = NumTo; i != e; ++i)
726           assert((!To[i].getNode() ||
727                   N->getValueType(i) == To[i].getValueType()) &&
728                  "Cannot combine value to value of different type!"));
729   WorkListRemover DeadNodes(*this);
730   DAG.ReplaceAllUsesWith(N, To);
731   if (AddTo) {
732     // Push the new nodes and any users onto the worklist
733     for (unsigned i = 0, e = NumTo; i != e; ++i) {
734       if (To[i].getNode()) {
735         AddToWorkList(To[i].getNode());
736         AddUsersToWorkList(To[i].getNode());
737       }
738     }
739   }
740
741   // Finally, if the node is now dead, remove it from the graph.  The node
742   // may not be dead if the replacement process recursively simplified to
743   // something else needing this node.
744   if (N->use_empty()) {
745     // Nodes can be reintroduced into the worklist.  Make sure we do not
746     // process a node that has been replaced.
747     removeFromWorkList(N);
748
749     // Finally, since the node is now dead, remove it from the graph.
750     DAG.DeleteNode(N);
751   }
752   return SDValue(N, 0);
753 }
754
755 void DAGCombiner::
756 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
757   // Replace all uses.  If any nodes become isomorphic to other nodes and
758   // are deleted, make sure to remove them from our worklist.
759   WorkListRemover DeadNodes(*this);
760   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
761
762   // Push the new node and any (possibly new) users onto the worklist.
763   AddToWorkList(TLO.New.getNode());
764   AddUsersToWorkList(TLO.New.getNode());
765
766   // Finally, if the node is now dead, remove it from the graph.  The node
767   // may not be dead if the replacement process recursively simplified to
768   // something else needing this node.
769   if (TLO.Old.getNode()->use_empty()) {
770     removeFromWorkList(TLO.Old.getNode());
771
772     // If the operands of this node are only used by the node, they will now
773     // be dead.  Make sure to visit them first to delete dead nodes early.
774     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
775       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
776         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
777
778     DAG.DeleteNode(TLO.Old.getNode());
779   }
780 }
781
782 /// SimplifyDemandedBits - Check the specified integer node value to see if
783 /// it can be simplified or if things it uses can be simplified by bit
784 /// propagation.  If so, return true.
785 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
786   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
787   APInt KnownZero, KnownOne;
788   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
789     return false;
790
791   // Revisit the node.
792   AddToWorkList(Op.getNode());
793
794   // Replace the old value with the new one.
795   ++NodesCombined;
796   DEBUG(dbgs() << "\nReplacing.2 ";
797         TLO.Old.getNode()->dump(&DAG);
798         dbgs() << "\nWith: ";
799         TLO.New.getNode()->dump(&DAG);
800         dbgs() << '\n');
801
802   CommitTargetLoweringOpt(TLO);
803   return true;
804 }
805
806 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
807   SDLoc dl(Load);
808   EVT VT = Load->getValueType(0);
809   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
810
811   DEBUG(dbgs() << "\nReplacing.9 ";
812         Load->dump(&DAG);
813         dbgs() << "\nWith: ";
814         Trunc.getNode()->dump(&DAG);
815         dbgs() << '\n');
816   WorkListRemover DeadNodes(*this);
817   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
818   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
819   removeFromWorkList(Load);
820   DAG.DeleteNode(Load);
821   AddToWorkList(Trunc.getNode());
822 }
823
824 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
825   Replace = false;
826   SDLoc dl(Op);
827   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
828     EVT MemVT = LD->getMemoryVT();
829     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
830       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
831                                                   : ISD::EXTLOAD)
832       : LD->getExtensionType();
833     Replace = true;
834     return DAG.getExtLoad(ExtType, dl, PVT,
835                           LD->getChain(), LD->getBasePtr(),
836                           MemVT, LD->getMemOperand());
837   }
838
839   unsigned Opc = Op.getOpcode();
840   switch (Opc) {
841   default: break;
842   case ISD::AssertSext:
843     return DAG.getNode(ISD::AssertSext, dl, PVT,
844                        SExtPromoteOperand(Op.getOperand(0), PVT),
845                        Op.getOperand(1));
846   case ISD::AssertZext:
847     return DAG.getNode(ISD::AssertZext, dl, PVT,
848                        ZExtPromoteOperand(Op.getOperand(0), PVT),
849                        Op.getOperand(1));
850   case ISD::Constant: {
851     unsigned ExtOpc =
852       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
853     return DAG.getNode(ExtOpc, dl, PVT, Op);
854   }
855   }
856
857   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
858     return SDValue();
859   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
860 }
861
862 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
863   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
864     return SDValue();
865   EVT OldVT = Op.getValueType();
866   SDLoc dl(Op);
867   bool Replace = false;
868   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
869   if (!NewOp.getNode())
870     return SDValue();
871   AddToWorkList(NewOp.getNode());
872
873   if (Replace)
874     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
875   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
876                      DAG.getValueType(OldVT));
877 }
878
879 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
880   EVT OldVT = Op.getValueType();
881   SDLoc dl(Op);
882   bool Replace = false;
883   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
884   if (!NewOp.getNode())
885     return SDValue();
886   AddToWorkList(NewOp.getNode());
887
888   if (Replace)
889     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
890   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
891 }
892
893 /// PromoteIntBinOp - Promote the specified integer binary operation if the
894 /// target indicates it is beneficial. e.g. On x86, it's usually better to
895 /// promote i16 operations to i32 since i16 instructions are longer.
896 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
897   if (!LegalOperations)
898     return SDValue();
899
900   EVT VT = Op.getValueType();
901   if (VT.isVector() || !VT.isInteger())
902     return SDValue();
903
904   // If operation type is 'undesirable', e.g. i16 on x86, consider
905   // promoting it.
906   unsigned Opc = Op.getOpcode();
907   if (TLI.isTypeDesirableForOp(Opc, VT))
908     return SDValue();
909
910   EVT PVT = VT;
911   // Consult target whether it is a good idea to promote this operation and
912   // what's the right type to promote it to.
913   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
914     assert(PVT != VT && "Don't know what type to promote to!");
915
916     bool Replace0 = false;
917     SDValue N0 = Op.getOperand(0);
918     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
919     if (!NN0.getNode())
920       return SDValue();
921
922     bool Replace1 = false;
923     SDValue N1 = Op.getOperand(1);
924     SDValue NN1;
925     if (N0 == N1)
926       NN1 = NN0;
927     else {
928       NN1 = PromoteOperand(N1, PVT, Replace1);
929       if (!NN1.getNode())
930         return SDValue();
931     }
932
933     AddToWorkList(NN0.getNode());
934     if (NN1.getNode())
935       AddToWorkList(NN1.getNode());
936
937     if (Replace0)
938       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
939     if (Replace1)
940       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
941
942     DEBUG(dbgs() << "\nPromoting ";
943           Op.getNode()->dump(&DAG));
944     SDLoc dl(Op);
945     return DAG.getNode(ISD::TRUNCATE, dl, VT,
946                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
947   }
948   return SDValue();
949 }
950
951 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
952 /// target indicates it is beneficial. e.g. On x86, it's usually better to
953 /// promote i16 operations to i32 since i16 instructions are longer.
954 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
955   if (!LegalOperations)
956     return SDValue();
957
958   EVT VT = Op.getValueType();
959   if (VT.isVector() || !VT.isInteger())
960     return SDValue();
961
962   // If operation type is 'undesirable', e.g. i16 on x86, consider
963   // promoting it.
964   unsigned Opc = Op.getOpcode();
965   if (TLI.isTypeDesirableForOp(Opc, VT))
966     return SDValue();
967
968   EVT PVT = VT;
969   // Consult target whether it is a good idea to promote this operation and
970   // what's the right type to promote it to.
971   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
972     assert(PVT != VT && "Don't know what type to promote to!");
973
974     bool Replace = false;
975     SDValue N0 = Op.getOperand(0);
976     if (Opc == ISD::SRA)
977       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
978     else if (Opc == ISD::SRL)
979       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
980     else
981       N0 = PromoteOperand(N0, PVT, Replace);
982     if (!N0.getNode())
983       return SDValue();
984
985     AddToWorkList(N0.getNode());
986     if (Replace)
987       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
988
989     DEBUG(dbgs() << "\nPromoting ";
990           Op.getNode()->dump(&DAG));
991     SDLoc dl(Op);
992     return DAG.getNode(ISD::TRUNCATE, dl, VT,
993                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
994   }
995   return SDValue();
996 }
997
998 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
999   if (!LegalOperations)
1000     return SDValue();
1001
1002   EVT VT = Op.getValueType();
1003   if (VT.isVector() || !VT.isInteger())
1004     return SDValue();
1005
1006   // If operation type is 'undesirable', e.g. i16 on x86, consider
1007   // promoting it.
1008   unsigned Opc = Op.getOpcode();
1009   if (TLI.isTypeDesirableForOp(Opc, VT))
1010     return SDValue();
1011
1012   EVT PVT = VT;
1013   // Consult target whether it is a good idea to promote this operation and
1014   // what's the right type to promote it to.
1015   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1016     assert(PVT != VT && "Don't know what type to promote to!");
1017     // fold (aext (aext x)) -> (aext x)
1018     // fold (aext (zext x)) -> (zext x)
1019     // fold (aext (sext x)) -> (sext x)
1020     DEBUG(dbgs() << "\nPromoting ";
1021           Op.getNode()->dump(&DAG));
1022     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1023   }
1024   return SDValue();
1025 }
1026
1027 bool DAGCombiner::PromoteLoad(SDValue Op) {
1028   if (!LegalOperations)
1029     return false;
1030
1031   EVT VT = Op.getValueType();
1032   if (VT.isVector() || !VT.isInteger())
1033     return false;
1034
1035   // If operation type is 'undesirable', e.g. i16 on x86, consider
1036   // promoting it.
1037   unsigned Opc = Op.getOpcode();
1038   if (TLI.isTypeDesirableForOp(Opc, VT))
1039     return false;
1040
1041   EVT PVT = VT;
1042   // Consult target whether it is a good idea to promote this operation and
1043   // what's the right type to promote it to.
1044   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1045     assert(PVT != VT && "Don't know what type to promote to!");
1046
1047     SDLoc dl(Op);
1048     SDNode *N = Op.getNode();
1049     LoadSDNode *LD = cast<LoadSDNode>(N);
1050     EVT MemVT = LD->getMemoryVT();
1051     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1052       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1053                                                   : ISD::EXTLOAD)
1054       : LD->getExtensionType();
1055     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1056                                    LD->getChain(), LD->getBasePtr(),
1057                                    MemVT, LD->getMemOperand());
1058     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1059
1060     DEBUG(dbgs() << "\nPromoting ";
1061           N->dump(&DAG);
1062           dbgs() << "\nTo: ";
1063           Result.getNode()->dump(&DAG);
1064           dbgs() << '\n');
1065     WorkListRemover DeadNodes(*this);
1066     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1067     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1068     removeFromWorkList(N);
1069     DAG.DeleteNode(N);
1070     AddToWorkList(Result.getNode());
1071     return true;
1072   }
1073   return false;
1074 }
1075
1076
1077 //===----------------------------------------------------------------------===//
1078 //  Main DAG Combiner implementation
1079 //===----------------------------------------------------------------------===//
1080
1081 void DAGCombiner::Run(CombineLevel AtLevel) {
1082   // set the instance variables, so that the various visit routines may use it.
1083   Level = AtLevel;
1084   LegalOperations = Level >= AfterLegalizeVectorOps;
1085   LegalTypes = Level >= AfterLegalizeTypes;
1086
1087   // Add all the dag nodes to the worklist.
1088   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1089        E = DAG.allnodes_end(); I != E; ++I)
1090     AddToWorkList(I);
1091
1092   // Create a dummy node (which is not added to allnodes), that adds a reference
1093   // to the root node, preventing it from being deleted, and tracking any
1094   // changes of the root.
1095   HandleSDNode Dummy(DAG.getRoot());
1096
1097   // The root of the dag may dangle to deleted nodes until the dag combiner is
1098   // done.  Set it to null to avoid confusion.
1099   DAG.setRoot(SDValue());
1100
1101   // while the worklist isn't empty, find a node and
1102   // try and combine it.
1103   while (!WorkListContents.empty()) {
1104     SDNode *N;
1105     // The WorkListOrder holds the SDNodes in order, but it may contain
1106     // duplicates.
1107     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1108     // worklist *should* contain, and check the node we want to visit is should
1109     // actually be visited.
1110     do {
1111       N = WorkListOrder.pop_back_val();
1112     } while (!WorkListContents.erase(N));
1113
1114     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1115     // N is deleted from the DAG, since they too may now be dead or may have a
1116     // reduced number of uses, allowing other xforms.
1117     if (N->use_empty() && N != &Dummy) {
1118       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1119         AddToWorkList(N->getOperand(i).getNode());
1120
1121       DAG.DeleteNode(N);
1122       continue;
1123     }
1124
1125     SDValue RV = combine(N);
1126
1127     if (!RV.getNode())
1128       continue;
1129
1130     ++NodesCombined;
1131
1132     // If we get back the same node we passed in, rather than a new node or
1133     // zero, we know that the node must have defined multiple values and
1134     // CombineTo was used.  Since CombineTo takes care of the worklist
1135     // mechanics for us, we have no work to do in this case.
1136     if (RV.getNode() == N)
1137       continue;
1138
1139     assert(N->getOpcode() != ISD::DELETED_NODE &&
1140            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1141            "Node was deleted but visit returned new node!");
1142
1143     DEBUG(dbgs() << "\nReplacing.3 ";
1144           N->dump(&DAG);
1145           dbgs() << "\nWith: ";
1146           RV.getNode()->dump(&DAG);
1147           dbgs() << '\n');
1148
1149     // Transfer debug value.
1150     DAG.TransferDbgValues(SDValue(N, 0), RV);
1151     WorkListRemover DeadNodes(*this);
1152     if (N->getNumValues() == RV.getNode()->getNumValues())
1153       DAG.ReplaceAllUsesWith(N, RV.getNode());
1154     else {
1155       assert(N->getValueType(0) == RV.getValueType() &&
1156              N->getNumValues() == 1 && "Type mismatch");
1157       SDValue OpV = RV;
1158       DAG.ReplaceAllUsesWith(N, &OpV);
1159     }
1160
1161     // Push the new node and any users onto the worklist
1162     AddToWorkList(RV.getNode());
1163     AddUsersToWorkList(RV.getNode());
1164
1165     // Add any uses of the old node to the worklist in case this node is the
1166     // last one that uses them.  They may become dead after this node is
1167     // deleted.
1168     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1169       AddToWorkList(N->getOperand(i).getNode());
1170
1171     // Finally, if the node is now dead, remove it from the graph.  The node
1172     // may not be dead if the replacement process recursively simplified to
1173     // something else needing this node.
1174     if (N->use_empty()) {
1175       // Nodes can be reintroduced into the worklist.  Make sure we do not
1176       // process a node that has been replaced.
1177       removeFromWorkList(N);
1178
1179       // Finally, since the node is now dead, remove it from the graph.
1180       DAG.DeleteNode(N);
1181     }
1182   }
1183
1184   // If the root changed (e.g. it was a dead load, update the root).
1185   DAG.setRoot(Dummy.getValue());
1186   DAG.RemoveDeadNodes();
1187 }
1188
1189 SDValue DAGCombiner::visit(SDNode *N) {
1190   switch (N->getOpcode()) {
1191   default: break;
1192   case ISD::TokenFactor:        return visitTokenFactor(N);
1193   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1194   case ISD::ADD:                return visitADD(N);
1195   case ISD::SUB:                return visitSUB(N);
1196   case ISD::ADDC:               return visitADDC(N);
1197   case ISD::SUBC:               return visitSUBC(N);
1198   case ISD::ADDE:               return visitADDE(N);
1199   case ISD::SUBE:               return visitSUBE(N);
1200   case ISD::MUL:                return visitMUL(N);
1201   case ISD::SDIV:               return visitSDIV(N);
1202   case ISD::UDIV:               return visitUDIV(N);
1203   case ISD::SREM:               return visitSREM(N);
1204   case ISD::UREM:               return visitUREM(N);
1205   case ISD::MULHU:              return visitMULHU(N);
1206   case ISD::MULHS:              return visitMULHS(N);
1207   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1208   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1209   case ISD::SMULO:              return visitSMULO(N);
1210   case ISD::UMULO:              return visitUMULO(N);
1211   case ISD::SDIVREM:            return visitSDIVREM(N);
1212   case ISD::UDIVREM:            return visitUDIVREM(N);
1213   case ISD::AND:                return visitAND(N);
1214   case ISD::OR:                 return visitOR(N);
1215   case ISD::XOR:                return visitXOR(N);
1216   case ISD::SHL:                return visitSHL(N);
1217   case ISD::SRA:                return visitSRA(N);
1218   case ISD::SRL:                return visitSRL(N);
1219   case ISD::ROTR:
1220   case ISD::ROTL:               return visitRotate(N);
1221   case ISD::CTLZ:               return visitCTLZ(N);
1222   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1223   case ISD::CTTZ:               return visitCTTZ(N);
1224   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1225   case ISD::CTPOP:              return visitCTPOP(N);
1226   case ISD::SELECT:             return visitSELECT(N);
1227   case ISD::VSELECT:            return visitVSELECT(N);
1228   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1229   case ISD::SETCC:              return visitSETCC(N);
1230   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1231   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1232   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1233   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1234   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1235   case ISD::BITCAST:            return visitBITCAST(N);
1236   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1237   case ISD::FADD:               return visitFADD(N);
1238   case ISD::FSUB:               return visitFSUB(N);
1239   case ISD::FMUL:               return visitFMUL(N);
1240   case ISD::FMA:                return visitFMA(N);
1241   case ISD::FDIV:               return visitFDIV(N);
1242   case ISD::FREM:               return visitFREM(N);
1243   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1244   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1245   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1246   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1247   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1248   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1249   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1250   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1251   case ISD::FNEG:               return visitFNEG(N);
1252   case ISD::FABS:               return visitFABS(N);
1253   case ISD::FFLOOR:             return visitFFLOOR(N);
1254   case ISD::FCEIL:              return visitFCEIL(N);
1255   case ISD::FTRUNC:             return visitFTRUNC(N);
1256   case ISD::BRCOND:             return visitBRCOND(N);
1257   case ISD::BR_CC:              return visitBR_CC(N);
1258   case ISD::LOAD:               return visitLOAD(N);
1259   case ISD::STORE:              return visitSTORE(N);
1260   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1261   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1262   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1263   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1264   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1265   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1266   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1267   }
1268   return SDValue();
1269 }
1270
1271 SDValue DAGCombiner::combine(SDNode *N) {
1272   SDValue RV = visit(N);
1273
1274   // If nothing happened, try a target-specific DAG combine.
1275   if (!RV.getNode()) {
1276     assert(N->getOpcode() != ISD::DELETED_NODE &&
1277            "Node was deleted but visit returned NULL!");
1278
1279     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1280         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1281
1282       // Expose the DAG combiner to the target combiner impls.
1283       TargetLowering::DAGCombinerInfo
1284         DagCombineInfo(DAG, Level, false, this);
1285
1286       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1287     }
1288   }
1289
1290   // If nothing happened still, try promoting the operation.
1291   if (!RV.getNode()) {
1292     switch (N->getOpcode()) {
1293     default: break;
1294     case ISD::ADD:
1295     case ISD::SUB:
1296     case ISD::MUL:
1297     case ISD::AND:
1298     case ISD::OR:
1299     case ISD::XOR:
1300       RV = PromoteIntBinOp(SDValue(N, 0));
1301       break;
1302     case ISD::SHL:
1303     case ISD::SRA:
1304     case ISD::SRL:
1305       RV = PromoteIntShiftOp(SDValue(N, 0));
1306       break;
1307     case ISD::SIGN_EXTEND:
1308     case ISD::ZERO_EXTEND:
1309     case ISD::ANY_EXTEND:
1310       RV = PromoteExtend(SDValue(N, 0));
1311       break;
1312     case ISD::LOAD:
1313       if (PromoteLoad(SDValue(N, 0)))
1314         RV = SDValue(N, 0);
1315       break;
1316     }
1317   }
1318
1319   // If N is a commutative binary node, try commuting it to enable more
1320   // sdisel CSE.
1321   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1322       N->getNumValues() == 1) {
1323     SDValue N0 = N->getOperand(0);
1324     SDValue N1 = N->getOperand(1);
1325
1326     // Constant operands are canonicalized to RHS.
1327     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1328       SDValue Ops[] = { N1, N0 };
1329       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1330                                             Ops);
1331       if (CSENode)
1332         return SDValue(CSENode, 0);
1333     }
1334   }
1335
1336   return RV;
1337 }
1338
1339 /// getInputChainForNode - Given a node, return its input chain if it has one,
1340 /// otherwise return a null sd operand.
1341 static SDValue getInputChainForNode(SDNode *N) {
1342   if (unsigned NumOps = N->getNumOperands()) {
1343     if (N->getOperand(0).getValueType() == MVT::Other)
1344       return N->getOperand(0);
1345     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1346       return N->getOperand(NumOps-1);
1347     for (unsigned i = 1; i < NumOps-1; ++i)
1348       if (N->getOperand(i).getValueType() == MVT::Other)
1349         return N->getOperand(i);
1350   }
1351   return SDValue();
1352 }
1353
1354 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1355   // If N has two operands, where one has an input chain equal to the other,
1356   // the 'other' chain is redundant.
1357   if (N->getNumOperands() == 2) {
1358     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1359       return N->getOperand(0);
1360     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1361       return N->getOperand(1);
1362   }
1363
1364   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1365   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1366   SmallPtrSet<SDNode*, 16> SeenOps;
1367   bool Changed = false;             // If we should replace this token factor.
1368
1369   // Start out with this token factor.
1370   TFs.push_back(N);
1371
1372   // Iterate through token factors.  The TFs grows when new token factors are
1373   // encountered.
1374   for (unsigned i = 0; i < TFs.size(); ++i) {
1375     SDNode *TF = TFs[i];
1376
1377     // Check each of the operands.
1378     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1379       SDValue Op = TF->getOperand(i);
1380
1381       switch (Op.getOpcode()) {
1382       case ISD::EntryToken:
1383         // Entry tokens don't need to be added to the list. They are
1384         // rededundant.
1385         Changed = true;
1386         break;
1387
1388       case ISD::TokenFactor:
1389         if (Op.hasOneUse() &&
1390             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1391           // Queue up for processing.
1392           TFs.push_back(Op.getNode());
1393           // Clean up in case the token factor is removed.
1394           AddToWorkList(Op.getNode());
1395           Changed = true;
1396           break;
1397         }
1398         // Fall thru
1399
1400       default:
1401         // Only add if it isn't already in the list.
1402         if (SeenOps.insert(Op.getNode()))
1403           Ops.push_back(Op);
1404         else
1405           Changed = true;
1406         break;
1407       }
1408     }
1409   }
1410
1411   SDValue Result;
1412
1413   // If we've change things around then replace token factor.
1414   if (Changed) {
1415     if (Ops.empty()) {
1416       // The entry token is the only possible outcome.
1417       Result = DAG.getEntryNode();
1418     } else {
1419       // New and improved token factor.
1420       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1421     }
1422
1423     // Don't add users to work list.
1424     return CombineTo(N, Result, false);
1425   }
1426
1427   return Result;
1428 }
1429
1430 /// MERGE_VALUES can always be eliminated.
1431 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1432   WorkListRemover DeadNodes(*this);
1433   // Replacing results may cause a different MERGE_VALUES to suddenly
1434   // be CSE'd with N, and carry its uses with it. Iterate until no
1435   // uses remain, to ensure that the node can be safely deleted.
1436   // First add the users of this node to the work list so that they
1437   // can be tried again once they have new operands.
1438   AddUsersToWorkList(N);
1439   do {
1440     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1441       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1442   } while (!N->use_empty());
1443   removeFromWorkList(N);
1444   DAG.DeleteNode(N);
1445   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1446 }
1447
1448 static
1449 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1450                               SelectionDAG &DAG) {
1451   EVT VT = N0.getValueType();
1452   SDValue N00 = N0.getOperand(0);
1453   SDValue N01 = N0.getOperand(1);
1454   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1455
1456   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1457       isa<ConstantSDNode>(N00.getOperand(1))) {
1458     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1459     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1460                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1461                                  N00.getOperand(0), N01),
1462                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1463                                  N00.getOperand(1), N01));
1464     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1465   }
1466
1467   return SDValue();
1468 }
1469
1470 SDValue DAGCombiner::visitADD(SDNode *N) {
1471   SDValue N0 = N->getOperand(0);
1472   SDValue N1 = N->getOperand(1);
1473   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1474   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1475   EVT VT = N0.getValueType();
1476
1477   // fold vector ops
1478   if (VT.isVector()) {
1479     SDValue FoldedVOp = SimplifyVBinOp(N);
1480     if (FoldedVOp.getNode()) return FoldedVOp;
1481
1482     // fold (add x, 0) -> x, vector edition
1483     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1484       return N0;
1485     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1486       return N1;
1487   }
1488
1489   // fold (add x, undef) -> undef
1490   if (N0.getOpcode() == ISD::UNDEF)
1491     return N0;
1492   if (N1.getOpcode() == ISD::UNDEF)
1493     return N1;
1494   // fold (add c1, c2) -> c1+c2
1495   if (N0C && N1C)
1496     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1497   // canonicalize constant to RHS
1498   if (N0C && !N1C)
1499     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1500   // fold (add x, 0) -> x
1501   if (N1C && N1C->isNullValue())
1502     return N0;
1503   // fold (add Sym, c) -> Sym+c
1504   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1505     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1506         GA->getOpcode() == ISD::GlobalAddress)
1507       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1508                                   GA->getOffset() +
1509                                     (uint64_t)N1C->getSExtValue());
1510   // fold ((c1-A)+c2) -> (c1+c2)-A
1511   if (N1C && N0.getOpcode() == ISD::SUB)
1512     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1513       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1514                          DAG.getConstant(N1C->getAPIntValue()+
1515                                          N0C->getAPIntValue(), VT),
1516                          N0.getOperand(1));
1517   // reassociate add
1518   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1519   if (RADD.getNode())
1520     return RADD;
1521   // fold ((0-A) + B) -> B-A
1522   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1523       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1524     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1525   // fold (A + (0-B)) -> A-B
1526   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1527       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1528     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1529   // fold (A+(B-A)) -> B
1530   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1531     return N1.getOperand(0);
1532   // fold ((B-A)+A) -> B
1533   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1534     return N0.getOperand(0);
1535   // fold (A+(B-(A+C))) to (B-C)
1536   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1537       N0 == N1.getOperand(1).getOperand(0))
1538     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1539                        N1.getOperand(1).getOperand(1));
1540   // fold (A+(B-(C+A))) to (B-C)
1541   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1542       N0 == N1.getOperand(1).getOperand(1))
1543     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1544                        N1.getOperand(1).getOperand(0));
1545   // fold (A+((B-A)+or-C)) to (B+or-C)
1546   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1547       N1.getOperand(0).getOpcode() == ISD::SUB &&
1548       N0 == N1.getOperand(0).getOperand(1))
1549     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1550                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1551
1552   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1553   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1554     SDValue N00 = N0.getOperand(0);
1555     SDValue N01 = N0.getOperand(1);
1556     SDValue N10 = N1.getOperand(0);
1557     SDValue N11 = N1.getOperand(1);
1558
1559     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1560       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1561                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1562                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1563   }
1564
1565   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1566     return SDValue(N, 0);
1567
1568   // fold (a+b) -> (a|b) iff a and b share no bits.
1569   if (VT.isInteger() && !VT.isVector()) {
1570     APInt LHSZero, LHSOne;
1571     APInt RHSZero, RHSOne;
1572     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1573
1574     if (LHSZero.getBoolValue()) {
1575       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1576
1577       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1578       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1579       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1580         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1581           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1582       }
1583     }
1584   }
1585
1586   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1587   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1588     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1589     if (Result.getNode()) return Result;
1590   }
1591   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1592     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1593     if (Result.getNode()) return Result;
1594   }
1595
1596   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1597   if (N1.getOpcode() == ISD::SHL &&
1598       N1.getOperand(0).getOpcode() == ISD::SUB)
1599     if (ConstantSDNode *C =
1600           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1601       if (C->getAPIntValue() == 0)
1602         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1603                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1604                                        N1.getOperand(0).getOperand(1),
1605                                        N1.getOperand(1)));
1606   if (N0.getOpcode() == ISD::SHL &&
1607       N0.getOperand(0).getOpcode() == ISD::SUB)
1608     if (ConstantSDNode *C =
1609           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1610       if (C->getAPIntValue() == 0)
1611         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1612                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1613                                        N0.getOperand(0).getOperand(1),
1614                                        N0.getOperand(1)));
1615
1616   if (N1.getOpcode() == ISD::AND) {
1617     SDValue AndOp0 = N1.getOperand(0);
1618     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1619     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1620     unsigned DestBits = VT.getScalarType().getSizeInBits();
1621
1622     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1623     // and similar xforms where the inner op is either ~0 or 0.
1624     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1625       SDLoc DL(N);
1626       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1627     }
1628   }
1629
1630   // add (sext i1), X -> sub X, (zext i1)
1631   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1632       N0.getOperand(0).getValueType() == MVT::i1 &&
1633       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1634     SDLoc DL(N);
1635     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1636     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1637   }
1638
1639   return SDValue();
1640 }
1641
1642 SDValue DAGCombiner::visitADDC(SDNode *N) {
1643   SDValue N0 = N->getOperand(0);
1644   SDValue N1 = N->getOperand(1);
1645   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1646   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1647   EVT VT = N0.getValueType();
1648
1649   // If the flag result is dead, turn this into an ADD.
1650   if (!N->hasAnyUseOfValue(1))
1651     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1652                      DAG.getNode(ISD::CARRY_FALSE,
1653                                  SDLoc(N), MVT::Glue));
1654
1655   // canonicalize constant to RHS.
1656   if (N0C && !N1C)
1657     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1658
1659   // fold (addc x, 0) -> x + no carry out
1660   if (N1C && N1C->isNullValue())
1661     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1662                                         SDLoc(N), MVT::Glue));
1663
1664   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1665   APInt LHSZero, LHSOne;
1666   APInt RHSZero, RHSOne;
1667   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1668
1669   if (LHSZero.getBoolValue()) {
1670     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1671
1672     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1673     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1674     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1675       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1676                        DAG.getNode(ISD::CARRY_FALSE,
1677                                    SDLoc(N), MVT::Glue));
1678   }
1679
1680   return SDValue();
1681 }
1682
1683 SDValue DAGCombiner::visitADDE(SDNode *N) {
1684   SDValue N0 = N->getOperand(0);
1685   SDValue N1 = N->getOperand(1);
1686   SDValue CarryIn = N->getOperand(2);
1687   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1688   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1689
1690   // canonicalize constant to RHS
1691   if (N0C && !N1C)
1692     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1693                        N1, N0, CarryIn);
1694
1695   // fold (adde x, y, false) -> (addc x, y)
1696   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1697     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1698
1699   return SDValue();
1700 }
1701
1702 // Since it may not be valid to emit a fold to zero for vector initializers
1703 // check if we can before folding.
1704 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1705                              SelectionDAG &DAG,
1706                              bool LegalOperations, bool LegalTypes) {
1707   if (!VT.isVector())
1708     return DAG.getConstant(0, VT);
1709   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1710     return DAG.getConstant(0, VT);
1711   return SDValue();
1712 }
1713
1714 SDValue DAGCombiner::visitSUB(SDNode *N) {
1715   SDValue N0 = N->getOperand(0);
1716   SDValue N1 = N->getOperand(1);
1717   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1718   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1719   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1720     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1721   EVT VT = N0.getValueType();
1722
1723   // fold vector ops
1724   if (VT.isVector()) {
1725     SDValue FoldedVOp = SimplifyVBinOp(N);
1726     if (FoldedVOp.getNode()) return FoldedVOp;
1727
1728     // fold (sub x, 0) -> x, vector edition
1729     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1730       return N0;
1731   }
1732
1733   // fold (sub x, x) -> 0
1734   // FIXME: Refactor this and xor and other similar operations together.
1735   if (N0 == N1)
1736     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1737   // fold (sub c1, c2) -> c1-c2
1738   if (N0C && N1C)
1739     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1740   // fold (sub x, c) -> (add x, -c)
1741   if (N1C)
1742     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1743                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1744   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1745   if (N0C && N0C->isAllOnesValue())
1746     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1747   // fold A-(A-B) -> B
1748   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1749     return N1.getOperand(1);
1750   // fold (A+B)-A -> B
1751   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1752     return N0.getOperand(1);
1753   // fold (A+B)-B -> A
1754   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1755     return N0.getOperand(0);
1756   // fold C2-(A+C1) -> (C2-C1)-A
1757   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1758     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1759                                    VT);
1760     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1761                        N1.getOperand(0));
1762   }
1763   // fold ((A+(B+or-C))-B) -> A+or-C
1764   if (N0.getOpcode() == ISD::ADD &&
1765       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1766        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1767       N0.getOperand(1).getOperand(0) == N1)
1768     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1769                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1770   // fold ((A+(C+B))-B) -> A+C
1771   if (N0.getOpcode() == ISD::ADD &&
1772       N0.getOperand(1).getOpcode() == ISD::ADD &&
1773       N0.getOperand(1).getOperand(1) == N1)
1774     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1775                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1776   // fold ((A-(B-C))-C) -> A-B
1777   if (N0.getOpcode() == ISD::SUB &&
1778       N0.getOperand(1).getOpcode() == ISD::SUB &&
1779       N0.getOperand(1).getOperand(1) == N1)
1780     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1781                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1782
1783   // If either operand of a sub is undef, the result is undef
1784   if (N0.getOpcode() == ISD::UNDEF)
1785     return N0;
1786   if (N1.getOpcode() == ISD::UNDEF)
1787     return N1;
1788
1789   // If the relocation model supports it, consider symbol offsets.
1790   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1791     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1792       // fold (sub Sym, c) -> Sym-c
1793       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1794         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1795                                     GA->getOffset() -
1796                                       (uint64_t)N1C->getSExtValue());
1797       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1798       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1799         if (GA->getGlobal() == GB->getGlobal())
1800           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1801                                  VT);
1802     }
1803
1804   return SDValue();
1805 }
1806
1807 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1808   SDValue N0 = N->getOperand(0);
1809   SDValue N1 = N->getOperand(1);
1810   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1811   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1812   EVT VT = N0.getValueType();
1813
1814   // If the flag result is dead, turn this into an SUB.
1815   if (!N->hasAnyUseOfValue(1))
1816     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1817                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1818                                  MVT::Glue));
1819
1820   // fold (subc x, x) -> 0 + no borrow
1821   if (N0 == N1)
1822     return CombineTo(N, DAG.getConstant(0, VT),
1823                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1824                                  MVT::Glue));
1825
1826   // fold (subc x, 0) -> x + no borrow
1827   if (N1C && N1C->isNullValue())
1828     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1829                                         MVT::Glue));
1830
1831   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1832   if (N0C && N0C->isAllOnesValue())
1833     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1834                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1835                                  MVT::Glue));
1836
1837   return SDValue();
1838 }
1839
1840 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1841   SDValue N0 = N->getOperand(0);
1842   SDValue N1 = N->getOperand(1);
1843   SDValue CarryIn = N->getOperand(2);
1844
1845   // fold (sube x, y, false) -> (subc x, y)
1846   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1847     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1848
1849   return SDValue();
1850 }
1851
1852 SDValue DAGCombiner::visitMUL(SDNode *N) {
1853   SDValue N0 = N->getOperand(0);
1854   SDValue N1 = N->getOperand(1);
1855   EVT VT = N0.getValueType();
1856
1857   // fold (mul x, undef) -> 0
1858   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1859     return DAG.getConstant(0, VT);
1860
1861   bool N0IsConst = false;
1862   bool N1IsConst = false;
1863   APInt ConstValue0, ConstValue1;
1864   // fold vector ops
1865   if (VT.isVector()) {
1866     SDValue FoldedVOp = SimplifyVBinOp(N);
1867     if (FoldedVOp.getNode()) return FoldedVOp;
1868
1869     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1870     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1871   } else {
1872     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1873     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1874                             : APInt();
1875     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1876     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1877                             : APInt();
1878   }
1879
1880   // fold (mul c1, c2) -> c1*c2
1881   if (N0IsConst && N1IsConst)
1882     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1883
1884   // canonicalize constant to RHS
1885   if (N0IsConst && !N1IsConst)
1886     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1887   // fold (mul x, 0) -> 0
1888   if (N1IsConst && ConstValue1 == 0)
1889     return N1;
1890   // We require a splat of the entire scalar bit width for non-contiguous
1891   // bit patterns.
1892   bool IsFullSplat =
1893     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1894   // fold (mul x, 1) -> x
1895   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1896     return N0;
1897   // fold (mul x, -1) -> 0-x
1898   if (N1IsConst && ConstValue1.isAllOnesValue())
1899     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1900                        DAG.getConstant(0, VT), N0);
1901   // fold (mul x, (1 << c)) -> x << c
1902   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1903     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1904                        DAG.getConstant(ConstValue1.logBase2(),
1905                                        getShiftAmountTy(N0.getValueType())));
1906   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1907   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1908     unsigned Log2Val = (-ConstValue1).logBase2();
1909     // FIXME: If the input is something that is easily negated (e.g. a
1910     // single-use add), we should put the negate there.
1911     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1912                        DAG.getConstant(0, VT),
1913                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1914                             DAG.getConstant(Log2Val,
1915                                       getShiftAmountTy(N0.getValueType()))));
1916   }
1917
1918   APInt Val;
1919   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1920   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1921       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1922                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1923     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1924                              N1, N0.getOperand(1));
1925     AddToWorkList(C3.getNode());
1926     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1927                        N0.getOperand(0), C3);
1928   }
1929
1930   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1931   // use.
1932   {
1933     SDValue Sh(nullptr,0), Y(nullptr,0);
1934     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1935     if (N0.getOpcode() == ISD::SHL &&
1936         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1937                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1938         N0.getNode()->hasOneUse()) {
1939       Sh = N0; Y = N1;
1940     } else if (N1.getOpcode() == ISD::SHL &&
1941                isa<ConstantSDNode>(N1.getOperand(1)) &&
1942                N1.getNode()->hasOneUse()) {
1943       Sh = N1; Y = N0;
1944     }
1945
1946     if (Sh.getNode()) {
1947       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1948                                 Sh.getOperand(0), Y);
1949       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1950                          Mul, Sh.getOperand(1));
1951     }
1952   }
1953
1954   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1955   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1956       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1957                      isa<ConstantSDNode>(N0.getOperand(1))))
1958     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1959                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1960                                    N0.getOperand(0), N1),
1961                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1962                                    N0.getOperand(1), N1));
1963
1964   // reassociate mul
1965   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1966   if (RMUL.getNode())
1967     return RMUL;
1968
1969   return SDValue();
1970 }
1971
1972 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1973   SDValue N0 = N->getOperand(0);
1974   SDValue N1 = N->getOperand(1);
1975   ConstantSDNode *N0C = isConstOrConstSplat(N0);
1976   ConstantSDNode *N1C = isConstOrConstSplat(N1);
1977   EVT VT = N->getValueType(0);
1978
1979   // fold vector ops
1980   if (VT.isVector()) {
1981     SDValue FoldedVOp = SimplifyVBinOp(N);
1982     if (FoldedVOp.getNode()) return FoldedVOp;
1983   }
1984
1985   // fold (sdiv c1, c2) -> c1/c2
1986   if (N0C && N1C && !N1C->isNullValue())
1987     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1988   // fold (sdiv X, 1) -> X
1989   if (N1C && N1C->getAPIntValue() == 1LL)
1990     return N0;
1991   // fold (sdiv X, -1) -> 0-X
1992   if (N1C && N1C->isAllOnesValue())
1993     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1994                        DAG.getConstant(0, VT), N0);
1995   // If we know the sign bits of both operands are zero, strength reduce to a
1996   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1997   if (!VT.isVector()) {
1998     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1999       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2000                          N0, N1);
2001   }
2002
2003   // fold (sdiv X, pow2) -> simple ops after legalize
2004   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2005                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2006     // If dividing by powers of two is cheap, then don't perform the following
2007     // fold.
2008     if (TLI.isPow2DivCheap())
2009       return SDValue();
2010
2011     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2012
2013     // Splat the sign bit into the register
2014     SDValue SGN =
2015         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2016                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2017                                     getShiftAmountTy(N0.getValueType())));
2018     AddToWorkList(SGN.getNode());
2019
2020     // Add (N0 < 0) ? abs2 - 1 : 0;
2021     SDValue SRL =
2022         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2023                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2024                                     getShiftAmountTy(SGN.getValueType())));
2025     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2026     AddToWorkList(SRL.getNode());
2027     AddToWorkList(ADD.getNode());    // Divide by pow2
2028     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2029                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2030
2031     // If we're dividing by a positive value, we're done.  Otherwise, we must
2032     // negate the result.
2033     if (N1C->getAPIntValue().isNonNegative())
2034       return SRA;
2035
2036     AddToWorkList(SRA.getNode());
2037     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2038   }
2039
2040   // if integer divide is expensive and we satisfy the requirements, emit an
2041   // alternate sequence.
2042   if (N1C && !TLI.isIntDivCheap()) {
2043     SDValue Op = BuildSDIV(N);
2044     if (Op.getNode()) return Op;
2045   }
2046
2047   // undef / X -> 0
2048   if (N0.getOpcode() == ISD::UNDEF)
2049     return DAG.getConstant(0, VT);
2050   // X / undef -> undef
2051   if (N1.getOpcode() == ISD::UNDEF)
2052     return N1;
2053
2054   return SDValue();
2055 }
2056
2057 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2058   SDValue N0 = N->getOperand(0);
2059   SDValue N1 = N->getOperand(1);
2060   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2061   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2062   EVT VT = N->getValueType(0);
2063
2064   // fold vector ops
2065   if (VT.isVector()) {
2066     SDValue FoldedVOp = SimplifyVBinOp(N);
2067     if (FoldedVOp.getNode()) return FoldedVOp;
2068   }
2069
2070   // fold (udiv c1, c2) -> c1/c2
2071   if (N0C && N1C && !N1C->isNullValue())
2072     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2073   // fold (udiv x, (1 << c)) -> x >>u c
2074   if (N1C && N1C->getAPIntValue().isPowerOf2())
2075     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2076                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2077                                        getShiftAmountTy(N0.getValueType())));
2078   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2079   if (N1.getOpcode() == ISD::SHL) {
2080     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2081       if (SHC->getAPIntValue().isPowerOf2()) {
2082         EVT ADDVT = N1.getOperand(1).getValueType();
2083         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2084                                   N1.getOperand(1),
2085                                   DAG.getConstant(SHC->getAPIntValue()
2086                                                                   .logBase2(),
2087                                                   ADDVT));
2088         AddToWorkList(Add.getNode());
2089         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2090       }
2091     }
2092   }
2093   // fold (udiv x, c) -> alternate
2094   if (N1C && !TLI.isIntDivCheap()) {
2095     SDValue Op = BuildUDIV(N);
2096     if (Op.getNode()) return Op;
2097   }
2098
2099   // undef / X -> 0
2100   if (N0.getOpcode() == ISD::UNDEF)
2101     return DAG.getConstant(0, VT);
2102   // X / undef -> undef
2103   if (N1.getOpcode() == ISD::UNDEF)
2104     return N1;
2105
2106   return SDValue();
2107 }
2108
2109 SDValue DAGCombiner::visitSREM(SDNode *N) {
2110   SDValue N0 = N->getOperand(0);
2111   SDValue N1 = N->getOperand(1);
2112   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2113   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2114   EVT VT = N->getValueType(0);
2115
2116   // fold (srem c1, c2) -> c1%c2
2117   if (N0C && N1C && !N1C->isNullValue())
2118     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2119   // If we know the sign bits of both operands are zero, strength reduce to a
2120   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2121   if (!VT.isVector()) {
2122     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2123       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2124   }
2125
2126   // If X/C can be simplified by the division-by-constant logic, lower
2127   // X%C to the equivalent of X-X/C*C.
2128   if (N1C && !N1C->isNullValue()) {
2129     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2130     AddToWorkList(Div.getNode());
2131     SDValue OptimizedDiv = combine(Div.getNode());
2132     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2133       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2134                                 OptimizedDiv, N1);
2135       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2136       AddToWorkList(Mul.getNode());
2137       return Sub;
2138     }
2139   }
2140
2141   // undef % X -> 0
2142   if (N0.getOpcode() == ISD::UNDEF)
2143     return DAG.getConstant(0, VT);
2144   // X % undef -> undef
2145   if (N1.getOpcode() == ISD::UNDEF)
2146     return N1;
2147
2148   return SDValue();
2149 }
2150
2151 SDValue DAGCombiner::visitUREM(SDNode *N) {
2152   SDValue N0 = N->getOperand(0);
2153   SDValue N1 = N->getOperand(1);
2154   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2155   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2156   EVT VT = N->getValueType(0);
2157
2158   // fold (urem c1, c2) -> c1%c2
2159   if (N0C && N1C && !N1C->isNullValue())
2160     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2161   // fold (urem x, pow2) -> (and x, pow2-1)
2162   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2163     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2164                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2165   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2166   if (N1.getOpcode() == ISD::SHL) {
2167     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2168       if (SHC->getAPIntValue().isPowerOf2()) {
2169         SDValue Add =
2170           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2171                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2172                                  VT));
2173         AddToWorkList(Add.getNode());
2174         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2175       }
2176     }
2177   }
2178
2179   // If X/C can be simplified by the division-by-constant logic, lower
2180   // X%C to the equivalent of X-X/C*C.
2181   if (N1C && !N1C->isNullValue()) {
2182     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2183     AddToWorkList(Div.getNode());
2184     SDValue OptimizedDiv = combine(Div.getNode());
2185     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2186       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2187                                 OptimizedDiv, N1);
2188       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2189       AddToWorkList(Mul.getNode());
2190       return Sub;
2191     }
2192   }
2193
2194   // undef % X -> 0
2195   if (N0.getOpcode() == ISD::UNDEF)
2196     return DAG.getConstant(0, VT);
2197   // X % undef -> undef
2198   if (N1.getOpcode() == ISD::UNDEF)
2199     return N1;
2200
2201   return SDValue();
2202 }
2203
2204 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2205   SDValue N0 = N->getOperand(0);
2206   SDValue N1 = N->getOperand(1);
2207   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2208   EVT VT = N->getValueType(0);
2209   SDLoc DL(N);
2210
2211   // fold (mulhs x, 0) -> 0
2212   if (N1C && N1C->isNullValue())
2213     return N1;
2214   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2215   if (N1C && N1C->getAPIntValue() == 1)
2216     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2217                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2218                                        getShiftAmountTy(N0.getValueType())));
2219   // fold (mulhs x, undef) -> 0
2220   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2221     return DAG.getConstant(0, VT);
2222
2223   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2224   // plus a shift.
2225   if (VT.isSimple() && !VT.isVector()) {
2226     MVT Simple = VT.getSimpleVT();
2227     unsigned SimpleSize = Simple.getSizeInBits();
2228     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2229     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2230       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2231       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2232       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2233       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2234             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2235       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2236     }
2237   }
2238
2239   return SDValue();
2240 }
2241
2242 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2243   SDValue N0 = N->getOperand(0);
2244   SDValue N1 = N->getOperand(1);
2245   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2246   EVT VT = N->getValueType(0);
2247   SDLoc DL(N);
2248
2249   // fold (mulhu x, 0) -> 0
2250   if (N1C && N1C->isNullValue())
2251     return N1;
2252   // fold (mulhu x, 1) -> 0
2253   if (N1C && N1C->getAPIntValue() == 1)
2254     return DAG.getConstant(0, N0.getValueType());
2255   // fold (mulhu x, undef) -> 0
2256   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2257     return DAG.getConstant(0, VT);
2258
2259   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2260   // plus a shift.
2261   if (VT.isSimple() && !VT.isVector()) {
2262     MVT Simple = VT.getSimpleVT();
2263     unsigned SimpleSize = Simple.getSizeInBits();
2264     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2265     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2266       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2267       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2268       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2269       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2270             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2271       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2272     }
2273   }
2274
2275   return SDValue();
2276 }
2277
2278 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2279 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2280 /// that are being performed. Return true if a simplification was made.
2281 ///
2282 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2283                                                 unsigned HiOp) {
2284   // If the high half is not needed, just compute the low half.
2285   bool HiExists = N->hasAnyUseOfValue(1);
2286   if (!HiExists &&
2287       (!LegalOperations ||
2288        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2289     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2290                               ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2291     return CombineTo(N, Res, Res);
2292   }
2293
2294   // If the low half is not needed, just compute the high half.
2295   bool LoExists = N->hasAnyUseOfValue(0);
2296   if (!LoExists &&
2297       (!LegalOperations ||
2298        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2299     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2300                               ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2301     return CombineTo(N, Res, Res);
2302   }
2303
2304   // If both halves are used, return as it is.
2305   if (LoExists && HiExists)
2306     return SDValue();
2307
2308   // If the two computed results can be simplified separately, separate them.
2309   if (LoExists) {
2310     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2311                              ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2312     AddToWorkList(Lo.getNode());
2313     SDValue LoOpt = combine(Lo.getNode());
2314     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2315         (!LegalOperations ||
2316          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2317       return CombineTo(N, LoOpt, LoOpt);
2318   }
2319
2320   if (HiExists) {
2321     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2322                              ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2323     AddToWorkList(Hi.getNode());
2324     SDValue HiOpt = combine(Hi.getNode());
2325     if (HiOpt.getNode() && HiOpt != Hi &&
2326         (!LegalOperations ||
2327          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2328       return CombineTo(N, HiOpt, HiOpt);
2329   }
2330
2331   return SDValue();
2332 }
2333
2334 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2335   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2336   if (Res.getNode()) return Res;
2337
2338   EVT VT = N->getValueType(0);
2339   SDLoc DL(N);
2340
2341   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2342   // plus a shift.
2343   if (VT.isSimple() && !VT.isVector()) {
2344     MVT Simple = VT.getSimpleVT();
2345     unsigned SimpleSize = Simple.getSizeInBits();
2346     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2347     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2348       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2349       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2350       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2351       // Compute the high part as N1.
2352       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2353             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2354       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2355       // Compute the low part as N0.
2356       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2357       return CombineTo(N, Lo, Hi);
2358     }
2359   }
2360
2361   return SDValue();
2362 }
2363
2364 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2365   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2366   if (Res.getNode()) return Res;
2367
2368   EVT VT = N->getValueType(0);
2369   SDLoc DL(N);
2370
2371   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2372   // plus a shift.
2373   if (VT.isSimple() && !VT.isVector()) {
2374     MVT Simple = VT.getSimpleVT();
2375     unsigned SimpleSize = Simple.getSizeInBits();
2376     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2377     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2378       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2379       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2380       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2381       // Compute the high part as N1.
2382       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2383             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2384       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2385       // Compute the low part as N0.
2386       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2387       return CombineTo(N, Lo, Hi);
2388     }
2389   }
2390
2391   return SDValue();
2392 }
2393
2394 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2395   // (smulo x, 2) -> (saddo x, x)
2396   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2397     if (C2->getAPIntValue() == 2)
2398       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2399                          N->getOperand(0), N->getOperand(0));
2400
2401   return SDValue();
2402 }
2403
2404 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2405   // (umulo x, 2) -> (uaddo x, x)
2406   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2407     if (C2->getAPIntValue() == 2)
2408       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2409                          N->getOperand(0), N->getOperand(0));
2410
2411   return SDValue();
2412 }
2413
2414 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2415   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2416   if (Res.getNode()) return Res;
2417
2418   return SDValue();
2419 }
2420
2421 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2422   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2423   if (Res.getNode()) return Res;
2424
2425   return SDValue();
2426 }
2427
2428 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2429 /// two operands of the same opcode, try to simplify it.
2430 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2431   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2432   EVT VT = N0.getValueType();
2433   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2434
2435   // Bail early if none of these transforms apply.
2436   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2437
2438   // For each of OP in AND/OR/XOR:
2439   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2440   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2441   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2442   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2443   //
2444   // do not sink logical op inside of a vector extend, since it may combine
2445   // into a vsetcc.
2446   EVT Op0VT = N0.getOperand(0).getValueType();
2447   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2448        N0.getOpcode() == ISD::SIGN_EXTEND ||
2449        // Avoid infinite looping with PromoteIntBinOp.
2450        (N0.getOpcode() == ISD::ANY_EXTEND &&
2451         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2452        (N0.getOpcode() == ISD::TRUNCATE &&
2453         (!TLI.isZExtFree(VT, Op0VT) ||
2454          !TLI.isTruncateFree(Op0VT, VT)) &&
2455         TLI.isTypeLegal(Op0VT))) &&
2456       !VT.isVector() &&
2457       Op0VT == N1.getOperand(0).getValueType() &&
2458       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2459     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2460                                  N0.getOperand(0).getValueType(),
2461                                  N0.getOperand(0), N1.getOperand(0));
2462     AddToWorkList(ORNode.getNode());
2463     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2464   }
2465
2466   // For each of OP in SHL/SRL/SRA/AND...
2467   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2468   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2469   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2470   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2471        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2472       N0.getOperand(1) == N1.getOperand(1)) {
2473     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2474                                  N0.getOperand(0).getValueType(),
2475                                  N0.getOperand(0), N1.getOperand(0));
2476     AddToWorkList(ORNode.getNode());
2477     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2478                        ORNode, N0.getOperand(1));
2479   }
2480
2481   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2482   // Only perform this optimization after type legalization and before
2483   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2484   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2485   // we don't want to undo this promotion.
2486   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2487   // on scalars.
2488   if ((N0.getOpcode() == ISD::BITCAST ||
2489        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2490       Level == AfterLegalizeTypes) {
2491     SDValue In0 = N0.getOperand(0);
2492     SDValue In1 = N1.getOperand(0);
2493     EVT In0Ty = In0.getValueType();
2494     EVT In1Ty = In1.getValueType();
2495     SDLoc DL(N);
2496     // If both incoming values are integers, and the original types are the
2497     // same.
2498     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2499       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2500       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2501       AddToWorkList(Op.getNode());
2502       return BC;
2503     }
2504   }
2505
2506   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2507   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2508   // If both shuffles use the same mask, and both shuffle within a single
2509   // vector, then it is worthwhile to move the swizzle after the operation.
2510   // The type-legalizer generates this pattern when loading illegal
2511   // vector types from memory. In many cases this allows additional shuffle
2512   // optimizations.
2513   // There are other cases where moving the shuffle after the xor/and/or
2514   // is profitable even if shuffles don't perform a swizzle.
2515   // If both shuffles use the same mask, and both shuffles have the same first
2516   // or second operand, then it might still be profitable to move the shuffle
2517   // after the xor/and/or operation.
2518   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2519     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2520     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2521
2522     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2523            "Inputs to shuffles are not the same type");
2524
2525     // Check that both shuffles use the same mask. The masks are known to be of
2526     // the same length because the result vector type is the same.
2527     // Check also that shuffles have only one use to avoid introducing extra
2528     // instructions.
2529     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2530         SVN0->getMask().equals(SVN1->getMask())) {
2531       SDValue ShOp = N0->getOperand(1);
2532
2533       // Don't try to fold this node if it requires introducing a
2534       // build vector of all zeros that might be illegal at this stage.
2535       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2536         if (!LegalTypes)
2537           ShOp = DAG.getConstant(0, VT);
2538         else
2539           ShOp = SDValue();
2540       }
2541
2542       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2543       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2544       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2545       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2546         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2547                                       N0->getOperand(0), N1->getOperand(0));
2548         AddToWorkList(NewNode.getNode());
2549         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2550                                     &SVN0->getMask()[0]);
2551       }
2552
2553       // Don't try to fold this node if it requires introducing a
2554       // build vector of all zeros that might be illegal at this stage.
2555       ShOp = N0->getOperand(0);
2556       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2557         if (!LegalTypes)
2558           ShOp = DAG.getConstant(0, VT);
2559         else
2560           ShOp = SDValue();
2561       }
2562
2563       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2564       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2565       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2566       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2567         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2568                                       N0->getOperand(1), N1->getOperand(1));
2569         AddToWorkList(NewNode.getNode());
2570         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2571                                     &SVN0->getMask()[0]);
2572       }
2573     }
2574   }
2575
2576   return SDValue();
2577 }
2578
2579 SDValue DAGCombiner::visitAND(SDNode *N) {
2580   SDValue N0 = N->getOperand(0);
2581   SDValue N1 = N->getOperand(1);
2582   SDValue LL, LR, RL, RR, CC0, CC1;
2583   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2584   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2585   EVT VT = N1.getValueType();
2586   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2587
2588   // fold vector ops
2589   if (VT.isVector()) {
2590     SDValue FoldedVOp = SimplifyVBinOp(N);
2591     if (FoldedVOp.getNode()) return FoldedVOp;
2592
2593     // fold (and x, 0) -> 0, vector edition
2594     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2595       return N0;
2596     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2597       return N1;
2598
2599     // fold (and x, -1) -> x, vector edition
2600     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2601       return N1;
2602     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2603       return N0;
2604   }
2605
2606   // fold (and x, undef) -> 0
2607   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2608     return DAG.getConstant(0, VT);
2609   // fold (and c1, c2) -> c1&c2
2610   if (N0C && N1C)
2611     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2612   // canonicalize constant to RHS
2613   if (N0C && !N1C)
2614     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2615   // fold (and x, -1) -> x
2616   if (N1C && N1C->isAllOnesValue())
2617     return N0;
2618   // if (and x, c) is known to be zero, return 0
2619   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2620                                    APInt::getAllOnesValue(BitWidth)))
2621     return DAG.getConstant(0, VT);
2622   // reassociate and
2623   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2624   if (RAND.getNode())
2625     return RAND;
2626   // fold (and (or x, C), D) -> D if (C & D) == D
2627   if (N1C && N0.getOpcode() == ISD::OR)
2628     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2629       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2630         return N1;
2631   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2632   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2633     SDValue N0Op0 = N0.getOperand(0);
2634     APInt Mask = ~N1C->getAPIntValue();
2635     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2636     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2637       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2638                                  N0.getValueType(), N0Op0);
2639
2640       // Replace uses of the AND with uses of the Zero extend node.
2641       CombineTo(N, Zext);
2642
2643       // We actually want to replace all uses of the any_extend with the
2644       // zero_extend, to avoid duplicating things.  This will later cause this
2645       // AND to be folded.
2646       CombineTo(N0.getNode(), Zext);
2647       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2648     }
2649   }
2650   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2651   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2652   // already be zero by virtue of the width of the base type of the load.
2653   //
2654   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2655   // more cases.
2656   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2657        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2658       N0.getOpcode() == ISD::LOAD) {
2659     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2660                                          N0 : N0.getOperand(0) );
2661
2662     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2663     // This can be a pure constant or a vector splat, in which case we treat the
2664     // vector as a scalar and use the splat value.
2665     APInt Constant = APInt::getNullValue(1);
2666     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2667       Constant = C->getAPIntValue();
2668     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2669       APInt SplatValue, SplatUndef;
2670       unsigned SplatBitSize;
2671       bool HasAnyUndefs;
2672       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2673                                              SplatBitSize, HasAnyUndefs);
2674       if (IsSplat) {
2675         // Undef bits can contribute to a possible optimisation if set, so
2676         // set them.
2677         SplatValue |= SplatUndef;
2678
2679         // The splat value may be something like "0x00FFFFFF", which means 0 for
2680         // the first vector value and FF for the rest, repeating. We need a mask
2681         // that will apply equally to all members of the vector, so AND all the
2682         // lanes of the constant together.
2683         EVT VT = Vector->getValueType(0);
2684         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2685
2686         // If the splat value has been compressed to a bitlength lower
2687         // than the size of the vector lane, we need to re-expand it to
2688         // the lane size.
2689         if (BitWidth > SplatBitSize)
2690           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2691                SplatBitSize < BitWidth;
2692                SplatBitSize = SplatBitSize * 2)
2693             SplatValue |= SplatValue.shl(SplatBitSize);
2694
2695         Constant = APInt::getAllOnesValue(BitWidth);
2696         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2697           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2698       }
2699     }
2700
2701     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2702     // actually legal and isn't going to get expanded, else this is a false
2703     // optimisation.
2704     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2705                                                     Load->getMemoryVT());
2706
2707     // Resize the constant to the same size as the original memory access before
2708     // extension. If it is still the AllOnesValue then this AND is completely
2709     // unneeded.
2710     Constant =
2711       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2712
2713     bool B;
2714     switch (Load->getExtensionType()) {
2715     default: B = false; break;
2716     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2717     case ISD::ZEXTLOAD:
2718     case ISD::NON_EXTLOAD: B = true; break;
2719     }
2720
2721     if (B && Constant.isAllOnesValue()) {
2722       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2723       // preserve semantics once we get rid of the AND.
2724       SDValue NewLoad(Load, 0);
2725       if (Load->getExtensionType() == ISD::EXTLOAD) {
2726         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2727                               Load->getValueType(0), SDLoc(Load),
2728                               Load->getChain(), Load->getBasePtr(),
2729                               Load->getOffset(), Load->getMemoryVT(),
2730                               Load->getMemOperand());
2731         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2732         if (Load->getNumValues() == 3) {
2733           // PRE/POST_INC loads have 3 values.
2734           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2735                            NewLoad.getValue(2) };
2736           CombineTo(Load, To, 3, true);
2737         } else {
2738           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2739         }
2740       }
2741
2742       // Fold the AND away, taking care not to fold to the old load node if we
2743       // replaced it.
2744       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2745
2746       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2747     }
2748   }
2749   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2750   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2751     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2752     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2753
2754     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2755         LL.getValueType().isInteger()) {
2756       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2757       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2758         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2759                                      LR.getValueType(), LL, RL);
2760         AddToWorkList(ORNode.getNode());
2761         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2762       }
2763       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2764       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2765         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2766                                       LR.getValueType(), LL, RL);
2767         AddToWorkList(ANDNode.getNode());
2768         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2769       }
2770       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2771       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2772         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2773                                      LR.getValueType(), LL, RL);
2774         AddToWorkList(ORNode.getNode());
2775         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2776       }
2777     }
2778     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2779     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2780         Op0 == Op1 && LL.getValueType().isInteger() &&
2781       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2782                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2783                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2784                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2785       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2786                                     LL, DAG.getConstant(1, LL.getValueType()));
2787       AddToWorkList(ADDNode.getNode());
2788       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2789                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2790     }
2791     // canonicalize equivalent to ll == rl
2792     if (LL == RR && LR == RL) {
2793       Op1 = ISD::getSetCCSwappedOperands(Op1);
2794       std::swap(RL, RR);
2795     }
2796     if (LL == RL && LR == RR) {
2797       bool isInteger = LL.getValueType().isInteger();
2798       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2799       if (Result != ISD::SETCC_INVALID &&
2800           (!LegalOperations ||
2801            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2802             TLI.isOperationLegal(ISD::SETCC,
2803                             getSetCCResultType(N0.getSimpleValueType())))))
2804         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2805                             LL, LR, Result);
2806     }
2807   }
2808
2809   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2810   if (N0.getOpcode() == N1.getOpcode()) {
2811     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2812     if (Tmp.getNode()) return Tmp;
2813   }
2814
2815   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2816   // fold (and (sra)) -> (and (srl)) when possible.
2817   if (!VT.isVector() &&
2818       SimplifyDemandedBits(SDValue(N, 0)))
2819     return SDValue(N, 0);
2820
2821   // fold (zext_inreg (extload x)) -> (zextload x)
2822   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2823     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2824     EVT MemVT = LN0->getMemoryVT();
2825     // If we zero all the possible extended bits, then we can turn this into
2826     // a zextload if we are running before legalize or the operation is legal.
2827     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2828     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2829                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2830         ((!LegalOperations && !LN0->isVolatile()) ||
2831          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2832       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2833                                        LN0->getChain(), LN0->getBasePtr(),
2834                                        MemVT, LN0->getMemOperand());
2835       AddToWorkList(N);
2836       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2837       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2838     }
2839   }
2840   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2841   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2842       N0.hasOneUse()) {
2843     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2844     EVT MemVT = LN0->getMemoryVT();
2845     // If we zero all the possible extended bits, then we can turn this into
2846     // a zextload if we are running before legalize or the operation is legal.
2847     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2848     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2849                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2850         ((!LegalOperations && !LN0->isVolatile()) ||
2851          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2852       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2853                                        LN0->getChain(), LN0->getBasePtr(),
2854                                        MemVT, LN0->getMemOperand());
2855       AddToWorkList(N);
2856       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2857       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2858     }
2859   }
2860
2861   // fold (and (load x), 255) -> (zextload x, i8)
2862   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2863   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2864   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2865               (N0.getOpcode() == ISD::ANY_EXTEND &&
2866                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2867     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2868     LoadSDNode *LN0 = HasAnyExt
2869       ? cast<LoadSDNode>(N0.getOperand(0))
2870       : cast<LoadSDNode>(N0);
2871     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2872         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2873       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2874       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2875         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2876         EVT LoadedVT = LN0->getMemoryVT();
2877
2878         if (ExtVT == LoadedVT &&
2879             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2880           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2881
2882           SDValue NewLoad =
2883             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2884                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2885                            LN0->getMemOperand());
2886           AddToWorkList(N);
2887           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2888           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2889         }
2890
2891         // Do not change the width of a volatile load.
2892         // Do not generate loads of non-round integer types since these can
2893         // be expensive (and would be wrong if the type is not byte sized).
2894         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2895             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2896           EVT PtrType = LN0->getOperand(1).getValueType();
2897
2898           unsigned Alignment = LN0->getAlignment();
2899           SDValue NewPtr = LN0->getBasePtr();
2900
2901           // For big endian targets, we need to add an offset to the pointer
2902           // to load the correct bytes.  For little endian systems, we merely
2903           // need to read fewer bytes from the same pointer.
2904           if (TLI.isBigEndian()) {
2905             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2906             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2907             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2908             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2909                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2910             Alignment = MinAlign(Alignment, PtrOff);
2911           }
2912
2913           AddToWorkList(NewPtr.getNode());
2914
2915           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2916           SDValue Load =
2917             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2918                            LN0->getChain(), NewPtr,
2919                            LN0->getPointerInfo(),
2920                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2921                            Alignment, LN0->getTBAAInfo());
2922           AddToWorkList(N);
2923           CombineTo(LN0, Load, Load.getValue(1));
2924           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2925         }
2926       }
2927     }
2928   }
2929
2930   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2931       VT.getSizeInBits() <= 64) {
2932     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2933       APInt ADDC = ADDI->getAPIntValue();
2934       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2935         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2936         // immediate for an add, but it is legal if its top c2 bits are set,
2937         // transform the ADD so the immediate doesn't need to be materialized
2938         // in a register.
2939         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2940           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2941                                              SRLI->getZExtValue());
2942           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2943             ADDC |= Mask;
2944             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2945               SDValue NewAdd =
2946                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2947                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2948               CombineTo(N0.getNode(), NewAdd);
2949               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2950             }
2951           }
2952         }
2953       }
2954     }
2955   }
2956
2957   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2958   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2959     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2960                                        N0.getOperand(1), false);
2961     if (BSwap.getNode())
2962       return BSwap;
2963   }
2964
2965   return SDValue();
2966 }
2967
2968 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2969 ///
2970 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2971                                         bool DemandHighBits) {
2972   if (!LegalOperations)
2973     return SDValue();
2974
2975   EVT VT = N->getValueType(0);
2976   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2977     return SDValue();
2978   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2979     return SDValue();
2980
2981   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2982   bool LookPassAnd0 = false;
2983   bool LookPassAnd1 = false;
2984   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2985       std::swap(N0, N1);
2986   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2987       std::swap(N0, N1);
2988   if (N0.getOpcode() == ISD::AND) {
2989     if (!N0.getNode()->hasOneUse())
2990       return SDValue();
2991     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2992     if (!N01C || N01C->getZExtValue() != 0xFF00)
2993       return SDValue();
2994     N0 = N0.getOperand(0);
2995     LookPassAnd0 = true;
2996   }
2997
2998   if (N1.getOpcode() == ISD::AND) {
2999     if (!N1.getNode()->hasOneUse())
3000       return SDValue();
3001     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3002     if (!N11C || N11C->getZExtValue() != 0xFF)
3003       return SDValue();
3004     N1 = N1.getOperand(0);
3005     LookPassAnd1 = true;
3006   }
3007
3008   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3009     std::swap(N0, N1);
3010   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3011     return SDValue();
3012   if (!N0.getNode()->hasOneUse() ||
3013       !N1.getNode()->hasOneUse())
3014     return SDValue();
3015
3016   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3017   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3018   if (!N01C || !N11C)
3019     return SDValue();
3020   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3021     return SDValue();
3022
3023   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3024   SDValue N00 = N0->getOperand(0);
3025   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3026     if (!N00.getNode()->hasOneUse())
3027       return SDValue();
3028     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3029     if (!N001C || N001C->getZExtValue() != 0xFF)
3030       return SDValue();
3031     N00 = N00.getOperand(0);
3032     LookPassAnd0 = true;
3033   }
3034
3035   SDValue N10 = N1->getOperand(0);
3036   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3037     if (!N10.getNode()->hasOneUse())
3038       return SDValue();
3039     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3040     if (!N101C || N101C->getZExtValue() != 0xFF00)
3041       return SDValue();
3042     N10 = N10.getOperand(0);
3043     LookPassAnd1 = true;
3044   }
3045
3046   if (N00 != N10)
3047     return SDValue();
3048
3049   // Make sure everything beyond the low halfword gets set to zero since the SRL
3050   // 16 will clear the top bits.
3051   unsigned OpSizeInBits = VT.getSizeInBits();
3052   if (DemandHighBits && OpSizeInBits > 16) {
3053     // If the left-shift isn't masked out then the only way this is a bswap is
3054     // if all bits beyond the low 8 are 0. In that case the entire pattern
3055     // reduces to a left shift anyway: leave it for other parts of the combiner.
3056     if (!LookPassAnd0)
3057       return SDValue();
3058
3059     // However, if the right shift isn't masked out then it might be because
3060     // it's not needed. See if we can spot that too.
3061     if (!LookPassAnd1 &&
3062         !DAG.MaskedValueIsZero(
3063             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3064       return SDValue();
3065   }
3066
3067   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3068   if (OpSizeInBits > 16)
3069     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3070                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3071   return Res;
3072 }
3073
3074 /// isBSwapHWordElement - Return true if the specified node is an element
3075 /// that makes up a 32-bit packed halfword byteswap. i.e.
3076 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3077 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3078   if (!N.getNode()->hasOneUse())
3079     return false;
3080
3081   unsigned Opc = N.getOpcode();
3082   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3083     return false;
3084
3085   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3086   if (!N1C)
3087     return false;
3088
3089   unsigned Num;
3090   switch (N1C->getZExtValue()) {
3091   default:
3092     return false;
3093   case 0xFF:       Num = 0; break;
3094   case 0xFF00:     Num = 1; break;
3095   case 0xFF0000:   Num = 2; break;
3096   case 0xFF000000: Num = 3; break;
3097   }
3098
3099   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3100   SDValue N0 = N.getOperand(0);
3101   if (Opc == ISD::AND) {
3102     if (Num == 0 || Num == 2) {
3103       // (x >> 8) & 0xff
3104       // (x >> 8) & 0xff0000
3105       if (N0.getOpcode() != ISD::SRL)
3106         return false;
3107       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3108       if (!C || C->getZExtValue() != 8)
3109         return false;
3110     } else {
3111       // (x << 8) & 0xff00
3112       // (x << 8) & 0xff000000
3113       if (N0.getOpcode() != ISD::SHL)
3114         return false;
3115       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3116       if (!C || C->getZExtValue() != 8)
3117         return false;
3118     }
3119   } else if (Opc == ISD::SHL) {
3120     // (x & 0xff) << 8
3121     // (x & 0xff0000) << 8
3122     if (Num != 0 && Num != 2)
3123       return false;
3124     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3125     if (!C || C->getZExtValue() != 8)
3126       return false;
3127   } else { // Opc == ISD::SRL
3128     // (x & 0xff00) >> 8
3129     // (x & 0xff000000) >> 8
3130     if (Num != 1 && Num != 3)
3131       return false;
3132     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3133     if (!C || C->getZExtValue() != 8)
3134       return false;
3135   }
3136
3137   if (Parts[Num])
3138     return false;
3139
3140   Parts[Num] = N0.getOperand(0).getNode();
3141   return true;
3142 }
3143
3144 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3145 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3146 /// => (rotl (bswap x), 16)
3147 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3148   if (!LegalOperations)
3149     return SDValue();
3150
3151   EVT VT = N->getValueType(0);
3152   if (VT != MVT::i32)
3153     return SDValue();
3154   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3155     return SDValue();
3156
3157   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3158   // Look for either
3159   // (or (or (and), (and)), (or (and), (and)))
3160   // (or (or (or (and), (and)), (and)), (and))
3161   if (N0.getOpcode() != ISD::OR)
3162     return SDValue();
3163   SDValue N00 = N0.getOperand(0);
3164   SDValue N01 = N0.getOperand(1);
3165
3166   if (N1.getOpcode() == ISD::OR &&
3167       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3168     // (or (or (and), (and)), (or (and), (and)))
3169     SDValue N000 = N00.getOperand(0);
3170     if (!isBSwapHWordElement(N000, Parts))
3171       return SDValue();
3172
3173     SDValue N001 = N00.getOperand(1);
3174     if (!isBSwapHWordElement(N001, Parts))
3175       return SDValue();
3176     SDValue N010 = N01.getOperand(0);
3177     if (!isBSwapHWordElement(N010, Parts))
3178       return SDValue();
3179     SDValue N011 = N01.getOperand(1);
3180     if (!isBSwapHWordElement(N011, Parts))
3181       return SDValue();
3182   } else {
3183     // (or (or (or (and), (and)), (and)), (and))
3184     if (!isBSwapHWordElement(N1, Parts))
3185       return SDValue();
3186     if (!isBSwapHWordElement(N01, Parts))
3187       return SDValue();
3188     if (N00.getOpcode() != ISD::OR)
3189       return SDValue();
3190     SDValue N000 = N00.getOperand(0);
3191     if (!isBSwapHWordElement(N000, Parts))
3192       return SDValue();
3193     SDValue N001 = N00.getOperand(1);
3194     if (!isBSwapHWordElement(N001, Parts))
3195       return SDValue();
3196   }
3197
3198   // Make sure the parts are all coming from the same node.
3199   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3200     return SDValue();
3201
3202   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3203                               SDValue(Parts[0],0));
3204
3205   // Result of the bswap should be rotated by 16. If it's not legal, then
3206   // do  (x << 16) | (x >> 16).
3207   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3208   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3209     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3210   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3211     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3212   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3213                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3214                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3215 }
3216
3217 SDValue DAGCombiner::visitOR(SDNode *N) {
3218   SDValue N0 = N->getOperand(0);
3219   SDValue N1 = N->getOperand(1);
3220   SDValue LL, LR, RL, RR, CC0, CC1;
3221   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3222   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3223   EVT VT = N1.getValueType();
3224
3225   // fold vector ops
3226   if (VT.isVector()) {
3227     SDValue FoldedVOp = SimplifyVBinOp(N);
3228     if (FoldedVOp.getNode()) return FoldedVOp;
3229
3230     // fold (or x, 0) -> x, vector edition
3231     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3232       return N1;
3233     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3234       return N0;
3235
3236     // fold (or x, -1) -> -1, vector edition
3237     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3238       return N0;
3239     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3240       return N1;
3241
3242     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3243     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3244     // Do this only if the resulting shuffle is legal.
3245     if (isa<ShuffleVectorSDNode>(N0) &&
3246         isa<ShuffleVectorSDNode>(N1) &&
3247         N0->getOperand(1) == N1->getOperand(1) &&
3248         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3249       bool CanFold = true;
3250       unsigned NumElts = VT.getVectorNumElements();
3251       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3252       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3253       // We construct two shuffle masks:
3254       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3255       // and N1 as the second operand.
3256       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3257       // and N0 as the second operand.
3258       // We do this because OR is commutable and therefore there might be
3259       // two ways to fold this node into a shuffle.
3260       SmallVector<int,4> Mask1;
3261       SmallVector<int,4> Mask2;
3262
3263       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3264         int M0 = SV0->getMaskElt(i);
3265         int M1 = SV1->getMaskElt(i);
3266
3267         // Both shuffle indexes are undef. Propagate Undef.
3268         if (M0 < 0 && M1 < 0) {
3269           Mask1.push_back(M0);
3270           Mask2.push_back(M0);
3271           continue;
3272         }
3273
3274         if (M0 < 0 || M1 < 0 ||
3275             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3276             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3277           CanFold = false;
3278           break;
3279         }
3280
3281         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3282         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3283       }
3284
3285       if (CanFold) {
3286         // Fold this sequence only if the resulting shuffle is 'legal'.
3287         if (TLI.isShuffleMaskLegal(Mask1, VT))
3288           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3289                                       N1->getOperand(0), &Mask1[0]);
3290         if (TLI.isShuffleMaskLegal(Mask2, VT))
3291           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3292                                       N0->getOperand(0), &Mask2[0]);
3293       }
3294     }
3295   }
3296
3297   // fold (or x, undef) -> -1
3298   if (!LegalOperations &&
3299       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3300     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3301     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3302   }
3303   // fold (or c1, c2) -> c1|c2
3304   if (N0C && N1C)
3305     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3306   // canonicalize constant to RHS
3307   if (N0C && !N1C)
3308     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3309   // fold (or x, 0) -> x
3310   if (N1C && N1C->isNullValue())
3311     return N0;
3312   // fold (or x, -1) -> -1
3313   if (N1C && N1C->isAllOnesValue())
3314     return N1;
3315   // fold (or x, c) -> c iff (x & ~c) == 0
3316   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3317     return N1;
3318
3319   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3320   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3321   if (BSwap.getNode())
3322     return BSwap;
3323   BSwap = MatchBSwapHWordLow(N, N0, N1);
3324   if (BSwap.getNode())
3325     return BSwap;
3326
3327   // reassociate or
3328   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3329   if (ROR.getNode())
3330     return ROR;
3331   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3332   // iff (c1 & c2) == 0.
3333   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3334              isa<ConstantSDNode>(N0.getOperand(1))) {
3335     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3336     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3337       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3338       if (!COR.getNode())
3339         return SDValue();
3340       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3341                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3342                                      N0.getOperand(0), N1), COR);
3343     }
3344   }
3345   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3346   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3347     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3348     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3349
3350     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3351         LL.getValueType().isInteger()) {
3352       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3353       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3354       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3355           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3356         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3357                                      LR.getValueType(), LL, RL);
3358         AddToWorkList(ORNode.getNode());
3359         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3360       }
3361       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3362       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3363       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3364           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3365         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3366                                       LR.getValueType(), LL, RL);
3367         AddToWorkList(ANDNode.getNode());
3368         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3369       }
3370     }
3371     // canonicalize equivalent to ll == rl
3372     if (LL == RR && LR == RL) {
3373       Op1 = ISD::getSetCCSwappedOperands(Op1);
3374       std::swap(RL, RR);
3375     }
3376     if (LL == RL && LR == RR) {
3377       bool isInteger = LL.getValueType().isInteger();
3378       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3379       if (Result != ISD::SETCC_INVALID &&
3380           (!LegalOperations ||
3381            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3382             TLI.isOperationLegal(ISD::SETCC,
3383               getSetCCResultType(N0.getValueType())))))
3384         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3385                             LL, LR, Result);
3386     }
3387   }
3388
3389   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3390   if (N0.getOpcode() == N1.getOpcode()) {
3391     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3392     if (Tmp.getNode()) return Tmp;
3393   }
3394
3395   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3396   if (N0.getOpcode() == ISD::AND &&
3397       N1.getOpcode() == ISD::AND &&
3398       N0.getOperand(1).getOpcode() == ISD::Constant &&
3399       N1.getOperand(1).getOpcode() == ISD::Constant &&
3400       // Don't increase # computations.
3401       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3402     // We can only do this xform if we know that bits from X that are set in C2
3403     // but not in C1 are already zero.  Likewise for Y.
3404     const APInt &LHSMask =
3405       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3406     const APInt &RHSMask =
3407       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3408
3409     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3410         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3411       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3412                               N0.getOperand(0), N1.getOperand(0));
3413       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3414                          DAG.getConstant(LHSMask | RHSMask, VT));
3415     }
3416   }
3417
3418   // See if this is some rotate idiom.
3419   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3420     return SDValue(Rot, 0);
3421
3422   // Simplify the operands using demanded-bits information.
3423   if (!VT.isVector() &&
3424       SimplifyDemandedBits(SDValue(N, 0)))
3425     return SDValue(N, 0);
3426
3427   return SDValue();
3428 }
3429
3430 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3431 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3432   if (Op.getOpcode() == ISD::AND) {
3433     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3434       Mask = Op.getOperand(1);
3435       Op = Op.getOperand(0);
3436     } else {
3437       return false;
3438     }
3439   }
3440
3441   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3442     Shift = Op;
3443     return true;
3444   }
3445
3446   return false;
3447 }
3448
3449 // Return true if we can prove that, whenever Neg and Pos are both in the
3450 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3451 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3452 //
3453 //     (or (shift1 X, Neg), (shift2 X, Pos))
3454 //
3455 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3456 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3457 // to consider shift amounts with defined behavior.
3458 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3459   // If OpSize is a power of 2 then:
3460   //
3461   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3462   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3463   //
3464   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3465   // for the stronger condition:
3466   //
3467   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3468   //
3469   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3470   // we can just replace Neg with Neg' for the rest of the function.
3471   //
3472   // In other cases we check for the even stronger condition:
3473   //
3474   //     Neg == OpSize - Pos                                    [B]
3475   //
3476   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3477   // behavior if Pos == 0 (and consequently Neg == OpSize).
3478   //
3479   // We could actually use [A] whenever OpSize is a power of 2, but the
3480   // only extra cases that it would match are those uninteresting ones
3481   // where Neg and Pos are never in range at the same time.  E.g. for
3482   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3483   // as well as (sub 32, Pos), but:
3484   //
3485   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3486   //
3487   // always invokes undefined behavior for 32-bit X.
3488   //
3489   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3490   unsigned MaskLoBits = 0;
3491   if (Neg.getOpcode() == ISD::AND &&
3492       isPowerOf2_64(OpSize) &&
3493       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3494       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3495     Neg = Neg.getOperand(0);
3496     MaskLoBits = Log2_64(OpSize);
3497   }
3498
3499   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3500   if (Neg.getOpcode() != ISD::SUB)
3501     return 0;
3502   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3503   if (!NegC)
3504     return 0;
3505   SDValue NegOp1 = Neg.getOperand(1);
3506
3507   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3508   // Pos'.  The truncation is redundant for the purpose of the equality.
3509   if (MaskLoBits &&
3510       Pos.getOpcode() == ISD::AND &&
3511       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3512       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3513     Pos = Pos.getOperand(0);
3514
3515   // The condition we need is now:
3516   //
3517   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3518   //
3519   // If NegOp1 == Pos then we need:
3520   //
3521   //              OpSize & Mask == NegC & Mask
3522   //
3523   // (because "x & Mask" is a truncation and distributes through subtraction).
3524   APInt Width;
3525   if (Pos == NegOp1)
3526     Width = NegC->getAPIntValue();
3527   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3528   // Then the condition we want to prove becomes:
3529   //
3530   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3531   //
3532   // which, again because "x & Mask" is a truncation, becomes:
3533   //
3534   //                NegC & Mask == (OpSize - PosC) & Mask
3535   //              OpSize & Mask == (NegC + PosC) & Mask
3536   else if (Pos.getOpcode() == ISD::ADD &&
3537            Pos.getOperand(0) == NegOp1 &&
3538            Pos.getOperand(1).getOpcode() == ISD::Constant)
3539     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3540              NegC->getAPIntValue());
3541   else
3542     return false;
3543
3544   // Now we just need to check that OpSize & Mask == Width & Mask.
3545   if (MaskLoBits)
3546     // Opsize & Mask is 0 since Mask is Opsize - 1.
3547     return Width.getLoBits(MaskLoBits) == 0;
3548   return Width == OpSize;
3549 }
3550
3551 // A subroutine of MatchRotate used once we have found an OR of two opposite
3552 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3553 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3554 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3555 // Neg with outer conversions stripped away.
3556 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3557                                        SDValue Neg, SDValue InnerPos,
3558                                        SDValue InnerNeg, unsigned PosOpcode,
3559                                        unsigned NegOpcode, SDLoc DL) {
3560   // fold (or (shl x, (*ext y)),
3561   //          (srl x, (*ext (sub 32, y)))) ->
3562   //   (rotl x, y) or (rotr x, (sub 32, y))
3563   //
3564   // fold (or (shl x, (*ext (sub 32, y))),
3565   //          (srl x, (*ext y))) ->
3566   //   (rotr x, y) or (rotl x, (sub 32, y))
3567   EVT VT = Shifted.getValueType();
3568   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3569     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3570     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3571                        HasPos ? Pos : Neg).getNode();
3572   }
3573
3574   return nullptr;
3575 }
3576
3577 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3578 // idioms for rotate, and if the target supports rotation instructions, generate
3579 // a rot[lr].
3580 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3581   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3582   EVT VT = LHS.getValueType();
3583   if (!TLI.isTypeLegal(VT)) return nullptr;
3584
3585   // The target must have at least one rotate flavor.
3586   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3587   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3588   if (!HasROTL && !HasROTR) return nullptr;
3589
3590   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3591   SDValue LHSShift;   // The shift.
3592   SDValue LHSMask;    // AND value if any.
3593   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3594     return nullptr; // Not part of a rotate.
3595
3596   SDValue RHSShift;   // The shift.
3597   SDValue RHSMask;    // AND value if any.
3598   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3599     return nullptr; // Not part of a rotate.
3600
3601   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3602     return nullptr;   // Not shifting the same value.
3603
3604   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3605     return nullptr;   // Shifts must disagree.
3606
3607   // Canonicalize shl to left side in a shl/srl pair.
3608   if (RHSShift.getOpcode() == ISD::SHL) {
3609     std::swap(LHS, RHS);
3610     std::swap(LHSShift, RHSShift);
3611     std::swap(LHSMask , RHSMask );
3612   }
3613
3614   unsigned OpSizeInBits = VT.getSizeInBits();
3615   SDValue LHSShiftArg = LHSShift.getOperand(0);
3616   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3617   SDValue RHSShiftArg = RHSShift.getOperand(0);
3618   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3619
3620   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3621   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3622   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3623       RHSShiftAmt.getOpcode() == ISD::Constant) {
3624     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3625     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3626     if ((LShVal + RShVal) != OpSizeInBits)
3627       return nullptr;
3628
3629     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3630                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3631
3632     // If there is an AND of either shifted operand, apply it to the result.
3633     if (LHSMask.getNode() || RHSMask.getNode()) {
3634       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3635
3636       if (LHSMask.getNode()) {
3637         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3638         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3639       }
3640       if (RHSMask.getNode()) {
3641         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3642         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3643       }
3644
3645       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3646     }
3647
3648     return Rot.getNode();
3649   }
3650
3651   // If there is a mask here, and we have a variable shift, we can't be sure
3652   // that we're masking out the right stuff.
3653   if (LHSMask.getNode() || RHSMask.getNode())
3654     return nullptr;
3655
3656   // If the shift amount is sign/zext/any-extended just peel it off.
3657   SDValue LExtOp0 = LHSShiftAmt;
3658   SDValue RExtOp0 = RHSShiftAmt;
3659   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3660        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3661        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3662        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3663       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3664        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3665        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3666        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3667     LExtOp0 = LHSShiftAmt.getOperand(0);
3668     RExtOp0 = RHSShiftAmt.getOperand(0);
3669   }
3670
3671   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3672                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3673   if (TryL)
3674     return TryL;
3675
3676   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3677                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3678   if (TryR)
3679     return TryR;
3680
3681   return nullptr;
3682 }
3683
3684 SDValue DAGCombiner::visitXOR(SDNode *N) {
3685   SDValue N0 = N->getOperand(0);
3686   SDValue N1 = N->getOperand(1);
3687   SDValue LHS, RHS, CC;
3688   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3689   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3690   EVT VT = N0.getValueType();
3691
3692   // fold vector ops
3693   if (VT.isVector()) {
3694     SDValue FoldedVOp = SimplifyVBinOp(N);
3695     if (FoldedVOp.getNode()) return FoldedVOp;
3696
3697     // fold (xor x, 0) -> x, vector edition
3698     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3699       return N1;
3700     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3701       return N0;
3702   }
3703
3704   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3705   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3706     return DAG.getConstant(0, VT);
3707   // fold (xor x, undef) -> undef
3708   if (N0.getOpcode() == ISD::UNDEF)
3709     return N0;
3710   if (N1.getOpcode() == ISD::UNDEF)
3711     return N1;
3712   // fold (xor c1, c2) -> c1^c2
3713   if (N0C && N1C)
3714     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3715   // canonicalize constant to RHS
3716   if (N0C && !N1C)
3717     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3718   // fold (xor x, 0) -> x
3719   if (N1C && N1C->isNullValue())
3720     return N0;
3721   // reassociate xor
3722   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3723   if (RXOR.getNode())
3724     return RXOR;
3725
3726   // fold !(x cc y) -> (x !cc y)
3727   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3728     bool isInt = LHS.getValueType().isInteger();
3729     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3730                                                isInt);
3731
3732     if (!LegalOperations ||
3733         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3734       switch (N0.getOpcode()) {
3735       default:
3736         llvm_unreachable("Unhandled SetCC Equivalent!");
3737       case ISD::SETCC:
3738         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3739       case ISD::SELECT_CC:
3740         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3741                                N0.getOperand(3), NotCC);
3742       }
3743     }
3744   }
3745
3746   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3747   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3748       N0.getNode()->hasOneUse() &&
3749       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3750     SDValue V = N0.getOperand(0);
3751     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3752                     DAG.getConstant(1, V.getValueType()));
3753     AddToWorkList(V.getNode());
3754     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3755   }
3756
3757   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3758   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3759       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3760     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3761     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3762       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3763       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3764       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3765       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3766       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3767     }
3768   }
3769   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3770   if (N1C && N1C->isAllOnesValue() &&
3771       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3772     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3773     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3774       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3775       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3776       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3777       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3778       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3779     }
3780   }
3781   // fold (xor (and x, y), y) -> (and (not x), y)
3782   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3783       N0->getOperand(1) == N1) {
3784     SDValue X = N0->getOperand(0);
3785     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3786     AddToWorkList(NotX.getNode());
3787     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3788   }
3789   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3790   if (N1C && N0.getOpcode() == ISD::XOR) {
3791     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3792     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3793     if (N00C)
3794       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3795                          DAG.getConstant(N1C->getAPIntValue() ^
3796                                          N00C->getAPIntValue(), VT));
3797     if (N01C)
3798       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3799                          DAG.getConstant(N1C->getAPIntValue() ^
3800                                          N01C->getAPIntValue(), VT));
3801   }
3802   // fold (xor x, x) -> 0
3803   if (N0 == N1)
3804     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3805
3806   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3807   if (N0.getOpcode() == N1.getOpcode()) {
3808     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3809     if (Tmp.getNode()) return Tmp;
3810   }
3811
3812   // Simplify the expression using non-local knowledge.
3813   if (!VT.isVector() &&
3814       SimplifyDemandedBits(SDValue(N, 0)))
3815     return SDValue(N, 0);
3816
3817   return SDValue();
3818 }
3819
3820 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3821 /// the shift amount is a constant.
3822 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3823   // We can't and shouldn't fold opaque constants.
3824   if (Amt->isOpaque())
3825     return SDValue();
3826
3827   SDNode *LHS = N->getOperand(0).getNode();
3828   if (!LHS->hasOneUse()) return SDValue();
3829
3830   // We want to pull some binops through shifts, so that we have (and (shift))
3831   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3832   // thing happens with address calculations, so it's important to canonicalize
3833   // it.
3834   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3835
3836   switch (LHS->getOpcode()) {
3837   default: return SDValue();
3838   case ISD::OR:
3839   case ISD::XOR:
3840     HighBitSet = false; // We can only transform sra if the high bit is clear.
3841     break;
3842   case ISD::AND:
3843     HighBitSet = true;  // We can only transform sra if the high bit is set.
3844     break;
3845   case ISD::ADD:
3846     if (N->getOpcode() != ISD::SHL)
3847       return SDValue(); // only shl(add) not sr[al](add).
3848     HighBitSet = false; // We can only transform sra if the high bit is clear.
3849     break;
3850   }
3851
3852   // We require the RHS of the binop to be a constant and not opaque as well.
3853   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3854   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3855
3856   // FIXME: disable this unless the input to the binop is a shift by a constant.
3857   // If it is not a shift, it pessimizes some common cases like:
3858   //
3859   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3860   //    int bar(int *X, int i) { return X[i & 255]; }
3861   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3862   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3863        BinOpLHSVal->getOpcode() != ISD::SRA &&
3864        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3865       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3866     return SDValue();
3867
3868   EVT VT = N->getValueType(0);
3869
3870   // If this is a signed shift right, and the high bit is modified by the
3871   // logical operation, do not perform the transformation. The highBitSet
3872   // boolean indicates the value of the high bit of the constant which would
3873   // cause it to be modified for this operation.
3874   if (N->getOpcode() == ISD::SRA) {
3875     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3876     if (BinOpRHSSignSet != HighBitSet)
3877       return SDValue();
3878   }
3879
3880   if (!TLI.isDesirableToCommuteWithShift(LHS))
3881     return SDValue();
3882
3883   // Fold the constants, shifting the binop RHS by the shift amount.
3884   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3885                                N->getValueType(0),
3886                                LHS->getOperand(1), N->getOperand(1));
3887   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3888
3889   // Create the new shift.
3890   SDValue NewShift = DAG.getNode(N->getOpcode(),
3891                                  SDLoc(LHS->getOperand(0)),
3892                                  VT, LHS->getOperand(0), N->getOperand(1));
3893
3894   // Create the new binop.
3895   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3896 }
3897
3898 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3899   assert(N->getOpcode() == ISD::TRUNCATE);
3900   assert(N->getOperand(0).getOpcode() == ISD::AND);
3901
3902   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3903   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3904     SDValue N01 = N->getOperand(0).getOperand(1);
3905
3906     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3907       EVT TruncVT = N->getValueType(0);
3908       SDValue N00 = N->getOperand(0).getOperand(0);
3909       APInt TruncC = N01C->getAPIntValue();
3910       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3911
3912       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3913                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3914                          DAG.getConstant(TruncC, TruncVT));
3915     }
3916   }
3917
3918   return SDValue();
3919 }
3920
3921 SDValue DAGCombiner::visitRotate(SDNode *N) {
3922   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3923   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3924       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3925     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3926     if (NewOp1.getNode())
3927       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3928                          N->getOperand(0), NewOp1);
3929   }
3930   return SDValue();
3931 }
3932
3933 SDValue DAGCombiner::visitSHL(SDNode *N) {
3934   SDValue N0 = N->getOperand(0);
3935   SDValue N1 = N->getOperand(1);
3936   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3937   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3938   EVT VT = N0.getValueType();
3939   unsigned OpSizeInBits = VT.getScalarSizeInBits();
3940
3941   // fold vector ops
3942   if (VT.isVector()) {
3943     SDValue FoldedVOp = SimplifyVBinOp(N);
3944     if (FoldedVOp.getNode()) return FoldedVOp;
3945
3946     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3947     // If setcc produces all-one true value then:
3948     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3949     if (N1CV && N1CV->isConstant()) {
3950       if (N0.getOpcode() == ISD::AND &&
3951           TLI.getBooleanContents(true) ==
3952           TargetLowering::ZeroOrNegativeOneBooleanContent) {
3953         SDValue N00 = N0->getOperand(0);
3954         SDValue N01 = N0->getOperand(1);
3955         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3956
3957         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3958           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3959           if (C.getNode())
3960             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3961         }
3962       } else {
3963         N1C = isConstOrConstSplat(N1);
3964       }
3965     }
3966   }
3967
3968   // fold (shl c1, c2) -> c1<<c2
3969   if (N0C && N1C)
3970     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3971   // fold (shl 0, x) -> 0
3972   if (N0C && N0C->isNullValue())
3973     return N0;
3974   // fold (shl x, c >= size(x)) -> undef
3975   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3976     return DAG.getUNDEF(VT);
3977   // fold (shl x, 0) -> x
3978   if (N1C && N1C->isNullValue())
3979     return N0;
3980   // fold (shl undef, x) -> 0
3981   if (N0.getOpcode() == ISD::UNDEF)
3982     return DAG.getConstant(0, VT);
3983   // if (shl x, c) is known to be zero, return 0
3984   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3985                             APInt::getAllOnesValue(OpSizeInBits)))
3986     return DAG.getConstant(0, VT);
3987   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3988   if (N1.getOpcode() == ISD::TRUNCATE &&
3989       N1.getOperand(0).getOpcode() == ISD::AND) {
3990     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3991     if (NewOp1.getNode())
3992       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
3993   }
3994
3995   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3996     return SDValue(N, 0);
3997
3998   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3999   if (N1C && N0.getOpcode() == ISD::SHL) {
4000     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4001       uint64_t c1 = N0C1->getZExtValue();
4002       uint64_t c2 = N1C->getZExtValue();
4003       if (c1 + c2 >= OpSizeInBits)
4004         return DAG.getConstant(0, VT);
4005       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4006                          DAG.getConstant(c1 + c2, N1.getValueType()));
4007     }
4008   }
4009
4010   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4011   // For this to be valid, the second form must not preserve any of the bits
4012   // that are shifted out by the inner shift in the first form.  This means
4013   // the outer shift size must be >= the number of bits added by the ext.
4014   // As a corollary, we don't care what kind of ext it is.
4015   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4016               N0.getOpcode() == ISD::ANY_EXTEND ||
4017               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4018       N0.getOperand(0).getOpcode() == ISD::SHL) {
4019     SDValue N0Op0 = N0.getOperand(0);
4020     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4021       uint64_t c1 = N0Op0C1->getZExtValue();
4022       uint64_t c2 = N1C->getZExtValue();
4023       EVT InnerShiftVT = N0Op0.getValueType();
4024       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4025       if (c2 >= OpSizeInBits - InnerShiftSize) {
4026         if (c1 + c2 >= OpSizeInBits)
4027           return DAG.getConstant(0, VT);
4028         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4029                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4030                                        N0Op0->getOperand(0)),
4031                            DAG.getConstant(c1 + c2, N1.getValueType()));
4032       }
4033     }
4034   }
4035
4036   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4037   // Only fold this if the inner zext has no other uses to avoid increasing
4038   // the total number of instructions.
4039   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4040       N0.getOperand(0).getOpcode() == ISD::SRL) {
4041     SDValue N0Op0 = N0.getOperand(0);
4042     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4043       uint64_t c1 = N0Op0C1->getZExtValue();
4044       if (c1 < VT.getScalarSizeInBits()) {
4045         uint64_t c2 = N1C->getZExtValue();
4046         if (c1 == c2) {
4047           SDValue NewOp0 = N0.getOperand(0);
4048           EVT CountVT = NewOp0.getOperand(1).getValueType();
4049           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4050                                        NewOp0, DAG.getConstant(c2, CountVT));
4051           AddToWorkList(NewSHL.getNode());
4052           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4053         }
4054       }
4055     }
4056   }
4057
4058   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4059   //                               (and (srl x, (sub c1, c2), MASK)
4060   // Only fold this if the inner shift has no other uses -- if it does, folding
4061   // this will increase the total number of instructions.
4062   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4063     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4064       uint64_t c1 = N0C1->getZExtValue();
4065       if (c1 < OpSizeInBits) {
4066         uint64_t c2 = N1C->getZExtValue();
4067         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4068         SDValue Shift;
4069         if (c2 > c1) {
4070           Mask = Mask.shl(c2 - c1);
4071           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4072                               DAG.getConstant(c2 - c1, N1.getValueType()));
4073         } else {
4074           Mask = Mask.lshr(c1 - c2);
4075           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4076                               DAG.getConstant(c1 - c2, N1.getValueType()));
4077         }
4078         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4079                            DAG.getConstant(Mask, VT));
4080       }
4081     }
4082   }
4083   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4084   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4085     unsigned BitSize = VT.getScalarSizeInBits();
4086     SDValue HiBitsMask =
4087       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4088                                             BitSize - N1C->getZExtValue()), VT);
4089     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4090                        HiBitsMask);
4091   }
4092
4093   if (N1C) {
4094     SDValue NewSHL = visitShiftByConstant(N, N1C);
4095     if (NewSHL.getNode())
4096       return NewSHL;
4097   }
4098
4099   return SDValue();
4100 }
4101
4102 SDValue DAGCombiner::visitSRA(SDNode *N) {
4103   SDValue N0 = N->getOperand(0);
4104   SDValue N1 = N->getOperand(1);
4105   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4106   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4107   EVT VT = N0.getValueType();
4108   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4109
4110   // fold vector ops
4111   if (VT.isVector()) {
4112     SDValue FoldedVOp = SimplifyVBinOp(N);
4113     if (FoldedVOp.getNode()) return FoldedVOp;
4114
4115     N1C = isConstOrConstSplat(N1);
4116   }
4117
4118   // fold (sra c1, c2) -> (sra c1, c2)
4119   if (N0C && N1C)
4120     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4121   // fold (sra 0, x) -> 0
4122   if (N0C && N0C->isNullValue())
4123     return N0;
4124   // fold (sra -1, x) -> -1
4125   if (N0C && N0C->isAllOnesValue())
4126     return N0;
4127   // fold (sra x, (setge c, size(x))) -> undef
4128   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4129     return DAG.getUNDEF(VT);
4130   // fold (sra x, 0) -> x
4131   if (N1C && N1C->isNullValue())
4132     return N0;
4133   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4134   // sext_inreg.
4135   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4136     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4137     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4138     if (VT.isVector())
4139       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4140                                ExtVT, VT.getVectorNumElements());
4141     if ((!LegalOperations ||
4142          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4143       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4144                          N0.getOperand(0), DAG.getValueType(ExtVT));
4145   }
4146
4147   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4148   if (N1C && N0.getOpcode() == ISD::SRA) {
4149     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4150       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4151       if (Sum >= OpSizeInBits)
4152         Sum = OpSizeInBits - 1;
4153       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4154                          DAG.getConstant(Sum, N1.getValueType()));
4155     }
4156   }
4157
4158   // fold (sra (shl X, m), (sub result_size, n))
4159   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4160   // result_size - n != m.
4161   // If truncate is free for the target sext(shl) is likely to result in better
4162   // code.
4163   if (N0.getOpcode() == ISD::SHL && N1C) {
4164     // Get the two constanst of the shifts, CN0 = m, CN = n.
4165     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4166     if (N01C) {
4167       LLVMContext &Ctx = *DAG.getContext();
4168       // Determine what the truncate's result bitsize and type would be.
4169       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4170
4171       if (VT.isVector())
4172         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4173
4174       // Determine the residual right-shift amount.
4175       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4176
4177       // If the shift is not a no-op (in which case this should be just a sign
4178       // extend already), the truncated to type is legal, sign_extend is legal
4179       // on that type, and the truncate to that type is both legal and free,
4180       // perform the transform.
4181       if ((ShiftAmt > 0) &&
4182           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4183           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4184           TLI.isTruncateFree(VT, TruncVT)) {
4185
4186           SDValue Amt = DAG.getConstant(ShiftAmt,
4187               getShiftAmountTy(N0.getOperand(0).getValueType()));
4188           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4189                                       N0.getOperand(0), Amt);
4190           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4191                                       Shift);
4192           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4193                              N->getValueType(0), Trunc);
4194       }
4195     }
4196   }
4197
4198   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4199   if (N1.getOpcode() == ISD::TRUNCATE &&
4200       N1.getOperand(0).getOpcode() == ISD::AND) {
4201     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4202     if (NewOp1.getNode())
4203       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4204   }
4205
4206   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4207   //      if c1 is equal to the number of bits the trunc removes
4208   if (N0.getOpcode() == ISD::TRUNCATE &&
4209       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4210        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4211       N0.getOperand(0).hasOneUse() &&
4212       N0.getOperand(0).getOperand(1).hasOneUse() &&
4213       N1C) {
4214     SDValue N0Op0 = N0.getOperand(0);
4215     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4216       unsigned LargeShiftVal = LargeShift->getZExtValue();
4217       EVT LargeVT = N0Op0.getValueType();
4218
4219       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4220         SDValue Amt =
4221           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4222                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4223         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4224                                   N0Op0.getOperand(0), Amt);
4225         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4226       }
4227     }
4228   }
4229
4230   // Simplify, based on bits shifted out of the LHS.
4231   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4232     return SDValue(N, 0);
4233
4234
4235   // If the sign bit is known to be zero, switch this to a SRL.
4236   if (DAG.SignBitIsZero(N0))
4237     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4238
4239   if (N1C) {
4240     SDValue NewSRA = visitShiftByConstant(N, N1C);
4241     if (NewSRA.getNode())
4242       return NewSRA;
4243   }
4244
4245   return SDValue();
4246 }
4247
4248 SDValue DAGCombiner::visitSRL(SDNode *N) {
4249   SDValue N0 = N->getOperand(0);
4250   SDValue N1 = N->getOperand(1);
4251   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4252   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4253   EVT VT = N0.getValueType();
4254   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4255
4256   // fold vector ops
4257   if (VT.isVector()) {
4258     SDValue FoldedVOp = SimplifyVBinOp(N);
4259     if (FoldedVOp.getNode()) return FoldedVOp;
4260
4261     N1C = isConstOrConstSplat(N1);
4262   }
4263
4264   // fold (srl c1, c2) -> c1 >>u c2
4265   if (N0C && N1C)
4266     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4267   // fold (srl 0, x) -> 0
4268   if (N0C && N0C->isNullValue())
4269     return N0;
4270   // fold (srl x, c >= size(x)) -> undef
4271   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4272     return DAG.getUNDEF(VT);
4273   // fold (srl x, 0) -> x
4274   if (N1C && N1C->isNullValue())
4275     return N0;
4276   // if (srl x, c) is known to be zero, return 0
4277   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4278                                    APInt::getAllOnesValue(OpSizeInBits)))
4279     return DAG.getConstant(0, VT);
4280
4281   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4282   if (N1C && N0.getOpcode() == ISD::SRL) {
4283     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4284       uint64_t c1 = N01C->getZExtValue();
4285       uint64_t c2 = N1C->getZExtValue();
4286       if (c1 + c2 >= OpSizeInBits)
4287         return DAG.getConstant(0, VT);
4288       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4289                          DAG.getConstant(c1 + c2, N1.getValueType()));
4290     }
4291   }
4292
4293   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4294   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4295       N0.getOperand(0).getOpcode() == ISD::SRL &&
4296       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4297     uint64_t c1 =
4298       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4299     uint64_t c2 = N1C->getZExtValue();
4300     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4301     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4302     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4303     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4304     if (c1 + OpSizeInBits == InnerShiftSize) {
4305       if (c1 + c2 >= InnerShiftSize)
4306         return DAG.getConstant(0, VT);
4307       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4308                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4309                                      N0.getOperand(0)->getOperand(0),
4310                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4311     }
4312   }
4313
4314   // fold (srl (shl x, c), c) -> (and x, cst2)
4315   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4316     unsigned BitSize = N0.getScalarValueSizeInBits();
4317     if (BitSize <= 64) {
4318       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4319       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4320                          DAG.getConstant(~0ULL >> ShAmt, VT));
4321     }
4322   }
4323
4324   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4325   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4326     // Shifting in all undef bits?
4327     EVT SmallVT = N0.getOperand(0).getValueType();
4328     unsigned BitSize = SmallVT.getScalarSizeInBits();
4329     if (N1C->getZExtValue() >= BitSize)
4330       return DAG.getUNDEF(VT);
4331
4332     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4333       uint64_t ShiftAmt = N1C->getZExtValue();
4334       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4335                                        N0.getOperand(0),
4336                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4337       AddToWorkList(SmallShift.getNode());
4338       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4339       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4340                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4341                          DAG.getConstant(Mask, VT));
4342     }
4343   }
4344
4345   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4346   // bit, which is unmodified by sra.
4347   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4348     if (N0.getOpcode() == ISD::SRA)
4349       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4350   }
4351
4352   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4353   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4354       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4355     APInt KnownZero, KnownOne;
4356     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4357
4358     // If any of the input bits are KnownOne, then the input couldn't be all
4359     // zeros, thus the result of the srl will always be zero.
4360     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4361
4362     // If all of the bits input the to ctlz node are known to be zero, then
4363     // the result of the ctlz is "32" and the result of the shift is one.
4364     APInt UnknownBits = ~KnownZero;
4365     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4366
4367     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4368     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4369       // Okay, we know that only that the single bit specified by UnknownBits
4370       // could be set on input to the CTLZ node. If this bit is set, the SRL
4371       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4372       // to an SRL/XOR pair, which is likely to simplify more.
4373       unsigned ShAmt = UnknownBits.countTrailingZeros();
4374       SDValue Op = N0.getOperand(0);
4375
4376       if (ShAmt) {
4377         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4378                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4379         AddToWorkList(Op.getNode());
4380       }
4381
4382       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4383                          Op, DAG.getConstant(1, VT));
4384     }
4385   }
4386
4387   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4388   if (N1.getOpcode() == ISD::TRUNCATE &&
4389       N1.getOperand(0).getOpcode() == ISD::AND) {
4390     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4391     if (NewOp1.getNode())
4392       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4393   }
4394
4395   // fold operands of srl based on knowledge that the low bits are not
4396   // demanded.
4397   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4398     return SDValue(N, 0);
4399
4400   if (N1C) {
4401     SDValue NewSRL = visitShiftByConstant(N, N1C);
4402     if (NewSRL.getNode())
4403       return NewSRL;
4404   }
4405
4406   // Attempt to convert a srl of a load into a narrower zero-extending load.
4407   SDValue NarrowLoad = ReduceLoadWidth(N);
4408   if (NarrowLoad.getNode())
4409     return NarrowLoad;
4410
4411   // Here is a common situation. We want to optimize:
4412   //
4413   //   %a = ...
4414   //   %b = and i32 %a, 2
4415   //   %c = srl i32 %b, 1
4416   //   brcond i32 %c ...
4417   //
4418   // into
4419   //
4420   //   %a = ...
4421   //   %b = and %a, 2
4422   //   %c = setcc eq %b, 0
4423   //   brcond %c ...
4424   //
4425   // However when after the source operand of SRL is optimized into AND, the SRL
4426   // itself may not be optimized further. Look for it and add the BRCOND into
4427   // the worklist.
4428   if (N->hasOneUse()) {
4429     SDNode *Use = *N->use_begin();
4430     if (Use->getOpcode() == ISD::BRCOND)
4431       AddToWorkList(Use);
4432     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4433       // Also look pass the truncate.
4434       Use = *Use->use_begin();
4435       if (Use->getOpcode() == ISD::BRCOND)
4436         AddToWorkList(Use);
4437     }
4438   }
4439
4440   return SDValue();
4441 }
4442
4443 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4444   SDValue N0 = N->getOperand(0);
4445   EVT VT = N->getValueType(0);
4446
4447   // fold (ctlz c1) -> c2
4448   if (isa<ConstantSDNode>(N0))
4449     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4450   return SDValue();
4451 }
4452
4453 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4454   SDValue N0 = N->getOperand(0);
4455   EVT VT = N->getValueType(0);
4456
4457   // fold (ctlz_zero_undef c1) -> c2
4458   if (isa<ConstantSDNode>(N0))
4459     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4460   return SDValue();
4461 }
4462
4463 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4464   SDValue N0 = N->getOperand(0);
4465   EVT VT = N->getValueType(0);
4466
4467   // fold (cttz c1) -> c2
4468   if (isa<ConstantSDNode>(N0))
4469     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4470   return SDValue();
4471 }
4472
4473 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4474   SDValue N0 = N->getOperand(0);
4475   EVT VT = N->getValueType(0);
4476
4477   // fold (cttz_zero_undef c1) -> c2
4478   if (isa<ConstantSDNode>(N0))
4479     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4480   return SDValue();
4481 }
4482
4483 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4484   SDValue N0 = N->getOperand(0);
4485   EVT VT = N->getValueType(0);
4486
4487   // fold (ctpop c1) -> c2
4488   if (isa<ConstantSDNode>(N0))
4489     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4490   return SDValue();
4491 }
4492
4493 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4494   SDValue N0 = N->getOperand(0);
4495   SDValue N1 = N->getOperand(1);
4496   SDValue N2 = N->getOperand(2);
4497   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4498   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4499   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4500   EVT VT = N->getValueType(0);
4501   EVT VT0 = N0.getValueType();
4502
4503   // fold (select C, X, X) -> X
4504   if (N1 == N2)
4505     return N1;
4506   // fold (select true, X, Y) -> X
4507   if (N0C && !N0C->isNullValue())
4508     return N1;
4509   // fold (select false, X, Y) -> Y
4510   if (N0C && N0C->isNullValue())
4511     return N2;
4512   // fold (select C, 1, X) -> (or C, X)
4513   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4514     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4515   // fold (select C, 0, 1) -> (xor C, 1)
4516   if (VT.isInteger() &&
4517       (VT0 == MVT::i1 ||
4518        (VT0.isInteger() &&
4519         TLI.getBooleanContents(false) ==
4520         TargetLowering::ZeroOrOneBooleanContent)) &&
4521       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4522     SDValue XORNode;
4523     if (VT == VT0)
4524       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4525                          N0, DAG.getConstant(1, VT0));
4526     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4527                           N0, DAG.getConstant(1, VT0));
4528     AddToWorkList(XORNode.getNode());
4529     if (VT.bitsGT(VT0))
4530       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4531     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4532   }
4533   // fold (select C, 0, X) -> (and (not C), X)
4534   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4535     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4536     AddToWorkList(NOTNode.getNode());
4537     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4538   }
4539   // fold (select C, X, 1) -> (or (not C), X)
4540   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4541     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4542     AddToWorkList(NOTNode.getNode());
4543     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4544   }
4545   // fold (select C, X, 0) -> (and C, X)
4546   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4547     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4548   // fold (select X, X, Y) -> (or X, Y)
4549   // fold (select X, 1, Y) -> (or X, Y)
4550   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4551     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4552   // fold (select X, Y, X) -> (and X, Y)
4553   // fold (select X, Y, 0) -> (and X, Y)
4554   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4555     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4556
4557   // If we can fold this based on the true/false value, do so.
4558   if (SimplifySelectOps(N, N1, N2))
4559     return SDValue(N, 0);  // Don't revisit N.
4560
4561   // fold selects based on a setcc into other things, such as min/max/abs
4562   if (N0.getOpcode() == ISD::SETCC) {
4563     // FIXME:
4564     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4565     // having to say they don't support SELECT_CC on every type the DAG knows
4566     // about, since there is no way to mark an opcode illegal at all value types
4567     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4568         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4569       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4570                          N0.getOperand(0), N0.getOperand(1),
4571                          N1, N2, N0.getOperand(2));
4572     return SimplifySelect(SDLoc(N), N0, N1, N2);
4573   }
4574
4575   return SDValue();
4576 }
4577
4578 static
4579 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4580   SDLoc DL(N);
4581   EVT LoVT, HiVT;
4582   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4583
4584   // Split the inputs.
4585   SDValue Lo, Hi, LL, LH, RL, RH;
4586   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4587   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4588
4589   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4590   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4591
4592   return std::make_pair(Lo, Hi);
4593 }
4594
4595 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4596 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4597 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4598   SDLoc dl(N);
4599   SDValue Cond = N->getOperand(0);
4600   SDValue LHS = N->getOperand(1);
4601   SDValue RHS = N->getOperand(2);
4602   MVT VT = N->getSimpleValueType(0);
4603   int NumElems = VT.getVectorNumElements();
4604   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4605          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4606          Cond.getOpcode() == ISD::BUILD_VECTOR);
4607
4608   // We're sure we have an even number of elements due to the
4609   // concat_vectors we have as arguments to vselect.
4610   // Skip BV elements until we find one that's not an UNDEF
4611   // After we find an UNDEF element, keep looping until we get to half the
4612   // length of the BV and see if all the non-undef nodes are the same.
4613   ConstantSDNode *BottomHalf = nullptr;
4614   for (int i = 0; i < NumElems / 2; ++i) {
4615     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4616       continue;
4617
4618     if (BottomHalf == nullptr)
4619       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4620     else if (Cond->getOperand(i).getNode() != BottomHalf)
4621       return SDValue();
4622   }
4623
4624   // Do the same for the second half of the BuildVector
4625   ConstantSDNode *TopHalf = nullptr;
4626   for (int i = NumElems / 2; i < NumElems; ++i) {
4627     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4628       continue;
4629
4630     if (TopHalf == nullptr)
4631       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4632     else if (Cond->getOperand(i).getNode() != TopHalf)
4633       return SDValue();
4634   }
4635
4636   assert(TopHalf && BottomHalf &&
4637          "One half of the selector was all UNDEFs and the other was all the "
4638          "same value. This should have been addressed before this function.");
4639   return DAG.getNode(
4640       ISD::CONCAT_VECTORS, dl, VT,
4641       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4642       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4643 }
4644
4645 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4646   SDValue N0 = N->getOperand(0);
4647   SDValue N1 = N->getOperand(1);
4648   SDValue N2 = N->getOperand(2);
4649   SDLoc DL(N);
4650
4651   // Canonicalize integer abs.
4652   // vselect (setg[te] X,  0),  X, -X ->
4653   // vselect (setgt    X, -1),  X, -X ->
4654   // vselect (setl[te] X,  0), -X,  X ->
4655   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4656   if (N0.getOpcode() == ISD::SETCC) {
4657     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4658     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4659     bool isAbs = false;
4660     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4661
4662     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4663          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4664         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4665       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4666     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4667              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4668       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4669
4670     if (isAbs) {
4671       EVT VT = LHS.getValueType();
4672       SDValue Shift = DAG.getNode(
4673           ISD::SRA, DL, VT, LHS,
4674           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4675       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4676       AddToWorkList(Shift.getNode());
4677       AddToWorkList(Add.getNode());
4678       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4679     }
4680   }
4681
4682   // If the VSELECT result requires splitting and the mask is provided by a
4683   // SETCC, then split both nodes and its operands before legalization. This
4684   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4685   // and enables future optimizations (e.g. min/max pattern matching on X86).
4686   if (N0.getOpcode() == ISD::SETCC) {
4687     EVT VT = N->getValueType(0);
4688
4689     // Check if any splitting is required.
4690     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4691         TargetLowering::TypeSplitVector)
4692       return SDValue();
4693
4694     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4695     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4696     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4697     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4698
4699     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4700     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4701
4702     // Add the new VSELECT nodes to the work list in case they need to be split
4703     // again.
4704     AddToWorkList(Lo.getNode());
4705     AddToWorkList(Hi.getNode());
4706
4707     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4708   }
4709
4710   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4711   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4712     return N1;
4713   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4714   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4715     return N2;
4716
4717   // The ConvertSelectToConcatVector function is assuming both the above
4718   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4719   // and addressed.
4720   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4721       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4722       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4723     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4724     if (CV.getNode())
4725       return CV;
4726   }
4727
4728   return SDValue();
4729 }
4730
4731 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4732   SDValue N0 = N->getOperand(0);
4733   SDValue N1 = N->getOperand(1);
4734   SDValue N2 = N->getOperand(2);
4735   SDValue N3 = N->getOperand(3);
4736   SDValue N4 = N->getOperand(4);
4737   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4738
4739   // fold select_cc lhs, rhs, x, x, cc -> x
4740   if (N2 == N3)
4741     return N2;
4742
4743   // Determine if the condition we're dealing with is constant
4744   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4745                               N0, N1, CC, SDLoc(N), false);
4746   if (SCC.getNode()) {
4747     AddToWorkList(SCC.getNode());
4748
4749     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4750       if (!SCCC->isNullValue())
4751         return N2;    // cond always true -> true val
4752       else
4753         return N3;    // cond always false -> false val
4754     }
4755
4756     // Fold to a simpler select_cc
4757     if (SCC.getOpcode() == ISD::SETCC)
4758       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4759                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4760                          SCC.getOperand(2));
4761   }
4762
4763   // If we can fold this based on the true/false value, do so.
4764   if (SimplifySelectOps(N, N2, N3))
4765     return SDValue(N, 0);  // Don't revisit N.
4766
4767   // fold select_cc into other things, such as min/max/abs
4768   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4769 }
4770
4771 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4772   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4773                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4774                        SDLoc(N));
4775 }
4776
4777 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4778 // dag node into a ConstantSDNode or a build_vector of constants.
4779 // This function is called by the DAGCombiner when visiting sext/zext/aext
4780 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4781 // Vector extends are not folded if operations are legal; this is to
4782 // avoid introducing illegal build_vector dag nodes.
4783 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4784                                          SelectionDAG &DAG, bool LegalTypes,
4785                                          bool LegalOperations) {
4786   unsigned Opcode = N->getOpcode();
4787   SDValue N0 = N->getOperand(0);
4788   EVT VT = N->getValueType(0);
4789
4790   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4791          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4792
4793   // fold (sext c1) -> c1
4794   // fold (zext c1) -> c1
4795   // fold (aext c1) -> c1
4796   if (isa<ConstantSDNode>(N0))
4797     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4798
4799   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4800   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4801   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4802   EVT SVT = VT.getScalarType();
4803   if (!(VT.isVector() &&
4804       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4805       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4806     return nullptr;
4807
4808   // We can fold this node into a build_vector.
4809   unsigned VTBits = SVT.getSizeInBits();
4810   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4811   unsigned ShAmt = VTBits - EVTBits;
4812   SmallVector<SDValue, 8> Elts;
4813   unsigned NumElts = N0->getNumOperands();
4814   SDLoc DL(N);
4815
4816   for (unsigned i=0; i != NumElts; ++i) {
4817     SDValue Op = N0->getOperand(i);
4818     if (Op->getOpcode() == ISD::UNDEF) {
4819       Elts.push_back(DAG.getUNDEF(SVT));
4820       continue;
4821     }
4822
4823     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4824     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4825     if (Opcode == ISD::SIGN_EXTEND)
4826       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4827                                      SVT));
4828     else
4829       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4830                                      SVT));
4831   }
4832
4833   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4834 }
4835
4836 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4837 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4838 // transformation. Returns true if extension are possible and the above
4839 // mentioned transformation is profitable.
4840 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4841                                     unsigned ExtOpc,
4842                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4843                                     const TargetLowering &TLI) {
4844   bool HasCopyToRegUses = false;
4845   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4846   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4847                             UE = N0.getNode()->use_end();
4848        UI != UE; ++UI) {
4849     SDNode *User = *UI;
4850     if (User == N)
4851       continue;
4852     if (UI.getUse().getResNo() != N0.getResNo())
4853       continue;
4854     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4855     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4856       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4857       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4858         // Sign bits will be lost after a zext.
4859         return false;
4860       bool Add = false;
4861       for (unsigned i = 0; i != 2; ++i) {
4862         SDValue UseOp = User->getOperand(i);
4863         if (UseOp == N0)
4864           continue;
4865         if (!isa<ConstantSDNode>(UseOp))
4866           return false;
4867         Add = true;
4868       }
4869       if (Add)
4870         ExtendNodes.push_back(User);
4871       continue;
4872     }
4873     // If truncates aren't free and there are users we can't
4874     // extend, it isn't worthwhile.
4875     if (!isTruncFree)
4876       return false;
4877     // Remember if this value is live-out.
4878     if (User->getOpcode() == ISD::CopyToReg)
4879       HasCopyToRegUses = true;
4880   }
4881
4882   if (HasCopyToRegUses) {
4883     bool BothLiveOut = false;
4884     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4885          UI != UE; ++UI) {
4886       SDUse &Use = UI.getUse();
4887       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4888         BothLiveOut = true;
4889         break;
4890       }
4891     }
4892     if (BothLiveOut)
4893       // Both unextended and extended values are live out. There had better be
4894       // a good reason for the transformation.
4895       return ExtendNodes.size();
4896   }
4897   return true;
4898 }
4899
4900 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4901                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4902                                   ISD::NodeType ExtType) {
4903   // Extend SetCC uses if necessary.
4904   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4905     SDNode *SetCC = SetCCs[i];
4906     SmallVector<SDValue, 4> Ops;
4907
4908     for (unsigned j = 0; j != 2; ++j) {
4909       SDValue SOp = SetCC->getOperand(j);
4910       if (SOp == Trunc)
4911         Ops.push_back(ExtLoad);
4912       else
4913         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4914     }
4915
4916     Ops.push_back(SetCC->getOperand(2));
4917     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4918   }
4919 }
4920
4921 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4922   SDValue N0 = N->getOperand(0);
4923   EVT VT = N->getValueType(0);
4924
4925   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4926                                               LegalOperations))
4927     return SDValue(Res, 0);
4928
4929   // fold (sext (sext x)) -> (sext x)
4930   // fold (sext (aext x)) -> (sext x)
4931   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4932     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4933                        N0.getOperand(0));
4934
4935   if (N0.getOpcode() == ISD::TRUNCATE) {
4936     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4937     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4938     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4939     if (NarrowLoad.getNode()) {
4940       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4941       if (NarrowLoad.getNode() != N0.getNode()) {
4942         CombineTo(N0.getNode(), NarrowLoad);
4943         // CombineTo deleted the truncate, if needed, but not what's under it.
4944         AddToWorkList(oye);
4945       }
4946       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4947     }
4948
4949     // See if the value being truncated is already sign extended.  If so, just
4950     // eliminate the trunc/sext pair.
4951     SDValue Op = N0.getOperand(0);
4952     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4953     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4954     unsigned DestBits = VT.getScalarType().getSizeInBits();
4955     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4956
4957     if (OpBits == DestBits) {
4958       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4959       // bits, it is already ready.
4960       if (NumSignBits > DestBits-MidBits)
4961         return Op;
4962     } else if (OpBits < DestBits) {
4963       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4964       // bits, just sext from i32.
4965       if (NumSignBits > OpBits-MidBits)
4966         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4967     } else {
4968       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4969       // bits, just truncate to i32.
4970       if (NumSignBits > OpBits-MidBits)
4971         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4972     }
4973
4974     // fold (sext (truncate x)) -> (sextinreg x).
4975     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4976                                                  N0.getValueType())) {
4977       if (OpBits < DestBits)
4978         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4979       else if (OpBits > DestBits)
4980         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4981       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4982                          DAG.getValueType(N0.getValueType()));
4983     }
4984   }
4985
4986   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4987   // None of the supported targets knows how to perform load and sign extend
4988   // on vectors in one instruction.  We only perform this transformation on
4989   // scalars.
4990   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4991       ISD::isUNINDEXEDLoad(N0.getNode()) &&
4992       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4993        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4994     bool DoXform = true;
4995     SmallVector<SDNode*, 4> SetCCs;
4996     if (!N0.hasOneUse())
4997       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4998     if (DoXform) {
4999       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5000       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5001                                        LN0->getChain(),
5002                                        LN0->getBasePtr(), N0.getValueType(),
5003                                        LN0->getMemOperand());
5004       CombineTo(N, ExtLoad);
5005       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5006                                   N0.getValueType(), ExtLoad);
5007       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5008       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5009                       ISD::SIGN_EXTEND);
5010       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5011     }
5012   }
5013
5014   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5015   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5016   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5017       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5018     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5019     EVT MemVT = LN0->getMemoryVT();
5020     if ((!LegalOperations && !LN0->isVolatile()) ||
5021         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5022       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5023                                        LN0->getChain(),
5024                                        LN0->getBasePtr(), MemVT,
5025                                        LN0->getMemOperand());
5026       CombineTo(N, ExtLoad);
5027       CombineTo(N0.getNode(),
5028                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5029                             N0.getValueType(), ExtLoad),
5030                 ExtLoad.getValue(1));
5031       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5032     }
5033   }
5034
5035   // fold (sext (and/or/xor (load x), cst)) ->
5036   //      (and/or/xor (sextload x), (sext cst))
5037   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5038        N0.getOpcode() == ISD::XOR) &&
5039       isa<LoadSDNode>(N0.getOperand(0)) &&
5040       N0.getOperand(1).getOpcode() == ISD::Constant &&
5041       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5042       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5043     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5044     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5045       bool DoXform = true;
5046       SmallVector<SDNode*, 4> SetCCs;
5047       if (!N0.hasOneUse())
5048         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5049                                           SetCCs, TLI);
5050       if (DoXform) {
5051         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5052                                          LN0->getChain(), LN0->getBasePtr(),
5053                                          LN0->getMemoryVT(),
5054                                          LN0->getMemOperand());
5055         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5056         Mask = Mask.sext(VT.getSizeInBits());
5057         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5058                                   ExtLoad, DAG.getConstant(Mask, VT));
5059         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5060                                     SDLoc(N0.getOperand(0)),
5061                                     N0.getOperand(0).getValueType(), ExtLoad);
5062         CombineTo(N, And);
5063         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5064         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5065                         ISD::SIGN_EXTEND);
5066         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5067       }
5068     }
5069   }
5070
5071   if (N0.getOpcode() == ISD::SETCC) {
5072     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5073     // Only do this before legalize for now.
5074     if (VT.isVector() && !LegalOperations &&
5075         TLI.getBooleanContents(true) ==
5076           TargetLowering::ZeroOrNegativeOneBooleanContent) {
5077       EVT N0VT = N0.getOperand(0).getValueType();
5078       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5079       // of the same size as the compared operands. Only optimize sext(setcc())
5080       // if this is the case.
5081       EVT SVT = getSetCCResultType(N0VT);
5082
5083       // We know that the # elements of the results is the same as the
5084       // # elements of the compare (and the # elements of the compare result
5085       // for that matter).  Check to see that they are the same size.  If so,
5086       // we know that the element size of the sext'd result matches the
5087       // element size of the compare operands.
5088       if (VT.getSizeInBits() == SVT.getSizeInBits())
5089         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5090                              N0.getOperand(1),
5091                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5092
5093       // If the desired elements are smaller or larger than the source
5094       // elements we can use a matching integer vector type and then
5095       // truncate/sign extend
5096       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5097       if (SVT == MatchingVectorType) {
5098         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5099                                N0.getOperand(0), N0.getOperand(1),
5100                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5101         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5102       }
5103     }
5104
5105     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5106     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5107     SDValue NegOne =
5108       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5109     SDValue SCC =
5110       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5111                        NegOne, DAG.getConstant(0, VT),
5112                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5113     if (SCC.getNode()) return SCC;
5114
5115     if (!VT.isVector()) {
5116       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5117       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5118         SDLoc DL(N);
5119         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5120         SDValue SetCC = DAG.getSetCC(DL,
5121                                      SetCCVT,
5122                                      N0.getOperand(0), N0.getOperand(1), CC);
5123         EVT SelectVT = getSetCCResultType(VT);
5124         return DAG.getSelect(DL, VT,
5125                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5126                              NegOne, DAG.getConstant(0, VT));
5127
5128       }
5129     }
5130   }
5131
5132   // fold (sext x) -> (zext x) if the sign bit is known zero.
5133   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5134       DAG.SignBitIsZero(N0))
5135     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5136
5137   return SDValue();
5138 }
5139
5140 // isTruncateOf - If N is a truncate of some other value, return true, record
5141 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5142 // This function computes KnownZero to avoid a duplicated call to
5143 // computeKnownBits in the caller.
5144 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5145                          APInt &KnownZero) {
5146   APInt KnownOne;
5147   if (N->getOpcode() == ISD::TRUNCATE) {
5148     Op = N->getOperand(0);
5149     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5150     return true;
5151   }
5152
5153   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5154       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5155     return false;
5156
5157   SDValue Op0 = N->getOperand(0);
5158   SDValue Op1 = N->getOperand(1);
5159   assert(Op0.getValueType() == Op1.getValueType());
5160
5161   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5162   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5163   if (COp0 && COp0->isNullValue())
5164     Op = Op1;
5165   else if (COp1 && COp1->isNullValue())
5166     Op = Op0;
5167   else
5168     return false;
5169
5170   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5171
5172   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5173     return false;
5174
5175   return true;
5176 }
5177
5178 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5179   SDValue N0 = N->getOperand(0);
5180   EVT VT = N->getValueType(0);
5181
5182   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5183                                               LegalOperations))
5184     return SDValue(Res, 0);
5185
5186   // fold (zext (zext x)) -> (zext x)
5187   // fold (zext (aext x)) -> (zext x)
5188   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5189     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5190                        N0.getOperand(0));
5191
5192   // fold (zext (truncate x)) -> (zext x) or
5193   //      (zext (truncate x)) -> (truncate x)
5194   // This is valid when the truncated bits of x are already zero.
5195   // FIXME: We should extend this to work for vectors too.
5196   SDValue Op;
5197   APInt KnownZero;
5198   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5199     APInt TruncatedBits =
5200       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5201       APInt(Op.getValueSizeInBits(), 0) :
5202       APInt::getBitsSet(Op.getValueSizeInBits(),
5203                         N0.getValueSizeInBits(),
5204                         std::min(Op.getValueSizeInBits(),
5205                                  VT.getSizeInBits()));
5206     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5207       if (VT.bitsGT(Op.getValueType()))
5208         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5209       if (VT.bitsLT(Op.getValueType()))
5210         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5211
5212       return Op;
5213     }
5214   }
5215
5216   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5217   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5218   if (N0.getOpcode() == ISD::TRUNCATE) {
5219     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5220     if (NarrowLoad.getNode()) {
5221       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5222       if (NarrowLoad.getNode() != N0.getNode()) {
5223         CombineTo(N0.getNode(), NarrowLoad);
5224         // CombineTo deleted the truncate, if needed, but not what's under it.
5225         AddToWorkList(oye);
5226       }
5227       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5228     }
5229   }
5230
5231   // fold (zext (truncate x)) -> (and x, mask)
5232   if (N0.getOpcode() == ISD::TRUNCATE &&
5233       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5234
5235     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5236     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5237     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5238     if (NarrowLoad.getNode()) {
5239       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5240       if (NarrowLoad.getNode() != N0.getNode()) {
5241         CombineTo(N0.getNode(), NarrowLoad);
5242         // CombineTo deleted the truncate, if needed, but not what's under it.
5243         AddToWorkList(oye);
5244       }
5245       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5246     }
5247
5248     SDValue Op = N0.getOperand(0);
5249     if (Op.getValueType().bitsLT(VT)) {
5250       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5251       AddToWorkList(Op.getNode());
5252     } else if (Op.getValueType().bitsGT(VT)) {
5253       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5254       AddToWorkList(Op.getNode());
5255     }
5256     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5257                                   N0.getValueType().getScalarType());
5258   }
5259
5260   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5261   // if either of the casts is not free.
5262   if (N0.getOpcode() == ISD::AND &&
5263       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5264       N0.getOperand(1).getOpcode() == ISD::Constant &&
5265       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5266                            N0.getValueType()) ||
5267        !TLI.isZExtFree(N0.getValueType(), VT))) {
5268     SDValue X = N0.getOperand(0).getOperand(0);
5269     if (X.getValueType().bitsLT(VT)) {
5270       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5271     } else if (X.getValueType().bitsGT(VT)) {
5272       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5273     }
5274     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5275     Mask = Mask.zext(VT.getSizeInBits());
5276     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5277                        X, DAG.getConstant(Mask, VT));
5278   }
5279
5280   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5281   // None of the supported targets knows how to perform load and vector_zext
5282   // on vectors in one instruction.  We only perform this transformation on
5283   // scalars.
5284   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5285       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5286       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5287        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5288     bool DoXform = true;
5289     SmallVector<SDNode*, 4> SetCCs;
5290     if (!N0.hasOneUse())
5291       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5292     if (DoXform) {
5293       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5294       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5295                                        LN0->getChain(),
5296                                        LN0->getBasePtr(), N0.getValueType(),
5297                                        LN0->getMemOperand());
5298       CombineTo(N, ExtLoad);
5299       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5300                                   N0.getValueType(), ExtLoad);
5301       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5302
5303       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5304                       ISD::ZERO_EXTEND);
5305       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5306     }
5307   }
5308
5309   // fold (zext (and/or/xor (load x), cst)) ->
5310   //      (and/or/xor (zextload x), (zext cst))
5311   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5312        N0.getOpcode() == ISD::XOR) &&
5313       isa<LoadSDNode>(N0.getOperand(0)) &&
5314       N0.getOperand(1).getOpcode() == ISD::Constant &&
5315       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5316       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5317     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5318     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5319       bool DoXform = true;
5320       SmallVector<SDNode*, 4> SetCCs;
5321       if (!N0.hasOneUse())
5322         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5323                                           SetCCs, TLI);
5324       if (DoXform) {
5325         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5326                                          LN0->getChain(), LN0->getBasePtr(),
5327                                          LN0->getMemoryVT(),
5328                                          LN0->getMemOperand());
5329         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5330         Mask = Mask.zext(VT.getSizeInBits());
5331         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5332                                   ExtLoad, DAG.getConstant(Mask, VT));
5333         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5334                                     SDLoc(N0.getOperand(0)),
5335                                     N0.getOperand(0).getValueType(), ExtLoad);
5336         CombineTo(N, And);
5337         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5338         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5339                         ISD::ZERO_EXTEND);
5340         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5341       }
5342     }
5343   }
5344
5345   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5346   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5347   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5348       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5349     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5350     EVT MemVT = LN0->getMemoryVT();
5351     if ((!LegalOperations && !LN0->isVolatile()) ||
5352         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5353       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5354                                        LN0->getChain(),
5355                                        LN0->getBasePtr(), MemVT,
5356                                        LN0->getMemOperand());
5357       CombineTo(N, ExtLoad);
5358       CombineTo(N0.getNode(),
5359                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5360                             ExtLoad),
5361                 ExtLoad.getValue(1));
5362       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5363     }
5364   }
5365
5366   if (N0.getOpcode() == ISD::SETCC) {
5367     if (!LegalOperations && VT.isVector() &&
5368         N0.getValueType().getVectorElementType() == MVT::i1) {
5369       EVT N0VT = N0.getOperand(0).getValueType();
5370       if (getSetCCResultType(N0VT) == N0.getValueType())
5371         return SDValue();
5372
5373       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5374       // Only do this before legalize for now.
5375       EVT EltVT = VT.getVectorElementType();
5376       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5377                                     DAG.getConstant(1, EltVT));
5378       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5379         // We know that the # elements of the results is the same as the
5380         // # elements of the compare (and the # elements of the compare result
5381         // for that matter).  Check to see that they are the same size.  If so,
5382         // we know that the element size of the sext'd result matches the
5383         // element size of the compare operands.
5384         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5385                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5386                                          N0.getOperand(1),
5387                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5388                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5389                                        OneOps));
5390
5391       // If the desired elements are smaller or larger than the source
5392       // elements we can use a matching integer vector type and then
5393       // truncate/sign extend
5394       EVT MatchingElementType =
5395         EVT::getIntegerVT(*DAG.getContext(),
5396                           N0VT.getScalarType().getSizeInBits());
5397       EVT MatchingVectorType =
5398         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5399                          N0VT.getVectorNumElements());
5400       SDValue VsetCC =
5401         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5402                       N0.getOperand(1),
5403                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5404       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5405                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5406                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5407     }
5408
5409     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5410     SDValue SCC =
5411       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5412                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5413                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5414     if (SCC.getNode()) return SCC;
5415   }
5416
5417   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5418   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5419       isa<ConstantSDNode>(N0.getOperand(1)) &&
5420       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5421       N0.hasOneUse()) {
5422     SDValue ShAmt = N0.getOperand(1);
5423     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5424     if (N0.getOpcode() == ISD::SHL) {
5425       SDValue InnerZExt = N0.getOperand(0);
5426       // If the original shl may be shifting out bits, do not perform this
5427       // transformation.
5428       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5429         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5430       if (ShAmtVal > KnownZeroBits)
5431         return SDValue();
5432     }
5433
5434     SDLoc DL(N);
5435
5436     // Ensure that the shift amount is wide enough for the shifted value.
5437     if (VT.getSizeInBits() >= 256)
5438       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5439
5440     return DAG.getNode(N0.getOpcode(), DL, VT,
5441                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5442                        ShAmt);
5443   }
5444
5445   return SDValue();
5446 }
5447
5448 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5449   SDValue N0 = N->getOperand(0);
5450   EVT VT = N->getValueType(0);
5451
5452   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5453                                               LegalOperations))
5454     return SDValue(Res, 0);
5455
5456   // fold (aext (aext x)) -> (aext x)
5457   // fold (aext (zext x)) -> (zext x)
5458   // fold (aext (sext x)) -> (sext x)
5459   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5460       N0.getOpcode() == ISD::ZERO_EXTEND ||
5461       N0.getOpcode() == ISD::SIGN_EXTEND)
5462     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5463
5464   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5465   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5466   if (N0.getOpcode() == ISD::TRUNCATE) {
5467     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5468     if (NarrowLoad.getNode()) {
5469       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5470       if (NarrowLoad.getNode() != N0.getNode()) {
5471         CombineTo(N0.getNode(), NarrowLoad);
5472         // CombineTo deleted the truncate, if needed, but not what's under it.
5473         AddToWorkList(oye);
5474       }
5475       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5476     }
5477   }
5478
5479   // fold (aext (truncate x))
5480   if (N0.getOpcode() == ISD::TRUNCATE) {
5481     SDValue TruncOp = N0.getOperand(0);
5482     if (TruncOp.getValueType() == VT)
5483       return TruncOp; // x iff x size == zext size.
5484     if (TruncOp.getValueType().bitsGT(VT))
5485       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5486     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5487   }
5488
5489   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5490   // if the trunc is not free.
5491   if (N0.getOpcode() == ISD::AND &&
5492       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5493       N0.getOperand(1).getOpcode() == ISD::Constant &&
5494       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5495                           N0.getValueType())) {
5496     SDValue X = N0.getOperand(0).getOperand(0);
5497     if (X.getValueType().bitsLT(VT)) {
5498       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5499     } else if (X.getValueType().bitsGT(VT)) {
5500       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5501     }
5502     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5503     Mask = Mask.zext(VT.getSizeInBits());
5504     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5505                        X, DAG.getConstant(Mask, VT));
5506   }
5507
5508   // fold (aext (load x)) -> (aext (truncate (extload x)))
5509   // None of the supported targets knows how to perform load and any_ext
5510   // on vectors in one instruction.  We only perform this transformation on
5511   // scalars.
5512   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5513       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5514       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5515        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5516     bool DoXform = true;
5517     SmallVector<SDNode*, 4> SetCCs;
5518     if (!N0.hasOneUse())
5519       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5520     if (DoXform) {
5521       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5522       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5523                                        LN0->getChain(),
5524                                        LN0->getBasePtr(), N0.getValueType(),
5525                                        LN0->getMemOperand());
5526       CombineTo(N, ExtLoad);
5527       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5528                                   N0.getValueType(), ExtLoad);
5529       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5530       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5531                       ISD::ANY_EXTEND);
5532       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5533     }
5534   }
5535
5536   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5537   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5538   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5539   if (N0.getOpcode() == ISD::LOAD &&
5540       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5541       N0.hasOneUse()) {
5542     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5543     ISD::LoadExtType ExtType = LN0->getExtensionType();
5544     EVT MemVT = LN0->getMemoryVT();
5545     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5546       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5547                                        VT, LN0->getChain(), LN0->getBasePtr(),
5548                                        MemVT, LN0->getMemOperand());
5549       CombineTo(N, ExtLoad);
5550       CombineTo(N0.getNode(),
5551                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5552                             N0.getValueType(), ExtLoad),
5553                 ExtLoad.getValue(1));
5554       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5555     }
5556   }
5557
5558   if (N0.getOpcode() == ISD::SETCC) {
5559     // For vectors:
5560     // aext(setcc) -> vsetcc
5561     // aext(setcc) -> truncate(vsetcc)
5562     // aext(setcc) -> aext(vsetcc)
5563     // Only do this before legalize for now.
5564     if (VT.isVector() && !LegalOperations) {
5565       EVT N0VT = N0.getOperand(0).getValueType();
5566         // We know that the # elements of the results is the same as the
5567         // # elements of the compare (and the # elements of the compare result
5568         // for that matter).  Check to see that they are the same size.  If so,
5569         // we know that the element size of the sext'd result matches the
5570         // element size of the compare operands.
5571       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5572         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5573                              N0.getOperand(1),
5574                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5575       // If the desired elements are smaller or larger than the source
5576       // elements we can use a matching integer vector type and then
5577       // truncate/any extend
5578       else {
5579         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5580         SDValue VsetCC =
5581           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5582                         N0.getOperand(1),
5583                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5584         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5585       }
5586     }
5587
5588     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5589     SDValue SCC =
5590       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5591                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5592                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5593     if (SCC.getNode())
5594       return SCC;
5595   }
5596
5597   return SDValue();
5598 }
5599
5600 /// GetDemandedBits - See if the specified operand can be simplified with the
5601 /// knowledge that only the bits specified by Mask are used.  If so, return the
5602 /// simpler operand, otherwise return a null SDValue.
5603 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5604   switch (V.getOpcode()) {
5605   default: break;
5606   case ISD::Constant: {
5607     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5608     assert(CV && "Const value should be ConstSDNode.");
5609     const APInt &CVal = CV->getAPIntValue();
5610     APInt NewVal = CVal & Mask;
5611     if (NewVal != CVal)
5612       return DAG.getConstant(NewVal, V.getValueType());
5613     break;
5614   }
5615   case ISD::OR:
5616   case ISD::XOR:
5617     // If the LHS or RHS don't contribute bits to the or, drop them.
5618     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5619       return V.getOperand(1);
5620     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5621       return V.getOperand(0);
5622     break;
5623   case ISD::SRL:
5624     // Only look at single-use SRLs.
5625     if (!V.getNode()->hasOneUse())
5626       break;
5627     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5628       // See if we can recursively simplify the LHS.
5629       unsigned Amt = RHSC->getZExtValue();
5630
5631       // Watch out for shift count overflow though.
5632       if (Amt >= Mask.getBitWidth()) break;
5633       APInt NewMask = Mask << Amt;
5634       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5635       if (SimplifyLHS.getNode())
5636         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5637                            SimplifyLHS, V.getOperand(1));
5638     }
5639   }
5640   return SDValue();
5641 }
5642
5643 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5644 /// bits and then truncated to a narrower type and where N is a multiple
5645 /// of number of bits of the narrower type, transform it to a narrower load
5646 /// from address + N / num of bits of new type. If the result is to be
5647 /// extended, also fold the extension to form a extending load.
5648 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5649   unsigned Opc = N->getOpcode();
5650
5651   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5652   SDValue N0 = N->getOperand(0);
5653   EVT VT = N->getValueType(0);
5654   EVT ExtVT = VT;
5655
5656   // This transformation isn't valid for vector loads.
5657   if (VT.isVector())
5658     return SDValue();
5659
5660   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5661   // extended to VT.
5662   if (Opc == ISD::SIGN_EXTEND_INREG) {
5663     ExtType = ISD::SEXTLOAD;
5664     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5665   } else if (Opc == ISD::SRL) {
5666     // Another special-case: SRL is basically zero-extending a narrower value.
5667     ExtType = ISD::ZEXTLOAD;
5668     N0 = SDValue(N, 0);
5669     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5670     if (!N01) return SDValue();
5671     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5672                               VT.getSizeInBits() - N01->getZExtValue());
5673   }
5674   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5675     return SDValue();
5676
5677   unsigned EVTBits = ExtVT.getSizeInBits();
5678
5679   // Do not generate loads of non-round integer types since these can
5680   // be expensive (and would be wrong if the type is not byte sized).
5681   if (!ExtVT.isRound())
5682     return SDValue();
5683
5684   unsigned ShAmt = 0;
5685   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5686     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5687       ShAmt = N01->getZExtValue();
5688       // Is the shift amount a multiple of size of VT?
5689       if ((ShAmt & (EVTBits-1)) == 0) {
5690         N0 = N0.getOperand(0);
5691         // Is the load width a multiple of size of VT?
5692         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5693           return SDValue();
5694       }
5695
5696       // At this point, we must have a load or else we can't do the transform.
5697       if (!isa<LoadSDNode>(N0)) return SDValue();
5698
5699       // Because a SRL must be assumed to *need* to zero-extend the high bits
5700       // (as opposed to anyext the high bits), we can't combine the zextload
5701       // lowering of SRL and an sextload.
5702       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5703         return SDValue();
5704
5705       // If the shift amount is larger than the input type then we're not
5706       // accessing any of the loaded bytes.  If the load was a zextload/extload
5707       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5708       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5709         return SDValue();
5710     }
5711   }
5712
5713   // If the load is shifted left (and the result isn't shifted back right),
5714   // we can fold the truncate through the shift.
5715   unsigned ShLeftAmt = 0;
5716   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5717       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5718     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5719       ShLeftAmt = N01->getZExtValue();
5720       N0 = N0.getOperand(0);
5721     }
5722   }
5723
5724   // If we haven't found a load, we can't narrow it.  Don't transform one with
5725   // multiple uses, this would require adding a new load.
5726   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5727     return SDValue();
5728
5729   // Don't change the width of a volatile load.
5730   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5731   if (LN0->isVolatile())
5732     return SDValue();
5733
5734   // Verify that we are actually reducing a load width here.
5735   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5736     return SDValue();
5737
5738   // For the transform to be legal, the load must produce only two values
5739   // (the value loaded and the chain).  Don't transform a pre-increment
5740   // load, for example, which produces an extra value.  Otherwise the
5741   // transformation is not equivalent, and the downstream logic to replace
5742   // uses gets things wrong.
5743   if (LN0->getNumValues() > 2)
5744     return SDValue();
5745
5746   // If the load that we're shrinking is an extload and we're not just
5747   // discarding the extension we can't simply shrink the load. Bail.
5748   // TODO: It would be possible to merge the extensions in some cases.
5749   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5750       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5751     return SDValue();
5752
5753   EVT PtrType = N0.getOperand(1).getValueType();
5754
5755   if (PtrType == MVT::Untyped || PtrType.isExtended())
5756     // It's not possible to generate a constant of extended or untyped type.
5757     return SDValue();
5758
5759   // For big endian targets, we need to adjust the offset to the pointer to
5760   // load the correct bytes.
5761   if (TLI.isBigEndian()) {
5762     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5763     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5764     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5765   }
5766
5767   uint64_t PtrOff = ShAmt / 8;
5768   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5769   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5770                                PtrType, LN0->getBasePtr(),
5771                                DAG.getConstant(PtrOff, PtrType));
5772   AddToWorkList(NewPtr.getNode());
5773
5774   SDValue Load;
5775   if (ExtType == ISD::NON_EXTLOAD)
5776     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5777                         LN0->getPointerInfo().getWithOffset(PtrOff),
5778                         LN0->isVolatile(), LN0->isNonTemporal(),
5779                         LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5780   else
5781     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5782                           LN0->getPointerInfo().getWithOffset(PtrOff),
5783                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5784                           NewAlign, LN0->getTBAAInfo());
5785
5786   // Replace the old load's chain with the new load's chain.
5787   WorkListRemover DeadNodes(*this);
5788   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5789
5790   // Shift the result left, if we've swallowed a left shift.
5791   SDValue Result = Load;
5792   if (ShLeftAmt != 0) {
5793     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5794     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5795       ShImmTy = VT;
5796     // If the shift amount is as large as the result size (but, presumably,
5797     // no larger than the source) then the useful bits of the result are
5798     // zero; we can't simply return the shortened shift, because the result
5799     // of that operation is undefined.
5800     if (ShLeftAmt >= VT.getSizeInBits())
5801       Result = DAG.getConstant(0, VT);
5802     else
5803       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5804                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5805   }
5806
5807   // Return the new loaded value.
5808   return Result;
5809 }
5810
5811 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5812   SDValue N0 = N->getOperand(0);
5813   SDValue N1 = N->getOperand(1);
5814   EVT VT = N->getValueType(0);
5815   EVT EVT = cast<VTSDNode>(N1)->getVT();
5816   unsigned VTBits = VT.getScalarType().getSizeInBits();
5817   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5818
5819   // fold (sext_in_reg c1) -> c1
5820   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5821     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5822
5823   // If the input is already sign extended, just drop the extension.
5824   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5825     return N0;
5826
5827   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5828   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5829       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5830     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5831                        N0.getOperand(0), N1);
5832
5833   // fold (sext_in_reg (sext x)) -> (sext x)
5834   // fold (sext_in_reg (aext x)) -> (sext x)
5835   // if x is small enough.
5836   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5837     SDValue N00 = N0.getOperand(0);
5838     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5839         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5840       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5841   }
5842
5843   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5844   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5845     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5846
5847   // fold operands of sext_in_reg based on knowledge that the top bits are not
5848   // demanded.
5849   if (SimplifyDemandedBits(SDValue(N, 0)))
5850     return SDValue(N, 0);
5851
5852   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5853   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5854   SDValue NarrowLoad = ReduceLoadWidth(N);
5855   if (NarrowLoad.getNode())
5856     return NarrowLoad;
5857
5858   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5859   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5860   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5861   if (N0.getOpcode() == ISD::SRL) {
5862     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5863       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5864         // We can turn this into an SRA iff the input to the SRL is already sign
5865         // extended enough.
5866         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5867         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5868           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5869                              N0.getOperand(0), N0.getOperand(1));
5870       }
5871   }
5872
5873   // fold (sext_inreg (extload x)) -> (sextload x)
5874   if (ISD::isEXTLoad(N0.getNode()) &&
5875       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5876       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5877       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5878        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5879     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5880     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5881                                      LN0->getChain(),
5882                                      LN0->getBasePtr(), EVT,
5883                                      LN0->getMemOperand());
5884     CombineTo(N, ExtLoad);
5885     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5886     AddToWorkList(ExtLoad.getNode());
5887     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5888   }
5889   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5890   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5891       N0.hasOneUse() &&
5892       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5893       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5894        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5895     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5896     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5897                                      LN0->getChain(),
5898                                      LN0->getBasePtr(), EVT,
5899                                      LN0->getMemOperand());
5900     CombineTo(N, ExtLoad);
5901     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5902     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5903   }
5904
5905   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5906   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5907     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5908                                        N0.getOperand(1), false);
5909     if (BSwap.getNode())
5910       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5911                          BSwap, N1);
5912   }
5913
5914   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5915   // into a build_vector.
5916   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5917     SmallVector<SDValue, 8> Elts;
5918     unsigned NumElts = N0->getNumOperands();
5919     unsigned ShAmt = VTBits - EVTBits;
5920
5921     for (unsigned i = 0; i != NumElts; ++i) {
5922       SDValue Op = N0->getOperand(i);
5923       if (Op->getOpcode() == ISD::UNDEF) {
5924         Elts.push_back(Op);
5925         continue;
5926       }
5927
5928       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5929       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5930       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5931                                      Op.getValueType()));
5932     }
5933
5934     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5935   }
5936
5937   return SDValue();
5938 }
5939
5940 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5941   SDValue N0 = N->getOperand(0);
5942   EVT VT = N->getValueType(0);
5943   bool isLE = TLI.isLittleEndian();
5944
5945   // noop truncate
5946   if (N0.getValueType() == N->getValueType(0))
5947     return N0;
5948   // fold (truncate c1) -> c1
5949   if (isa<ConstantSDNode>(N0))
5950     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5951   // fold (truncate (truncate x)) -> (truncate x)
5952   if (N0.getOpcode() == ISD::TRUNCATE)
5953     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5954   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5955   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5956       N0.getOpcode() == ISD::SIGN_EXTEND ||
5957       N0.getOpcode() == ISD::ANY_EXTEND) {
5958     if (N0.getOperand(0).getValueType().bitsLT(VT))
5959       // if the source is smaller than the dest, we still need an extend
5960       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5961                          N0.getOperand(0));
5962     if (N0.getOperand(0).getValueType().bitsGT(VT))
5963       // if the source is larger than the dest, than we just need the truncate
5964       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5965     // if the source and dest are the same type, we can drop both the extend
5966     // and the truncate.
5967     return N0.getOperand(0);
5968   }
5969
5970   // Fold extract-and-trunc into a narrow extract. For example:
5971   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5972   //   i32 y = TRUNCATE(i64 x)
5973   //        -- becomes --
5974   //   v16i8 b = BITCAST (v2i64 val)
5975   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5976   //
5977   // Note: We only run this optimization after type legalization (which often
5978   // creates this pattern) and before operation legalization after which
5979   // we need to be more careful about the vector instructions that we generate.
5980   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5981       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5982
5983     EVT VecTy = N0.getOperand(0).getValueType();
5984     EVT ExTy = N0.getValueType();
5985     EVT TrTy = N->getValueType(0);
5986
5987     unsigned NumElem = VecTy.getVectorNumElements();
5988     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5989
5990     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5991     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5992
5993     SDValue EltNo = N0->getOperand(1);
5994     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5995       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5996       EVT IndexTy = TLI.getVectorIdxTy();
5997       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5998
5999       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6000                               NVT, N0.getOperand(0));
6001
6002       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6003                          SDLoc(N), TrTy, V,
6004                          DAG.getConstant(Index, IndexTy));
6005     }
6006   }
6007
6008   // Fold a series of buildvector, bitcast, and truncate if possible.
6009   // For example fold
6010   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6011   //   (2xi32 (buildvector x, y)).
6012   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6013       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6014       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6015       N0.getOperand(0).hasOneUse()) {
6016
6017     SDValue BuildVect = N0.getOperand(0);
6018     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6019     EVT TruncVecEltTy = VT.getVectorElementType();
6020
6021     // Check that the element types match.
6022     if (BuildVectEltTy == TruncVecEltTy) {
6023       // Now we only need to compute the offset of the truncated elements.
6024       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6025       unsigned TruncVecNumElts = VT.getVectorNumElements();
6026       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6027
6028       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6029              "Invalid number of elements");
6030
6031       SmallVector<SDValue, 8> Opnds;
6032       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6033         Opnds.push_back(BuildVect.getOperand(i));
6034
6035       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6036     }
6037   }
6038
6039   // See if we can simplify the input to this truncate through knowledge that
6040   // only the low bits are being used.
6041   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6042   // Currently we only perform this optimization on scalars because vectors
6043   // may have different active low bits.
6044   if (!VT.isVector()) {
6045     SDValue Shorter =
6046       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6047                                                VT.getSizeInBits()));
6048     if (Shorter.getNode())
6049       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6050   }
6051   // fold (truncate (load x)) -> (smaller load x)
6052   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6053   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6054     SDValue Reduced = ReduceLoadWidth(N);
6055     if (Reduced.getNode())
6056       return Reduced;
6057     // Handle the case where the load remains an extending load even
6058     // after truncation.
6059     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6060       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6061       if (!LN0->isVolatile() &&
6062           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6063         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6064                                          VT, LN0->getChain(), LN0->getBasePtr(),
6065                                          LN0->getMemoryVT(),
6066                                          LN0->getMemOperand());
6067         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6068         return NewLoad;
6069       }
6070     }
6071   }
6072   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6073   // where ... are all 'undef'.
6074   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6075     SmallVector<EVT, 8> VTs;
6076     SDValue V;
6077     unsigned Idx = 0;
6078     unsigned NumDefs = 0;
6079
6080     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6081       SDValue X = N0.getOperand(i);
6082       if (X.getOpcode() != ISD::UNDEF) {
6083         V = X;
6084         Idx = i;
6085         NumDefs++;
6086       }
6087       // Stop if more than one members are non-undef.
6088       if (NumDefs > 1)
6089         break;
6090       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6091                                      VT.getVectorElementType(),
6092                                      X.getValueType().getVectorNumElements()));
6093     }
6094
6095     if (NumDefs == 0)
6096       return DAG.getUNDEF(VT);
6097
6098     if (NumDefs == 1) {
6099       assert(V.getNode() && "The single defined operand is empty!");
6100       SmallVector<SDValue, 8> Opnds;
6101       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6102         if (i != Idx) {
6103           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6104           continue;
6105         }
6106         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6107         AddToWorkList(NV.getNode());
6108         Opnds.push_back(NV);
6109       }
6110       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6111     }
6112   }
6113
6114   // Simplify the operands using demanded-bits information.
6115   if (!VT.isVector() &&
6116       SimplifyDemandedBits(SDValue(N, 0)))
6117     return SDValue(N, 0);
6118
6119   return SDValue();
6120 }
6121
6122 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6123   SDValue Elt = N->getOperand(i);
6124   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6125     return Elt.getNode();
6126   return Elt.getOperand(Elt.getResNo()).getNode();
6127 }
6128
6129 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6130 /// if load locations are consecutive.
6131 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6132   assert(N->getOpcode() == ISD::BUILD_PAIR);
6133
6134   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6135   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6136   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6137       LD1->getAddressSpace() != LD2->getAddressSpace())
6138     return SDValue();
6139   EVT LD1VT = LD1->getValueType(0);
6140
6141   if (ISD::isNON_EXTLoad(LD2) &&
6142       LD2->hasOneUse() &&
6143       // If both are volatile this would reduce the number of volatile loads.
6144       // If one is volatile it might be ok, but play conservative and bail out.
6145       !LD1->isVolatile() &&
6146       !LD2->isVolatile() &&
6147       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6148     unsigned Align = LD1->getAlignment();
6149     unsigned NewAlign = TLI.getDataLayout()->
6150       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6151
6152     if (NewAlign <= Align &&
6153         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6154       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6155                          LD1->getBasePtr(), LD1->getPointerInfo(),
6156                          false, false, false, Align);
6157   }
6158
6159   return SDValue();
6160 }
6161
6162 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6163   SDValue N0 = N->getOperand(0);
6164   EVT VT = N->getValueType(0);
6165
6166   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6167   // Only do this before legalize, since afterward the target may be depending
6168   // on the bitconvert.
6169   // First check to see if this is all constant.
6170   if (!LegalTypes &&
6171       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6172       VT.isVector()) {
6173     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6174
6175     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6176     assert(!DestEltVT.isVector() &&
6177            "Element type of vector ValueType must not be vector!");
6178     if (isSimple)
6179       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6180   }
6181
6182   // If the input is a constant, let getNode fold it.
6183   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6184     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6185     if (Res.getNode() != N) {
6186       if (!LegalOperations ||
6187           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6188         return Res;
6189
6190       // Folding it resulted in an illegal node, and it's too late to
6191       // do that. Clean up the old node and forego the transformation.
6192       // Ideally this won't happen very often, because instcombine
6193       // and the earlier dagcombine runs (where illegal nodes are
6194       // permitted) should have folded most of them already.
6195       DAG.DeleteNode(Res.getNode());
6196     }
6197   }
6198
6199   // (conv (conv x, t1), t2) -> (conv x, t2)
6200   if (N0.getOpcode() == ISD::BITCAST)
6201     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6202                        N0.getOperand(0));
6203
6204   // fold (conv (load x)) -> (load (conv*)x)
6205   // If the resultant load doesn't need a higher alignment than the original!
6206   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6207       // Do not change the width of a volatile load.
6208       !cast<LoadSDNode>(N0)->isVolatile() &&
6209       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6210       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6211     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6212     unsigned Align = TLI.getDataLayout()->
6213       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6214     unsigned OrigAlign = LN0->getAlignment();
6215
6216     if (Align <= OrigAlign) {
6217       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6218                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6219                                  LN0->isVolatile(), LN0->isNonTemporal(),
6220                                  LN0->isInvariant(), OrigAlign,
6221                                  LN0->getTBAAInfo());
6222       AddToWorkList(N);
6223       CombineTo(N0.getNode(),
6224                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6225                             N0.getValueType(), Load),
6226                 Load.getValue(1));
6227       return Load;
6228     }
6229   }
6230
6231   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6232   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6233   // This often reduces constant pool loads.
6234   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6235        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6236       N0.getNode()->hasOneUse() && VT.isInteger() &&
6237       !VT.isVector() && !N0.getValueType().isVector()) {
6238     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6239                                   N0.getOperand(0));
6240     AddToWorkList(NewConv.getNode());
6241
6242     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6243     if (N0.getOpcode() == ISD::FNEG)
6244       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6245                          NewConv, DAG.getConstant(SignBit, VT));
6246     assert(N0.getOpcode() == ISD::FABS);
6247     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6248                        NewConv, DAG.getConstant(~SignBit, VT));
6249   }
6250
6251   // fold (bitconvert (fcopysign cst, x)) ->
6252   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6253   // Note that we don't handle (copysign x, cst) because this can always be
6254   // folded to an fneg or fabs.
6255   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6256       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6257       VT.isInteger() && !VT.isVector()) {
6258     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6259     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6260     if (isTypeLegal(IntXVT)) {
6261       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6262                               IntXVT, N0.getOperand(1));
6263       AddToWorkList(X.getNode());
6264
6265       // If X has a different width than the result/lhs, sext it or truncate it.
6266       unsigned VTWidth = VT.getSizeInBits();
6267       if (OrigXWidth < VTWidth) {
6268         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6269         AddToWorkList(X.getNode());
6270       } else if (OrigXWidth > VTWidth) {
6271         // To get the sign bit in the right place, we have to shift it right
6272         // before truncating.
6273         X = DAG.getNode(ISD::SRL, SDLoc(X),
6274                         X.getValueType(), X,
6275                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6276         AddToWorkList(X.getNode());
6277         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6278         AddToWorkList(X.getNode());
6279       }
6280
6281       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6282       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6283                       X, DAG.getConstant(SignBit, VT));
6284       AddToWorkList(X.getNode());
6285
6286       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6287                                 VT, N0.getOperand(0));
6288       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6289                         Cst, DAG.getConstant(~SignBit, VT));
6290       AddToWorkList(Cst.getNode());
6291
6292       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6293     }
6294   }
6295
6296   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6297   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6298     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6299     if (CombineLD.getNode())
6300       return CombineLD;
6301   }
6302
6303   return SDValue();
6304 }
6305
6306 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6307   EVT VT = N->getValueType(0);
6308   return CombineConsecutiveLoads(N, VT);
6309 }
6310
6311 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6312 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6313 /// destination element value type.
6314 SDValue DAGCombiner::
6315 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6316   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6317
6318   // If this is already the right type, we're done.
6319   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6320
6321   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6322   unsigned DstBitSize = DstEltVT.getSizeInBits();
6323
6324   // If this is a conversion of N elements of one type to N elements of another
6325   // type, convert each element.  This handles FP<->INT cases.
6326   if (SrcBitSize == DstBitSize) {
6327     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6328                               BV->getValueType(0).getVectorNumElements());
6329
6330     // Due to the FP element handling below calling this routine recursively,
6331     // we can end up with a scalar-to-vector node here.
6332     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6333       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6334                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6335                                      DstEltVT, BV->getOperand(0)));
6336
6337     SmallVector<SDValue, 8> Ops;
6338     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6339       SDValue Op = BV->getOperand(i);
6340       // If the vector element type is not legal, the BUILD_VECTOR operands
6341       // are promoted and implicitly truncated.  Make that explicit here.
6342       if (Op.getValueType() != SrcEltVT)
6343         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6344       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6345                                 DstEltVT, Op));
6346       AddToWorkList(Ops.back().getNode());
6347     }
6348     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6349   }
6350
6351   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6352   // handle annoying details of growing/shrinking FP values, we convert them to
6353   // int first.
6354   if (SrcEltVT.isFloatingPoint()) {
6355     // Convert the input float vector to a int vector where the elements are the
6356     // same sizes.
6357     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6358     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6359     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6360     SrcEltVT = IntVT;
6361   }
6362
6363   // Now we know the input is an integer vector.  If the output is a FP type,
6364   // convert to integer first, then to FP of the right size.
6365   if (DstEltVT.isFloatingPoint()) {
6366     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6367     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6368     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6369
6370     // Next, convert to FP elements of the same size.
6371     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6372   }
6373
6374   // Okay, we know the src/dst types are both integers of differing types.
6375   // Handling growing first.
6376   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6377   if (SrcBitSize < DstBitSize) {
6378     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6379
6380     SmallVector<SDValue, 8> Ops;
6381     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6382          i += NumInputsPerOutput) {
6383       bool isLE = TLI.isLittleEndian();
6384       APInt NewBits = APInt(DstBitSize, 0);
6385       bool EltIsUndef = true;
6386       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6387         // Shift the previously computed bits over.
6388         NewBits <<= SrcBitSize;
6389         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6390         if (Op.getOpcode() == ISD::UNDEF) continue;
6391         EltIsUndef = false;
6392
6393         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6394                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6395       }
6396
6397       if (EltIsUndef)
6398         Ops.push_back(DAG.getUNDEF(DstEltVT));
6399       else
6400         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6401     }
6402
6403     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6404     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6405   }
6406
6407   // Finally, this must be the case where we are shrinking elements: each input
6408   // turns into multiple outputs.
6409   bool isS2V = ISD::isScalarToVector(BV);
6410   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6411   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6412                             NumOutputsPerInput*BV->getNumOperands());
6413   SmallVector<SDValue, 8> Ops;
6414
6415   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6416     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6417       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6418         Ops.push_back(DAG.getUNDEF(DstEltVT));
6419       continue;
6420     }
6421
6422     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6423                   getAPIntValue().zextOrTrunc(SrcBitSize);
6424
6425     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6426       APInt ThisVal = OpVal.trunc(DstBitSize);
6427       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6428       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6429         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6430         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6431                            Ops[0]);
6432       OpVal = OpVal.lshr(DstBitSize);
6433     }
6434
6435     // For big endian targets, swap the order of the pieces of each element.
6436     if (TLI.isBigEndian())
6437       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6438   }
6439
6440   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6441 }
6442
6443 SDValue DAGCombiner::visitFADD(SDNode *N) {
6444   SDValue N0 = N->getOperand(0);
6445   SDValue N1 = N->getOperand(1);
6446   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6447   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6448   EVT VT = N->getValueType(0);
6449
6450   // fold vector ops
6451   if (VT.isVector()) {
6452     SDValue FoldedVOp = SimplifyVBinOp(N);
6453     if (FoldedVOp.getNode()) return FoldedVOp;
6454   }
6455
6456   // fold (fadd c1, c2) -> c1 + c2
6457   if (N0CFP && N1CFP)
6458     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6459   // canonicalize constant to RHS
6460   if (N0CFP && !N1CFP)
6461     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6462   // fold (fadd A, 0) -> A
6463   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6464       N1CFP->getValueAPF().isZero())
6465     return N0;
6466   // fold (fadd A, (fneg B)) -> (fsub A, B)
6467   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6468     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6469     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6470                        GetNegatedExpression(N1, DAG, LegalOperations));
6471   // fold (fadd (fneg A), B) -> (fsub B, A)
6472   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6473     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6474     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6475                        GetNegatedExpression(N0, DAG, LegalOperations));
6476
6477   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6478   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6479       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6480       isa<ConstantFPSDNode>(N0.getOperand(1)))
6481     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6482                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6483                                    N0.getOperand(1), N1));
6484
6485   // No FP constant should be created after legalization as Instruction
6486   // Selection pass has hard time in dealing with FP constant.
6487   //
6488   // We don't need test this condition for transformation like following, as
6489   // the DAG being transformed implies it is legal to take FP constant as
6490   // operand.
6491   //
6492   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6493   //
6494   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6495
6496   // If allow, fold (fadd (fneg x), x) -> 0.0
6497   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6498       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6499     return DAG.getConstantFP(0.0, VT);
6500
6501     // If allow, fold (fadd x, (fneg x)) -> 0.0
6502   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6503       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6504     return DAG.getConstantFP(0.0, VT);
6505
6506   // In unsafe math mode, we can fold chains of FADD's of the same value
6507   // into multiplications.  This transform is not safe in general because
6508   // we are reducing the number of rounding steps.
6509   if (DAG.getTarget().Options.UnsafeFPMath &&
6510       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6511       !N0CFP && !N1CFP) {
6512     if (N0.getOpcode() == ISD::FMUL) {
6513       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6514       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6515
6516       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6517       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6518         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6519                                      SDValue(CFP00, 0),
6520                                      DAG.getConstantFP(1.0, VT));
6521         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6522                            N1, NewCFP);
6523       }
6524
6525       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6526       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6527         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6528                                      SDValue(CFP01, 0),
6529                                      DAG.getConstantFP(1.0, VT));
6530         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6531                            N1, NewCFP);
6532       }
6533
6534       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6535       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6536           N1.getOperand(0) == N1.getOperand(1) &&
6537           N0.getOperand(1) == N1.getOperand(0)) {
6538         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6539                                      SDValue(CFP00, 0),
6540                                      DAG.getConstantFP(2.0, VT));
6541         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6542                            N0.getOperand(1), NewCFP);
6543       }
6544
6545       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6546       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6547           N1.getOperand(0) == N1.getOperand(1) &&
6548           N0.getOperand(0) == N1.getOperand(0)) {
6549         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6550                                      SDValue(CFP01, 0),
6551                                      DAG.getConstantFP(2.0, VT));
6552         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6553                            N0.getOperand(0), NewCFP);
6554       }
6555     }
6556
6557     if (N1.getOpcode() == ISD::FMUL) {
6558       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6559       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6560
6561       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6562       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6563         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6564                                      SDValue(CFP10, 0),
6565                                      DAG.getConstantFP(1.0, VT));
6566         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6567                            N0, NewCFP);
6568       }
6569
6570       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6571       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6572         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6573                                      SDValue(CFP11, 0),
6574                                      DAG.getConstantFP(1.0, VT));
6575         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6576                            N0, NewCFP);
6577       }
6578
6579
6580       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6581       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6582           N0.getOperand(0) == N0.getOperand(1) &&
6583           N1.getOperand(1) == N0.getOperand(0)) {
6584         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6585                                      SDValue(CFP10, 0),
6586                                      DAG.getConstantFP(2.0, VT));
6587         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6588                            N1.getOperand(1), NewCFP);
6589       }
6590
6591       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6592       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6593           N0.getOperand(0) == N0.getOperand(1) &&
6594           N1.getOperand(0) == N0.getOperand(0)) {
6595         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6596                                      SDValue(CFP11, 0),
6597                                      DAG.getConstantFP(2.0, VT));
6598         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6599                            N1.getOperand(0), NewCFP);
6600       }
6601     }
6602
6603     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6604       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6605       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6606       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6607           (N0.getOperand(0) == N1))
6608         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6609                            N1, DAG.getConstantFP(3.0, VT));
6610     }
6611
6612     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6613       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6614       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6615       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6616           N1.getOperand(0) == N0)
6617         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6618                            N0, DAG.getConstantFP(3.0, VT));
6619     }
6620
6621     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6622     if (AllowNewFpConst &&
6623         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6624         N0.getOperand(0) == N0.getOperand(1) &&
6625         N1.getOperand(0) == N1.getOperand(1) &&
6626         N0.getOperand(0) == N1.getOperand(0))
6627       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6628                          N0.getOperand(0),
6629                          DAG.getConstantFP(4.0, VT));
6630   }
6631
6632   // FADD -> FMA combines:
6633   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6634        DAG.getTarget().Options.UnsafeFPMath) &&
6635       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6636       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6637
6638     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6639     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6640       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6641                          N0.getOperand(0), N0.getOperand(1), N1);
6642
6643     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6644     // Note: Commutes FADD operands.
6645     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6646       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6647                          N1.getOperand(0), N1.getOperand(1), N0);
6648   }
6649
6650   return SDValue();
6651 }
6652
6653 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6654   SDValue N0 = N->getOperand(0);
6655   SDValue N1 = N->getOperand(1);
6656   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6657   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6658   EVT VT = N->getValueType(0);
6659   SDLoc dl(N);
6660
6661   // fold vector ops
6662   if (VT.isVector()) {
6663     SDValue FoldedVOp = SimplifyVBinOp(N);
6664     if (FoldedVOp.getNode()) return FoldedVOp;
6665   }
6666
6667   // fold (fsub c1, c2) -> c1-c2
6668   if (N0CFP && N1CFP)
6669     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6670   // fold (fsub A, 0) -> A
6671   if (DAG.getTarget().Options.UnsafeFPMath &&
6672       N1CFP && N1CFP->getValueAPF().isZero())
6673     return N0;
6674   // fold (fsub 0, B) -> -B
6675   if (DAG.getTarget().Options.UnsafeFPMath &&
6676       N0CFP && N0CFP->getValueAPF().isZero()) {
6677     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6678       return GetNegatedExpression(N1, DAG, LegalOperations);
6679     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6680       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6681   }
6682   // fold (fsub A, (fneg B)) -> (fadd A, B)
6683   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6684     return DAG.getNode(ISD::FADD, dl, VT, N0,
6685                        GetNegatedExpression(N1, DAG, LegalOperations));
6686
6687   // If 'unsafe math' is enabled, fold
6688   //    (fsub x, x) -> 0.0 &
6689   //    (fsub x, (fadd x, y)) -> (fneg y) &
6690   //    (fsub x, (fadd y, x)) -> (fneg y)
6691   if (DAG.getTarget().Options.UnsafeFPMath) {
6692     if (N0 == N1)
6693       return DAG.getConstantFP(0.0f, VT);
6694
6695     if (N1.getOpcode() == ISD::FADD) {
6696       SDValue N10 = N1->getOperand(0);
6697       SDValue N11 = N1->getOperand(1);
6698
6699       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6700                                           &DAG.getTarget().Options))
6701         return GetNegatedExpression(N11, DAG, LegalOperations);
6702
6703       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6704                                           &DAG.getTarget().Options))
6705         return GetNegatedExpression(N10, DAG, LegalOperations);
6706     }
6707   }
6708
6709   // FSUB -> FMA combines:
6710   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6711        DAG.getTarget().Options.UnsafeFPMath) &&
6712       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6713       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6714
6715     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6716     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6717       return DAG.getNode(ISD::FMA, dl, VT,
6718                          N0.getOperand(0), N0.getOperand(1),
6719                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6720
6721     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6722     // Note: Commutes FSUB operands.
6723     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6724       return DAG.getNode(ISD::FMA, dl, VT,
6725                          DAG.getNode(ISD::FNEG, dl, VT,
6726                          N1.getOperand(0)),
6727                          N1.getOperand(1), N0);
6728
6729     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6730     if (N0.getOpcode() == ISD::FNEG &&
6731         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6732         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6733       SDValue N00 = N0.getOperand(0).getOperand(0);
6734       SDValue N01 = N0.getOperand(0).getOperand(1);
6735       return DAG.getNode(ISD::FMA, dl, VT,
6736                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6737                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6738     }
6739   }
6740
6741   return SDValue();
6742 }
6743
6744 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6745   SDValue N0 = N->getOperand(0);
6746   SDValue N1 = N->getOperand(1);
6747   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6748   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6749   EVT VT = N->getValueType(0);
6750   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6751
6752   // fold vector ops
6753   if (VT.isVector()) {
6754     SDValue FoldedVOp = SimplifyVBinOp(N);
6755     if (FoldedVOp.getNode()) return FoldedVOp;
6756   }
6757
6758   // fold (fmul c1, c2) -> c1*c2
6759   if (N0CFP && N1CFP)
6760     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6761   // canonicalize constant to RHS
6762   if (N0CFP && !N1CFP)
6763     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6764   // fold (fmul A, 0) -> 0
6765   if (DAG.getTarget().Options.UnsafeFPMath &&
6766       N1CFP && N1CFP->getValueAPF().isZero())
6767     return N1;
6768   // fold (fmul A, 0) -> 0, vector edition.
6769   if (DAG.getTarget().Options.UnsafeFPMath &&
6770       ISD::isBuildVectorAllZeros(N1.getNode()))
6771     return N1;
6772   // fold (fmul A, 1.0) -> A
6773   if (N1CFP && N1CFP->isExactlyValue(1.0))
6774     return N0;
6775   // fold (fmul X, 2.0) -> (fadd X, X)
6776   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6777     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6778   // fold (fmul X, -1.0) -> (fneg X)
6779   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6780     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6781       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6782
6783   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6784   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6785                                        &DAG.getTarget().Options)) {
6786     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6787                                          &DAG.getTarget().Options)) {
6788       // Both can be negated for free, check to see if at least one is cheaper
6789       // negated.
6790       if (LHSNeg == 2 || RHSNeg == 2)
6791         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6792                            GetNegatedExpression(N0, DAG, LegalOperations),
6793                            GetNegatedExpression(N1, DAG, LegalOperations));
6794     }
6795   }
6796
6797   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6798   if (DAG.getTarget().Options.UnsafeFPMath &&
6799       N1CFP && N0.getOpcode() == ISD::FMUL &&
6800       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6801     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6802                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6803                                    N0.getOperand(1), N1));
6804
6805   return SDValue();
6806 }
6807
6808 SDValue DAGCombiner::visitFMA(SDNode *N) {
6809   SDValue N0 = N->getOperand(0);
6810   SDValue N1 = N->getOperand(1);
6811   SDValue N2 = N->getOperand(2);
6812   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6813   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6814   EVT VT = N->getValueType(0);
6815   SDLoc dl(N);
6816
6817   if (DAG.getTarget().Options.UnsafeFPMath) {
6818     if (N0CFP && N0CFP->isZero())
6819       return N2;
6820     if (N1CFP && N1CFP->isZero())
6821       return N2;
6822   }
6823   if (N0CFP && N0CFP->isExactlyValue(1.0))
6824     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6825   if (N1CFP && N1CFP->isExactlyValue(1.0))
6826     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6827
6828   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6829   if (N0CFP && !N1CFP)
6830     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6831
6832   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6833   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6834       N2.getOpcode() == ISD::FMUL &&
6835       N0 == N2.getOperand(0) &&
6836       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6837     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6838                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6839   }
6840
6841
6842   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6843   if (DAG.getTarget().Options.UnsafeFPMath &&
6844       N0.getOpcode() == ISD::FMUL && N1CFP &&
6845       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6846     return DAG.getNode(ISD::FMA, dl, VT,
6847                        N0.getOperand(0),
6848                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6849                        N2);
6850   }
6851
6852   // (fma x, 1, y) -> (fadd x, y)
6853   // (fma x, -1, y) -> (fadd (fneg x), y)
6854   if (N1CFP) {
6855     if (N1CFP->isExactlyValue(1.0))
6856       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6857
6858     if (N1CFP->isExactlyValue(-1.0) &&
6859         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6860       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6861       AddToWorkList(RHSNeg.getNode());
6862       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6863     }
6864   }
6865
6866   // (fma x, c, x) -> (fmul x, (c+1))
6867   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6868     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6869                        DAG.getNode(ISD::FADD, dl, VT,
6870                                    N1, DAG.getConstantFP(1.0, VT)));
6871
6872   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6873   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6874       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6875     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6876                        DAG.getNode(ISD::FADD, dl, VT,
6877                                    N1, DAG.getConstantFP(-1.0, VT)));
6878
6879
6880   return SDValue();
6881 }
6882
6883 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6884   SDValue N0 = N->getOperand(0);
6885   SDValue N1 = N->getOperand(1);
6886   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6887   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6888   EVT VT = N->getValueType(0);
6889   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6890
6891   // fold vector ops
6892   if (VT.isVector()) {
6893     SDValue FoldedVOp = SimplifyVBinOp(N);
6894     if (FoldedVOp.getNode()) return FoldedVOp;
6895   }
6896
6897   // fold (fdiv c1, c2) -> c1/c2
6898   if (N0CFP && N1CFP)
6899     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6900
6901   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6902   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6903     // Compute the reciprocal 1.0 / c2.
6904     APFloat N1APF = N1CFP->getValueAPF();
6905     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6906     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6907     // Only do the transform if the reciprocal is a legal fp immediate that
6908     // isn't too nasty (eg NaN, denormal, ...).
6909     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6910         (!LegalOperations ||
6911          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6912          // backend)... we should handle this gracefully after Legalize.
6913          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6914          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6915          TLI.isFPImmLegal(Recip, VT)))
6916       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6917                          DAG.getConstantFP(Recip, VT));
6918   }
6919
6920   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6921   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6922                                        &DAG.getTarget().Options)) {
6923     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6924                                          &DAG.getTarget().Options)) {
6925       // Both can be negated for free, check to see if at least one is cheaper
6926       // negated.
6927       if (LHSNeg == 2 || RHSNeg == 2)
6928         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6929                            GetNegatedExpression(N0, DAG, LegalOperations),
6930                            GetNegatedExpression(N1, DAG, LegalOperations));
6931     }
6932   }
6933
6934   return SDValue();
6935 }
6936
6937 SDValue DAGCombiner::visitFREM(SDNode *N) {
6938   SDValue N0 = N->getOperand(0);
6939   SDValue N1 = N->getOperand(1);
6940   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6941   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6942   EVT VT = N->getValueType(0);
6943
6944   // fold (frem c1, c2) -> fmod(c1,c2)
6945   if (N0CFP && N1CFP)
6946     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6947
6948   return SDValue();
6949 }
6950
6951 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6952   SDValue N0 = N->getOperand(0);
6953   SDValue N1 = N->getOperand(1);
6954   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6955   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6956   EVT VT = N->getValueType(0);
6957
6958   if (N0CFP && N1CFP)  // Constant fold
6959     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6960
6961   if (N1CFP) {
6962     const APFloat& V = N1CFP->getValueAPF();
6963     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6964     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6965     if (!V.isNegative()) {
6966       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6967         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6968     } else {
6969       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6970         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6971                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6972     }
6973   }
6974
6975   // copysign(fabs(x), y) -> copysign(x, y)
6976   // copysign(fneg(x), y) -> copysign(x, y)
6977   // copysign(copysign(x,z), y) -> copysign(x, y)
6978   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6979       N0.getOpcode() == ISD::FCOPYSIGN)
6980     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6981                        N0.getOperand(0), N1);
6982
6983   // copysign(x, abs(y)) -> abs(x)
6984   if (N1.getOpcode() == ISD::FABS)
6985     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6986
6987   // copysign(x, copysign(y,z)) -> copysign(x, z)
6988   if (N1.getOpcode() == ISD::FCOPYSIGN)
6989     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6990                        N0, N1.getOperand(1));
6991
6992   // copysign(x, fp_extend(y)) -> copysign(x, y)
6993   // copysign(x, fp_round(y)) -> copysign(x, y)
6994   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6995     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6996                        N0, N1.getOperand(0));
6997
6998   return SDValue();
6999 }
7000
7001 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7002   SDValue N0 = N->getOperand(0);
7003   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7004   EVT VT = N->getValueType(0);
7005   EVT OpVT = N0.getValueType();
7006
7007   // fold (sint_to_fp c1) -> c1fp
7008   if (N0C &&
7009       // ...but only if the target supports immediate floating-point values
7010       (!LegalOperations ||
7011        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7012     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7013
7014   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7015   // but UINT_TO_FP is legal on this target, try to convert.
7016   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7017       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7018     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7019     if (DAG.SignBitIsZero(N0))
7020       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7021   }
7022
7023   // The next optimizations are desirable only if SELECT_CC can be lowered.
7024   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7025   // having to say they don't support SELECT_CC on every type the DAG knows
7026   // about, since there is no way to mark an opcode illegal at all value types
7027   // (See also visitSELECT)
7028   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7029     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7030     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7031         !VT.isVector() &&
7032         (!LegalOperations ||
7033          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7034       SDValue Ops[] =
7035         { N0.getOperand(0), N0.getOperand(1),
7036           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7037           N0.getOperand(2) };
7038       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7039     }
7040
7041     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7042     //      (select_cc x, y, 1.0, 0.0,, cc)
7043     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7044         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7045         (!LegalOperations ||
7046          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7047       SDValue Ops[] =
7048         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7049           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7050           N0.getOperand(0).getOperand(2) };
7051       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7052     }
7053   }
7054
7055   return SDValue();
7056 }
7057
7058 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7059   SDValue N0 = N->getOperand(0);
7060   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7061   EVT VT = N->getValueType(0);
7062   EVT OpVT = N0.getValueType();
7063
7064   // fold (uint_to_fp c1) -> c1fp
7065   if (N0C &&
7066       // ...but only if the target supports immediate floating-point values
7067       (!LegalOperations ||
7068        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7069     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7070
7071   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7072   // but SINT_TO_FP is legal on this target, try to convert.
7073   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7074       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7075     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7076     if (DAG.SignBitIsZero(N0))
7077       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7078   }
7079
7080   // The next optimizations are desirable only if SELECT_CC can be lowered.
7081   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7082   // having to say they don't support SELECT_CC on every type the DAG knows
7083   // about, since there is no way to mark an opcode illegal at all value types
7084   // (See also visitSELECT)
7085   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7086     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7087
7088     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7089         (!LegalOperations ||
7090          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7091       SDValue Ops[] =
7092         { N0.getOperand(0), N0.getOperand(1),
7093           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7094           N0.getOperand(2) };
7095       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7096     }
7097   }
7098
7099   return SDValue();
7100 }
7101
7102 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7103   SDValue N0 = N->getOperand(0);
7104   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7105   EVT VT = N->getValueType(0);
7106
7107   // fold (fp_to_sint c1fp) -> c1
7108   if (N0CFP)
7109     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7110
7111   return SDValue();
7112 }
7113
7114 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7115   SDValue N0 = N->getOperand(0);
7116   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7117   EVT VT = N->getValueType(0);
7118
7119   // fold (fp_to_uint c1fp) -> c1
7120   if (N0CFP)
7121     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7122
7123   return SDValue();
7124 }
7125
7126 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7127   SDValue N0 = N->getOperand(0);
7128   SDValue N1 = N->getOperand(1);
7129   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7130   EVT VT = N->getValueType(0);
7131
7132   // fold (fp_round c1fp) -> c1fp
7133   if (N0CFP)
7134     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7135
7136   // fold (fp_round (fp_extend x)) -> x
7137   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7138     return N0.getOperand(0);
7139
7140   // fold (fp_round (fp_round x)) -> (fp_round x)
7141   if (N0.getOpcode() == ISD::FP_ROUND) {
7142     // This is a value preserving truncation if both round's are.
7143     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7144                    N0.getNode()->getConstantOperandVal(1) == 1;
7145     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7146                        DAG.getIntPtrConstant(IsTrunc));
7147   }
7148
7149   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7150   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7151     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7152                               N0.getOperand(0), N1);
7153     AddToWorkList(Tmp.getNode());
7154     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7155                        Tmp, N0.getOperand(1));
7156   }
7157
7158   return SDValue();
7159 }
7160
7161 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7162   SDValue N0 = N->getOperand(0);
7163   EVT VT = N->getValueType(0);
7164   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7165   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7166
7167   // fold (fp_round_inreg c1fp) -> c1fp
7168   if (N0CFP && isTypeLegal(EVT)) {
7169     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7170     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7171   }
7172
7173   return SDValue();
7174 }
7175
7176 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7177   SDValue N0 = N->getOperand(0);
7178   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7179   EVT VT = N->getValueType(0);
7180
7181   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7182   if (N->hasOneUse() &&
7183       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7184     return SDValue();
7185
7186   // fold (fp_extend c1fp) -> c1fp
7187   if (N0CFP)
7188     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7189
7190   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7191   // value of X.
7192   if (N0.getOpcode() == ISD::FP_ROUND
7193       && N0.getNode()->getConstantOperandVal(1) == 1) {
7194     SDValue In = N0.getOperand(0);
7195     if (In.getValueType() == VT) return In;
7196     if (VT.bitsLT(In.getValueType()))
7197       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7198                          In, N0.getOperand(1));
7199     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7200   }
7201
7202   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7203   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7204       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7205        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7206     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7207     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7208                                      LN0->getChain(),
7209                                      LN0->getBasePtr(), N0.getValueType(),
7210                                      LN0->getMemOperand());
7211     CombineTo(N, ExtLoad);
7212     CombineTo(N0.getNode(),
7213               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7214                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7215               ExtLoad.getValue(1));
7216     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7217   }
7218
7219   return SDValue();
7220 }
7221
7222 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7223   SDValue N0 = N->getOperand(0);
7224   EVT VT = N->getValueType(0);
7225
7226   if (VT.isVector()) {
7227     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7228     if (FoldedVOp.getNode()) return FoldedVOp;
7229   }
7230
7231   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7232                          &DAG.getTarget().Options))
7233     return GetNegatedExpression(N0, DAG, LegalOperations);
7234
7235   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7236   // constant pool values.
7237   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7238       !VT.isVector() &&
7239       N0.getNode()->hasOneUse() &&
7240       N0.getOperand(0).getValueType().isInteger()) {
7241     SDValue Int = N0.getOperand(0);
7242     EVT IntVT = Int.getValueType();
7243     if (IntVT.isInteger() && !IntVT.isVector()) {
7244       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7245               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7246       AddToWorkList(Int.getNode());
7247       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7248                          VT, Int);
7249     }
7250   }
7251
7252   // (fneg (fmul c, x)) -> (fmul -c, x)
7253   if (N0.getOpcode() == ISD::FMUL) {
7254     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7255     if (CFP1) {
7256       APFloat CVal = CFP1->getValueAPF();
7257       CVal.changeSign();
7258       if (Level >= AfterLegalizeDAG &&
7259           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7260            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7261         return DAG.getNode(
7262             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7263             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7264     }
7265   }
7266
7267   return SDValue();
7268 }
7269
7270 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7271   SDValue N0 = N->getOperand(0);
7272   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7273   EVT VT = N->getValueType(0);
7274
7275   // fold (fceil c1) -> fceil(c1)
7276   if (N0CFP)
7277     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7278
7279   return SDValue();
7280 }
7281
7282 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7283   SDValue N0 = N->getOperand(0);
7284   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7285   EVT VT = N->getValueType(0);
7286
7287   // fold (ftrunc c1) -> ftrunc(c1)
7288   if (N0CFP)
7289     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7290
7291   return SDValue();
7292 }
7293
7294 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7295   SDValue N0 = N->getOperand(0);
7296   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7297   EVT VT = N->getValueType(0);
7298
7299   // fold (ffloor c1) -> ffloor(c1)
7300   if (N0CFP)
7301     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7302
7303   return SDValue();
7304 }
7305
7306 SDValue DAGCombiner::visitFABS(SDNode *N) {
7307   SDValue N0 = N->getOperand(0);
7308   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7309   EVT VT = N->getValueType(0);
7310
7311   if (VT.isVector()) {
7312     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7313     if (FoldedVOp.getNode()) return FoldedVOp;
7314   }
7315
7316   // fold (fabs c1) -> fabs(c1)
7317   if (N0CFP)
7318     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7319   // fold (fabs (fabs x)) -> (fabs x)
7320   if (N0.getOpcode() == ISD::FABS)
7321     return N->getOperand(0);
7322   // fold (fabs (fneg x)) -> (fabs x)
7323   // fold (fabs (fcopysign x, y)) -> (fabs x)
7324   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7325     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7326
7327   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7328   // constant pool values.
7329   if (!TLI.isFAbsFree(VT) &&
7330       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7331       N0.getOperand(0).getValueType().isInteger() &&
7332       !N0.getOperand(0).getValueType().isVector()) {
7333     SDValue Int = N0.getOperand(0);
7334     EVT IntVT = Int.getValueType();
7335     if (IntVT.isInteger() && !IntVT.isVector()) {
7336       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7337              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7338       AddToWorkList(Int.getNode());
7339       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7340                          N->getValueType(0), Int);
7341     }
7342   }
7343
7344   return SDValue();
7345 }
7346
7347 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7348   SDValue Chain = N->getOperand(0);
7349   SDValue N1 = N->getOperand(1);
7350   SDValue N2 = N->getOperand(2);
7351
7352   // If N is a constant we could fold this into a fallthrough or unconditional
7353   // branch. However that doesn't happen very often in normal code, because
7354   // Instcombine/SimplifyCFG should have handled the available opportunities.
7355   // If we did this folding here, it would be necessary to update the
7356   // MachineBasicBlock CFG, which is awkward.
7357
7358   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7359   // on the target.
7360   if (N1.getOpcode() == ISD::SETCC &&
7361       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7362                                    N1.getOperand(0).getValueType())) {
7363     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7364                        Chain, N1.getOperand(2),
7365                        N1.getOperand(0), N1.getOperand(1), N2);
7366   }
7367
7368   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7369       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7370        (N1.getOperand(0).hasOneUse() &&
7371         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7372     SDNode *Trunc = nullptr;
7373     if (N1.getOpcode() == ISD::TRUNCATE) {
7374       // Look pass the truncate.
7375       Trunc = N1.getNode();
7376       N1 = N1.getOperand(0);
7377     }
7378
7379     // Match this pattern so that we can generate simpler code:
7380     //
7381     //   %a = ...
7382     //   %b = and i32 %a, 2
7383     //   %c = srl i32 %b, 1
7384     //   brcond i32 %c ...
7385     //
7386     // into
7387     //
7388     //   %a = ...
7389     //   %b = and i32 %a, 2
7390     //   %c = setcc eq %b, 0
7391     //   brcond %c ...
7392     //
7393     // This applies only when the AND constant value has one bit set and the
7394     // SRL constant is equal to the log2 of the AND constant. The back-end is
7395     // smart enough to convert the result into a TEST/JMP sequence.
7396     SDValue Op0 = N1.getOperand(0);
7397     SDValue Op1 = N1.getOperand(1);
7398
7399     if (Op0.getOpcode() == ISD::AND &&
7400         Op1.getOpcode() == ISD::Constant) {
7401       SDValue AndOp1 = Op0.getOperand(1);
7402
7403       if (AndOp1.getOpcode() == ISD::Constant) {
7404         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7405
7406         if (AndConst.isPowerOf2() &&
7407             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7408           SDValue SetCC =
7409             DAG.getSetCC(SDLoc(N),
7410                          getSetCCResultType(Op0.getValueType()),
7411                          Op0, DAG.getConstant(0, Op0.getValueType()),
7412                          ISD::SETNE);
7413
7414           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7415                                           MVT::Other, Chain, SetCC, N2);
7416           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7417           // will convert it back to (X & C1) >> C2.
7418           CombineTo(N, NewBRCond, false);
7419           // Truncate is dead.
7420           if (Trunc) {
7421             removeFromWorkList(Trunc);
7422             DAG.DeleteNode(Trunc);
7423           }
7424           // Replace the uses of SRL with SETCC
7425           WorkListRemover DeadNodes(*this);
7426           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7427           removeFromWorkList(N1.getNode());
7428           DAG.DeleteNode(N1.getNode());
7429           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7430         }
7431       }
7432     }
7433
7434     if (Trunc)
7435       // Restore N1 if the above transformation doesn't match.
7436       N1 = N->getOperand(1);
7437   }
7438
7439   // Transform br(xor(x, y)) -> br(x != y)
7440   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7441   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7442     SDNode *TheXor = N1.getNode();
7443     SDValue Op0 = TheXor->getOperand(0);
7444     SDValue Op1 = TheXor->getOperand(1);
7445     if (Op0.getOpcode() == Op1.getOpcode()) {
7446       // Avoid missing important xor optimizations.
7447       SDValue Tmp = visitXOR(TheXor);
7448       if (Tmp.getNode()) {
7449         if (Tmp.getNode() != TheXor) {
7450           DEBUG(dbgs() << "\nReplacing.8 ";
7451                 TheXor->dump(&DAG);
7452                 dbgs() << "\nWith: ";
7453                 Tmp.getNode()->dump(&DAG);
7454                 dbgs() << '\n');
7455           WorkListRemover DeadNodes(*this);
7456           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7457           removeFromWorkList(TheXor);
7458           DAG.DeleteNode(TheXor);
7459           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7460                              MVT::Other, Chain, Tmp, N2);
7461         }
7462
7463         // visitXOR has changed XOR's operands or replaced the XOR completely,
7464         // bail out.
7465         return SDValue(N, 0);
7466       }
7467     }
7468
7469     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7470       bool Equal = false;
7471       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7472         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7473             Op0.getOpcode() == ISD::XOR) {
7474           TheXor = Op0.getNode();
7475           Equal = true;
7476         }
7477
7478       EVT SetCCVT = N1.getValueType();
7479       if (LegalTypes)
7480         SetCCVT = getSetCCResultType(SetCCVT);
7481       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7482                                    SetCCVT,
7483                                    Op0, Op1,
7484                                    Equal ? ISD::SETEQ : ISD::SETNE);
7485       // Replace the uses of XOR with SETCC
7486       WorkListRemover DeadNodes(*this);
7487       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7488       removeFromWorkList(N1.getNode());
7489       DAG.DeleteNode(N1.getNode());
7490       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7491                          MVT::Other, Chain, SetCC, N2);
7492     }
7493   }
7494
7495   return SDValue();
7496 }
7497
7498 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7499 //
7500 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7501   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7502   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7503
7504   // If N is a constant we could fold this into a fallthrough or unconditional
7505   // branch. However that doesn't happen very often in normal code, because
7506   // Instcombine/SimplifyCFG should have handled the available opportunities.
7507   // If we did this folding here, it would be necessary to update the
7508   // MachineBasicBlock CFG, which is awkward.
7509
7510   // Use SimplifySetCC to simplify SETCC's.
7511   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7512                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7513                                false);
7514   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7515
7516   // fold to a simpler setcc
7517   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7518     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7519                        N->getOperand(0), Simp.getOperand(2),
7520                        Simp.getOperand(0), Simp.getOperand(1),
7521                        N->getOperand(4));
7522
7523   return SDValue();
7524 }
7525
7526 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7527 /// uses N as its base pointer and that N may be folded in the load / store
7528 /// addressing mode.
7529 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7530                                     SelectionDAG &DAG,
7531                                     const TargetLowering &TLI) {
7532   EVT VT;
7533   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7534     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7535       return false;
7536     VT = Use->getValueType(0);
7537   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7538     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7539       return false;
7540     VT = ST->getValue().getValueType();
7541   } else
7542     return false;
7543
7544   TargetLowering::AddrMode AM;
7545   if (N->getOpcode() == ISD::ADD) {
7546     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7547     if (Offset)
7548       // [reg +/- imm]
7549       AM.BaseOffs = Offset->getSExtValue();
7550     else
7551       // [reg +/- reg]
7552       AM.Scale = 1;
7553   } else if (N->getOpcode() == ISD::SUB) {
7554     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7555     if (Offset)
7556       // [reg +/- imm]
7557       AM.BaseOffs = -Offset->getSExtValue();
7558     else
7559       // [reg +/- reg]
7560       AM.Scale = 1;
7561   } else
7562     return false;
7563
7564   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7565 }
7566
7567 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7568 /// pre-indexed load / store when the base pointer is an add or subtract
7569 /// and it has other uses besides the load / store. After the
7570 /// transformation, the new indexed load / store has effectively folded
7571 /// the add / subtract in and all of its other uses are redirected to the
7572 /// new load / store.
7573 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7574   if (Level < AfterLegalizeDAG)
7575     return false;
7576
7577   bool isLoad = true;
7578   SDValue Ptr;
7579   EVT VT;
7580   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7581     if (LD->isIndexed())
7582       return false;
7583     VT = LD->getMemoryVT();
7584     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7585         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7586       return false;
7587     Ptr = LD->getBasePtr();
7588   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7589     if (ST->isIndexed())
7590       return false;
7591     VT = ST->getMemoryVT();
7592     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7593         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7594       return false;
7595     Ptr = ST->getBasePtr();
7596     isLoad = false;
7597   } else {
7598     return false;
7599   }
7600
7601   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7602   // out.  There is no reason to make this a preinc/predec.
7603   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7604       Ptr.getNode()->hasOneUse())
7605     return false;
7606
7607   // Ask the target to do addressing mode selection.
7608   SDValue BasePtr;
7609   SDValue Offset;
7610   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7611   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7612     return false;
7613
7614   // Backends without true r+i pre-indexed forms may need to pass a
7615   // constant base with a variable offset so that constant coercion
7616   // will work with the patterns in canonical form.
7617   bool Swapped = false;
7618   if (isa<ConstantSDNode>(BasePtr)) {
7619     std::swap(BasePtr, Offset);
7620     Swapped = true;
7621   }
7622
7623   // Don't create a indexed load / store with zero offset.
7624   if (isa<ConstantSDNode>(Offset) &&
7625       cast<ConstantSDNode>(Offset)->isNullValue())
7626     return false;
7627
7628   // Try turning it into a pre-indexed load / store except when:
7629   // 1) The new base ptr is a frame index.
7630   // 2) If N is a store and the new base ptr is either the same as or is a
7631   //    predecessor of the value being stored.
7632   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7633   //    that would create a cycle.
7634   // 4) All uses are load / store ops that use it as old base ptr.
7635
7636   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7637   // (plus the implicit offset) to a register to preinc anyway.
7638   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7639     return false;
7640
7641   // Check #2.
7642   if (!isLoad) {
7643     SDValue Val = cast<StoreSDNode>(N)->getValue();
7644     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7645       return false;
7646   }
7647
7648   // If the offset is a constant, there may be other adds of constants that
7649   // can be folded with this one. We should do this to avoid having to keep
7650   // a copy of the original base pointer.
7651   SmallVector<SDNode *, 16> OtherUses;
7652   if (isa<ConstantSDNode>(Offset))
7653     for (SDNode *Use : BasePtr.getNode()->uses()) {
7654       if (Use == Ptr.getNode())
7655         continue;
7656
7657       if (Use->isPredecessorOf(N))
7658         continue;
7659
7660       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7661         OtherUses.clear();
7662         break;
7663       }
7664
7665       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7666       if (Op1.getNode() == BasePtr.getNode())
7667         std::swap(Op0, Op1);
7668       assert(Op0.getNode() == BasePtr.getNode() &&
7669              "Use of ADD/SUB but not an operand");
7670
7671       if (!isa<ConstantSDNode>(Op1)) {
7672         OtherUses.clear();
7673         break;
7674       }
7675
7676       // FIXME: In some cases, we can be smarter about this.
7677       if (Op1.getValueType() != Offset.getValueType()) {
7678         OtherUses.clear();
7679         break;
7680       }
7681
7682       OtherUses.push_back(Use);
7683     }
7684
7685   if (Swapped)
7686     std::swap(BasePtr, Offset);
7687
7688   // Now check for #3 and #4.
7689   bool RealUse = false;
7690
7691   // Caches for hasPredecessorHelper
7692   SmallPtrSet<const SDNode *, 32> Visited;
7693   SmallVector<const SDNode *, 16> Worklist;
7694
7695   for (SDNode *Use : Ptr.getNode()->uses()) {
7696     if (Use == N)
7697       continue;
7698     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7699       return false;
7700
7701     // If Ptr may be folded in addressing mode of other use, then it's
7702     // not profitable to do this transformation.
7703     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7704       RealUse = true;
7705   }
7706
7707   if (!RealUse)
7708     return false;
7709
7710   SDValue Result;
7711   if (isLoad)
7712     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7713                                 BasePtr, Offset, AM);
7714   else
7715     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7716                                  BasePtr, Offset, AM);
7717   ++PreIndexedNodes;
7718   ++NodesCombined;
7719   DEBUG(dbgs() << "\nReplacing.4 ";
7720         N->dump(&DAG);
7721         dbgs() << "\nWith: ";
7722         Result.getNode()->dump(&DAG);
7723         dbgs() << '\n');
7724   WorkListRemover DeadNodes(*this);
7725   if (isLoad) {
7726     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7727     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7728   } else {
7729     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7730   }
7731
7732   // Finally, since the node is now dead, remove it from the graph.
7733   DAG.DeleteNode(N);
7734
7735   if (Swapped)
7736     std::swap(BasePtr, Offset);
7737
7738   // Replace other uses of BasePtr that can be updated to use Ptr
7739   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7740     unsigned OffsetIdx = 1;
7741     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7742       OffsetIdx = 0;
7743     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7744            BasePtr.getNode() && "Expected BasePtr operand");
7745
7746     // We need to replace ptr0 in the following expression:
7747     //   x0 * offset0 + y0 * ptr0 = t0
7748     // knowing that
7749     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7750     //
7751     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7752     // indexed load/store and the expresion that needs to be re-written.
7753     //
7754     // Therefore, we have:
7755     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7756
7757     ConstantSDNode *CN =
7758       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7759     int X0, X1, Y0, Y1;
7760     APInt Offset0 = CN->getAPIntValue();
7761     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7762
7763     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7764     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7765     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7766     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7767
7768     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7769
7770     APInt CNV = Offset0;
7771     if (X0 < 0) CNV = -CNV;
7772     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7773     else CNV = CNV - Offset1;
7774
7775     // We can now generate the new expression.
7776     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7777     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7778
7779     SDValue NewUse = DAG.getNode(Opcode,
7780                                  SDLoc(OtherUses[i]),
7781                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7782     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7783     removeFromWorkList(OtherUses[i]);
7784     DAG.DeleteNode(OtherUses[i]);
7785   }
7786
7787   // Replace the uses of Ptr with uses of the updated base value.
7788   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7789   removeFromWorkList(Ptr.getNode());
7790   DAG.DeleteNode(Ptr.getNode());
7791
7792   return true;
7793 }
7794
7795 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7796 /// add / sub of the base pointer node into a post-indexed load / store.
7797 /// The transformation folded the add / subtract into the new indexed
7798 /// load / store effectively and all of its uses are redirected to the
7799 /// new load / store.
7800 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7801   if (Level < AfterLegalizeDAG)
7802     return false;
7803
7804   bool isLoad = true;
7805   SDValue Ptr;
7806   EVT VT;
7807   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7808     if (LD->isIndexed())
7809       return false;
7810     VT = LD->getMemoryVT();
7811     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7812         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7813       return false;
7814     Ptr = LD->getBasePtr();
7815   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7816     if (ST->isIndexed())
7817       return false;
7818     VT = ST->getMemoryVT();
7819     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7820         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7821       return false;
7822     Ptr = ST->getBasePtr();
7823     isLoad = false;
7824   } else {
7825     return false;
7826   }
7827
7828   if (Ptr.getNode()->hasOneUse())
7829     return false;
7830
7831   for (SDNode *Op : Ptr.getNode()->uses()) {
7832     if (Op == N ||
7833         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7834       continue;
7835
7836     SDValue BasePtr;
7837     SDValue Offset;
7838     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7839     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7840       // Don't create a indexed load / store with zero offset.
7841       if (isa<ConstantSDNode>(Offset) &&
7842           cast<ConstantSDNode>(Offset)->isNullValue())
7843         continue;
7844
7845       // Try turning it into a post-indexed load / store except when
7846       // 1) All uses are load / store ops that use it as base ptr (and
7847       //    it may be folded as addressing mmode).
7848       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7849       //    nor a successor of N. Otherwise, if Op is folded that would
7850       //    create a cycle.
7851
7852       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7853         continue;
7854
7855       // Check for #1.
7856       bool TryNext = false;
7857       for (SDNode *Use : BasePtr.getNode()->uses()) {
7858         if (Use == Ptr.getNode())
7859           continue;
7860
7861         // If all the uses are load / store addresses, then don't do the
7862         // transformation.
7863         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7864           bool RealUse = false;
7865           for (SDNode *UseUse : Use->uses()) {
7866             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7867               RealUse = true;
7868           }
7869
7870           if (!RealUse) {
7871             TryNext = true;
7872             break;
7873           }
7874         }
7875       }
7876
7877       if (TryNext)
7878         continue;
7879
7880       // Check for #2
7881       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7882         SDValue Result = isLoad
7883           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7884                                BasePtr, Offset, AM)
7885           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7886                                 BasePtr, Offset, AM);
7887         ++PostIndexedNodes;
7888         ++NodesCombined;
7889         DEBUG(dbgs() << "\nReplacing.5 ";
7890               N->dump(&DAG);
7891               dbgs() << "\nWith: ";
7892               Result.getNode()->dump(&DAG);
7893               dbgs() << '\n');
7894         WorkListRemover DeadNodes(*this);
7895         if (isLoad) {
7896           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7897           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7898         } else {
7899           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7900         }
7901
7902         // Finally, since the node is now dead, remove it from the graph.
7903         DAG.DeleteNode(N);
7904
7905         // Replace the uses of Use with uses of the updated base value.
7906         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7907                                       Result.getValue(isLoad ? 1 : 0));
7908         removeFromWorkList(Op);
7909         DAG.DeleteNode(Op);
7910         return true;
7911       }
7912     }
7913   }
7914
7915   return false;
7916 }
7917
7918 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7919   LoadSDNode *LD  = cast<LoadSDNode>(N);
7920   SDValue Chain = LD->getChain();
7921   SDValue Ptr   = LD->getBasePtr();
7922
7923   // If load is not volatile and there are no uses of the loaded value (and
7924   // the updated indexed value in case of indexed loads), change uses of the
7925   // chain value into uses of the chain input (i.e. delete the dead load).
7926   if (!LD->isVolatile()) {
7927     if (N->getValueType(1) == MVT::Other) {
7928       // Unindexed loads.
7929       if (!N->hasAnyUseOfValue(0)) {
7930         // It's not safe to use the two value CombineTo variant here. e.g.
7931         // v1, chain2 = load chain1, loc
7932         // v2, chain3 = load chain2, loc
7933         // v3         = add v2, c
7934         // Now we replace use of chain2 with chain1.  This makes the second load
7935         // isomorphic to the one we are deleting, and thus makes this load live.
7936         DEBUG(dbgs() << "\nReplacing.6 ";
7937               N->dump(&DAG);
7938               dbgs() << "\nWith chain: ";
7939               Chain.getNode()->dump(&DAG);
7940               dbgs() << "\n");
7941         WorkListRemover DeadNodes(*this);
7942         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7943
7944         if (N->use_empty()) {
7945           removeFromWorkList(N);
7946           DAG.DeleteNode(N);
7947         }
7948
7949         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7950       }
7951     } else {
7952       // Indexed loads.
7953       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7954       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7955         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7956         DEBUG(dbgs() << "\nReplacing.7 ";
7957               N->dump(&DAG);
7958               dbgs() << "\nWith: ";
7959               Undef.getNode()->dump(&DAG);
7960               dbgs() << " and 2 other values\n");
7961         WorkListRemover DeadNodes(*this);
7962         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7963         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7964                                       DAG.getUNDEF(N->getValueType(1)));
7965         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7966         removeFromWorkList(N);
7967         DAG.DeleteNode(N);
7968         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7969       }
7970     }
7971   }
7972
7973   // If this load is directly stored, replace the load value with the stored
7974   // value.
7975   // TODO: Handle store large -> read small portion.
7976   // TODO: Handle TRUNCSTORE/LOADEXT
7977   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7978     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7979       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7980       if (PrevST->getBasePtr() == Ptr &&
7981           PrevST->getValue().getValueType() == N->getValueType(0))
7982       return CombineTo(N, Chain.getOperand(1), Chain);
7983     }
7984   }
7985
7986   // Try to infer better alignment information than the load already has.
7987   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7988     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7989       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7990         SDValue NewLoad =
7991                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7992                               LD->getValueType(0),
7993                               Chain, Ptr, LD->getPointerInfo(),
7994                               LD->getMemoryVT(),
7995                               LD->isVolatile(), LD->isNonTemporal(), Align,
7996                               LD->getTBAAInfo());
7997         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7998       }
7999     }
8000   }
8001
8002   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8003     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8004 #ifndef NDEBUG
8005   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8006       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8007     UseAA = false;
8008 #endif
8009   if (UseAA && LD->isUnindexed()) {
8010     // Walk up chain skipping non-aliasing memory nodes.
8011     SDValue BetterChain = FindBetterChain(N, Chain);
8012
8013     // If there is a better chain.
8014     if (Chain != BetterChain) {
8015       SDValue ReplLoad;
8016
8017       // Replace the chain to void dependency.
8018       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8019         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8020                                BetterChain, Ptr, LD->getMemOperand());
8021       } else {
8022         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8023                                   LD->getValueType(0),
8024                                   BetterChain, Ptr, LD->getMemoryVT(),
8025                                   LD->getMemOperand());
8026       }
8027
8028       // Create token factor to keep old chain connected.
8029       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8030                                   MVT::Other, Chain, ReplLoad.getValue(1));
8031
8032       // Make sure the new and old chains are cleaned up.
8033       AddToWorkList(Token.getNode());
8034
8035       // Replace uses with load result and token factor. Don't add users
8036       // to work list.
8037       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8038     }
8039   }
8040
8041   // Try transforming N to an indexed load.
8042   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8043     return SDValue(N, 0);
8044
8045   // Try to slice up N to more direct loads if the slices are mapped to
8046   // different register banks or pairing can take place.
8047   if (SliceUpLoad(N))
8048     return SDValue(N, 0);
8049
8050   return SDValue();
8051 }
8052
8053 namespace {
8054 /// \brief Helper structure used to slice a load in smaller loads.
8055 /// Basically a slice is obtained from the following sequence:
8056 /// Origin = load Ty1, Base
8057 /// Shift = srl Ty1 Origin, CstTy Amount
8058 /// Inst = trunc Shift to Ty2
8059 ///
8060 /// Then, it will be rewriten into:
8061 /// Slice = load SliceTy, Base + SliceOffset
8062 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8063 ///
8064 /// SliceTy is deduced from the number of bits that are actually used to
8065 /// build Inst.
8066 struct LoadedSlice {
8067   /// \brief Helper structure used to compute the cost of a slice.
8068   struct Cost {
8069     /// Are we optimizing for code size.
8070     bool ForCodeSize;
8071     /// Various cost.
8072     unsigned Loads;
8073     unsigned Truncates;
8074     unsigned CrossRegisterBanksCopies;
8075     unsigned ZExts;
8076     unsigned Shift;
8077
8078     Cost(bool ForCodeSize = false)
8079         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8080           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8081
8082     /// \brief Get the cost of one isolated slice.
8083     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8084         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8085           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8086       EVT TruncType = LS.Inst->getValueType(0);
8087       EVT LoadedType = LS.getLoadedType();
8088       if (TruncType != LoadedType &&
8089           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8090         ZExts = 1;
8091     }
8092
8093     /// \brief Account for slicing gain in the current cost.
8094     /// Slicing provide a few gains like removing a shift or a
8095     /// truncate. This method allows to grow the cost of the original
8096     /// load with the gain from this slice.
8097     void addSliceGain(const LoadedSlice &LS) {
8098       // Each slice saves a truncate.
8099       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8100       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8101                               LS.Inst->getOperand(0).getValueType()))
8102         ++Truncates;
8103       // If there is a shift amount, this slice gets rid of it.
8104       if (LS.Shift)
8105         ++Shift;
8106       // If this slice can merge a cross register bank copy, account for it.
8107       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8108         ++CrossRegisterBanksCopies;
8109     }
8110
8111     Cost &operator+=(const Cost &RHS) {
8112       Loads += RHS.Loads;
8113       Truncates += RHS.Truncates;
8114       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8115       ZExts += RHS.ZExts;
8116       Shift += RHS.Shift;
8117       return *this;
8118     }
8119
8120     bool operator==(const Cost &RHS) const {
8121       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8122              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8123              ZExts == RHS.ZExts && Shift == RHS.Shift;
8124     }
8125
8126     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8127
8128     bool operator<(const Cost &RHS) const {
8129       // Assume cross register banks copies are as expensive as loads.
8130       // FIXME: Do we want some more target hooks?
8131       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8132       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8133       // Unless we are optimizing for code size, consider the
8134       // expensive operation first.
8135       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8136         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8137       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8138              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8139     }
8140
8141     bool operator>(const Cost &RHS) const { return RHS < *this; }
8142
8143     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8144
8145     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8146   };
8147   // The last instruction that represent the slice. This should be a
8148   // truncate instruction.
8149   SDNode *Inst;
8150   // The original load instruction.
8151   LoadSDNode *Origin;
8152   // The right shift amount in bits from the original load.
8153   unsigned Shift;
8154   // The DAG from which Origin came from.
8155   // This is used to get some contextual information about legal types, etc.
8156   SelectionDAG *DAG;
8157
8158   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8159               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8160       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8161
8162   LoadedSlice(const LoadedSlice &LS)
8163       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8164
8165   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8166   /// \return Result is \p BitWidth and has used bits set to 1 and
8167   ///         not used bits set to 0.
8168   APInt getUsedBits() const {
8169     // Reproduce the trunc(lshr) sequence:
8170     // - Start from the truncated value.
8171     // - Zero extend to the desired bit width.
8172     // - Shift left.
8173     assert(Origin && "No original load to compare against.");
8174     unsigned BitWidth = Origin->getValueSizeInBits(0);
8175     assert(Inst && "This slice is not bound to an instruction");
8176     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8177            "Extracted slice is bigger than the whole type!");
8178     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8179     UsedBits.setAllBits();
8180     UsedBits = UsedBits.zext(BitWidth);
8181     UsedBits <<= Shift;
8182     return UsedBits;
8183   }
8184
8185   /// \brief Get the size of the slice to be loaded in bytes.
8186   unsigned getLoadedSize() const {
8187     unsigned SliceSize = getUsedBits().countPopulation();
8188     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8189     return SliceSize / 8;
8190   }
8191
8192   /// \brief Get the type that will be loaded for this slice.
8193   /// Note: This may not be the final type for the slice.
8194   EVT getLoadedType() const {
8195     assert(DAG && "Missing context");
8196     LLVMContext &Ctxt = *DAG->getContext();
8197     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8198   }
8199
8200   /// \brief Get the alignment of the load used for this slice.
8201   unsigned getAlignment() const {
8202     unsigned Alignment = Origin->getAlignment();
8203     unsigned Offset = getOffsetFromBase();
8204     if (Offset != 0)
8205       Alignment = MinAlign(Alignment, Alignment + Offset);
8206     return Alignment;
8207   }
8208
8209   /// \brief Check if this slice can be rewritten with legal operations.
8210   bool isLegal() const {
8211     // An invalid slice is not legal.
8212     if (!Origin || !Inst || !DAG)
8213       return false;
8214
8215     // Offsets are for indexed load only, we do not handle that.
8216     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8217       return false;
8218
8219     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8220
8221     // Check that the type is legal.
8222     EVT SliceType = getLoadedType();
8223     if (!TLI.isTypeLegal(SliceType))
8224       return false;
8225
8226     // Check that the load is legal for this type.
8227     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8228       return false;
8229
8230     // Check that the offset can be computed.
8231     // 1. Check its type.
8232     EVT PtrType = Origin->getBasePtr().getValueType();
8233     if (PtrType == MVT::Untyped || PtrType.isExtended())
8234       return false;
8235
8236     // 2. Check that it fits in the immediate.
8237     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8238       return false;
8239
8240     // 3. Check that the computation is legal.
8241     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8242       return false;
8243
8244     // Check that the zext is legal if it needs one.
8245     EVT TruncateType = Inst->getValueType(0);
8246     if (TruncateType != SliceType &&
8247         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8248       return false;
8249
8250     return true;
8251   }
8252
8253   /// \brief Get the offset in bytes of this slice in the original chunk of
8254   /// bits.
8255   /// \pre DAG != nullptr.
8256   uint64_t getOffsetFromBase() const {
8257     assert(DAG && "Missing context.");
8258     bool IsBigEndian =
8259         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8260     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8261     uint64_t Offset = Shift / 8;
8262     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8263     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8264            "The size of the original loaded type is not a multiple of a"
8265            " byte.");
8266     // If Offset is bigger than TySizeInBytes, it means we are loading all
8267     // zeros. This should have been optimized before in the process.
8268     assert(TySizeInBytes > Offset &&
8269            "Invalid shift amount for given loaded size");
8270     if (IsBigEndian)
8271       Offset = TySizeInBytes - Offset - getLoadedSize();
8272     return Offset;
8273   }
8274
8275   /// \brief Generate the sequence of instructions to load the slice
8276   /// represented by this object and redirect the uses of this slice to
8277   /// this new sequence of instructions.
8278   /// \pre this->Inst && this->Origin are valid Instructions and this
8279   /// object passed the legal check: LoadedSlice::isLegal returned true.
8280   /// \return The last instruction of the sequence used to load the slice.
8281   SDValue loadSlice() const {
8282     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8283     const SDValue &OldBaseAddr = Origin->getBasePtr();
8284     SDValue BaseAddr = OldBaseAddr;
8285     // Get the offset in that chunk of bytes w.r.t. the endianess.
8286     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8287     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8288     if (Offset) {
8289       // BaseAddr = BaseAddr + Offset.
8290       EVT ArithType = BaseAddr.getValueType();
8291       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8292                               DAG->getConstant(Offset, ArithType));
8293     }
8294
8295     // Create the type of the loaded slice according to its size.
8296     EVT SliceType = getLoadedType();
8297
8298     // Create the load for the slice.
8299     SDValue LastInst = DAG->getLoad(
8300         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8301         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8302         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8303     // If the final type is not the same as the loaded type, this means that
8304     // we have to pad with zero. Create a zero extend for that.
8305     EVT FinalType = Inst->getValueType(0);
8306     if (SliceType != FinalType)
8307       LastInst =
8308           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8309     return LastInst;
8310   }
8311
8312   /// \brief Check if this slice can be merged with an expensive cross register
8313   /// bank copy. E.g.,
8314   /// i = load i32
8315   /// f = bitcast i32 i to float
8316   bool canMergeExpensiveCrossRegisterBankCopy() const {
8317     if (!Inst || !Inst->hasOneUse())
8318       return false;
8319     SDNode *Use = *Inst->use_begin();
8320     if (Use->getOpcode() != ISD::BITCAST)
8321       return false;
8322     assert(DAG && "Missing context");
8323     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8324     EVT ResVT = Use->getValueType(0);
8325     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8326     const TargetRegisterClass *ArgRC =
8327         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8328     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8329       return false;
8330
8331     // At this point, we know that we perform a cross-register-bank copy.
8332     // Check if it is expensive.
8333     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8334     // Assume bitcasts are cheap, unless both register classes do not
8335     // explicitly share a common sub class.
8336     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8337       return false;
8338
8339     // Check if it will be merged with the load.
8340     // 1. Check the alignment constraint.
8341     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8342         ResVT.getTypeForEVT(*DAG->getContext()));
8343
8344     if (RequiredAlignment > getAlignment())
8345       return false;
8346
8347     // 2. Check that the load is a legal operation for that type.
8348     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8349       return false;
8350
8351     // 3. Check that we do not have a zext in the way.
8352     if (Inst->getValueType(0) != getLoadedType())
8353       return false;
8354
8355     return true;
8356   }
8357 };
8358 }
8359
8360 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8361 /// \p UsedBits looks like 0..0 1..1 0..0.
8362 static bool areUsedBitsDense(const APInt &UsedBits) {
8363   // If all the bits are one, this is dense!
8364   if (UsedBits.isAllOnesValue())
8365     return true;
8366
8367   // Get rid of the unused bits on the right.
8368   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8369   // Get rid of the unused bits on the left.
8370   if (NarrowedUsedBits.countLeadingZeros())
8371     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8372   // Check that the chunk of bits is completely used.
8373   return NarrowedUsedBits.isAllOnesValue();
8374 }
8375
8376 /// \brief Check whether or not \p First and \p Second are next to each other
8377 /// in memory. This means that there is no hole between the bits loaded
8378 /// by \p First and the bits loaded by \p Second.
8379 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8380                                      const LoadedSlice &Second) {
8381   assert(First.Origin == Second.Origin && First.Origin &&
8382          "Unable to match different memory origins.");
8383   APInt UsedBits = First.getUsedBits();
8384   assert((UsedBits & Second.getUsedBits()) == 0 &&
8385          "Slices are not supposed to overlap.");
8386   UsedBits |= Second.getUsedBits();
8387   return areUsedBitsDense(UsedBits);
8388 }
8389
8390 /// \brief Adjust the \p GlobalLSCost according to the target
8391 /// paring capabilities and the layout of the slices.
8392 /// \pre \p GlobalLSCost should account for at least as many loads as
8393 /// there is in the slices in \p LoadedSlices.
8394 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8395                                  LoadedSlice::Cost &GlobalLSCost) {
8396   unsigned NumberOfSlices = LoadedSlices.size();
8397   // If there is less than 2 elements, no pairing is possible.
8398   if (NumberOfSlices < 2)
8399     return;
8400
8401   // Sort the slices so that elements that are likely to be next to each
8402   // other in memory are next to each other in the list.
8403   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8404             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8405     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8406     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8407   });
8408   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8409   // First (resp. Second) is the first (resp. Second) potentially candidate
8410   // to be placed in a paired load.
8411   const LoadedSlice *First = nullptr;
8412   const LoadedSlice *Second = nullptr;
8413   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8414                 // Set the beginning of the pair.
8415                                                            First = Second) {
8416
8417     Second = &LoadedSlices[CurrSlice];
8418
8419     // If First is NULL, it means we start a new pair.
8420     // Get to the next slice.
8421     if (!First)
8422       continue;
8423
8424     EVT LoadedType = First->getLoadedType();
8425
8426     // If the types of the slices are different, we cannot pair them.
8427     if (LoadedType != Second->getLoadedType())
8428       continue;
8429
8430     // Check if the target supplies paired loads for this type.
8431     unsigned RequiredAlignment = 0;
8432     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8433       // move to the next pair, this type is hopeless.
8434       Second = nullptr;
8435       continue;
8436     }
8437     // Check if we meet the alignment requirement.
8438     if (RequiredAlignment > First->getAlignment())
8439       continue;
8440
8441     // Check that both loads are next to each other in memory.
8442     if (!areSlicesNextToEachOther(*First, *Second))
8443       continue;
8444
8445     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8446     --GlobalLSCost.Loads;
8447     // Move to the next pair.
8448     Second = nullptr;
8449   }
8450 }
8451
8452 /// \brief Check the profitability of all involved LoadedSlice.
8453 /// Currently, it is considered profitable if there is exactly two
8454 /// involved slices (1) which are (2) next to each other in memory, and
8455 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8456 ///
8457 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8458 /// the elements themselves.
8459 ///
8460 /// FIXME: When the cost model will be mature enough, we can relax
8461 /// constraints (1) and (2).
8462 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8463                                 const APInt &UsedBits, bool ForCodeSize) {
8464   unsigned NumberOfSlices = LoadedSlices.size();
8465   if (StressLoadSlicing)
8466     return NumberOfSlices > 1;
8467
8468   // Check (1).
8469   if (NumberOfSlices != 2)
8470     return false;
8471
8472   // Check (2).
8473   if (!areUsedBitsDense(UsedBits))
8474     return false;
8475
8476   // Check (3).
8477   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8478   // The original code has one big load.
8479   OrigCost.Loads = 1;
8480   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8481     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8482     // Accumulate the cost of all the slices.
8483     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8484     GlobalSlicingCost += SliceCost;
8485
8486     // Account as cost in the original configuration the gain obtained
8487     // with the current slices.
8488     OrigCost.addSliceGain(LS);
8489   }
8490
8491   // If the target supports paired load, adjust the cost accordingly.
8492   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8493   return OrigCost > GlobalSlicingCost;
8494 }
8495
8496 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8497 /// operations, split it in the various pieces being extracted.
8498 ///
8499 /// This sort of thing is introduced by SROA.
8500 /// This slicing takes care not to insert overlapping loads.
8501 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8502 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8503   if (Level < AfterLegalizeDAG)
8504     return false;
8505
8506   LoadSDNode *LD = cast<LoadSDNode>(N);
8507   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8508       !LD->getValueType(0).isInteger())
8509     return false;
8510
8511   // Keep track of already used bits to detect overlapping values.
8512   // In that case, we will just abort the transformation.
8513   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8514
8515   SmallVector<LoadedSlice, 4> LoadedSlices;
8516
8517   // Check if this load is used as several smaller chunks of bits.
8518   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8519   // of computation for each trunc.
8520   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8521        UI != UIEnd; ++UI) {
8522     // Skip the uses of the chain.
8523     if (UI.getUse().getResNo() != 0)
8524       continue;
8525
8526     SDNode *User = *UI;
8527     unsigned Shift = 0;
8528
8529     // Check if this is a trunc(lshr).
8530     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8531         isa<ConstantSDNode>(User->getOperand(1))) {
8532       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8533       User = *User->use_begin();
8534     }
8535
8536     // At this point, User is a Truncate, iff we encountered, trunc or
8537     // trunc(lshr).
8538     if (User->getOpcode() != ISD::TRUNCATE)
8539       return false;
8540
8541     // The width of the type must be a power of 2 and greater than 8-bits.
8542     // Otherwise the load cannot be represented in LLVM IR.
8543     // Moreover, if we shifted with a non-8-bits multiple, the slice
8544     // will be across several bytes. We do not support that.
8545     unsigned Width = User->getValueSizeInBits(0);
8546     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8547       return 0;
8548
8549     // Build the slice for this chain of computations.
8550     LoadedSlice LS(User, LD, Shift, &DAG);
8551     APInt CurrentUsedBits = LS.getUsedBits();
8552
8553     // Check if this slice overlaps with another.
8554     if ((CurrentUsedBits & UsedBits) != 0)
8555       return false;
8556     // Update the bits used globally.
8557     UsedBits |= CurrentUsedBits;
8558
8559     // Check if the new slice would be legal.
8560     if (!LS.isLegal())
8561       return false;
8562
8563     // Record the slice.
8564     LoadedSlices.push_back(LS);
8565   }
8566
8567   // Abort slicing if it does not seem to be profitable.
8568   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8569     return false;
8570
8571   ++SlicedLoads;
8572
8573   // Rewrite each chain to use an independent load.
8574   // By construction, each chain can be represented by a unique load.
8575
8576   // Prepare the argument for the new token factor for all the slices.
8577   SmallVector<SDValue, 8> ArgChains;
8578   for (SmallVectorImpl<LoadedSlice>::const_iterator
8579            LSIt = LoadedSlices.begin(),
8580            LSItEnd = LoadedSlices.end();
8581        LSIt != LSItEnd; ++LSIt) {
8582     SDValue SliceInst = LSIt->loadSlice();
8583     CombineTo(LSIt->Inst, SliceInst, true);
8584     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8585       SliceInst = SliceInst.getOperand(0);
8586     assert(SliceInst->getOpcode() == ISD::LOAD &&
8587            "It takes more than a zext to get to the loaded slice!!");
8588     ArgChains.push_back(SliceInst.getValue(1));
8589   }
8590
8591   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8592                               ArgChains);
8593   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8594   return true;
8595 }
8596
8597 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8598 /// load is having specific bytes cleared out.  If so, return the byte size
8599 /// being masked out and the shift amount.
8600 static std::pair<unsigned, unsigned>
8601 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8602   std::pair<unsigned, unsigned> Result(0, 0);
8603
8604   // Check for the structure we're looking for.
8605   if (V->getOpcode() != ISD::AND ||
8606       !isa<ConstantSDNode>(V->getOperand(1)) ||
8607       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8608     return Result;
8609
8610   // Check the chain and pointer.
8611   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8612   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8613
8614   // The store should be chained directly to the load or be an operand of a
8615   // tokenfactor.
8616   if (LD == Chain.getNode())
8617     ; // ok.
8618   else if (Chain->getOpcode() != ISD::TokenFactor)
8619     return Result; // Fail.
8620   else {
8621     bool isOk = false;
8622     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8623       if (Chain->getOperand(i).getNode() == LD) {
8624         isOk = true;
8625         break;
8626       }
8627     if (!isOk) return Result;
8628   }
8629
8630   // This only handles simple types.
8631   if (V.getValueType() != MVT::i16 &&
8632       V.getValueType() != MVT::i32 &&
8633       V.getValueType() != MVT::i64)
8634     return Result;
8635
8636   // Check the constant mask.  Invert it so that the bits being masked out are
8637   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8638   // follow the sign bit for uniformity.
8639   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8640   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8641   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8642   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8643   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8644   if (NotMaskLZ == 64) return Result;  // All zero mask.
8645
8646   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8647   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8648     return Result;
8649
8650   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8651   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8652     NotMaskLZ -= 64-V.getValueSizeInBits();
8653
8654   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8655   switch (MaskedBytes) {
8656   case 1:
8657   case 2:
8658   case 4: break;
8659   default: return Result; // All one mask, or 5-byte mask.
8660   }
8661
8662   // Verify that the first bit starts at a multiple of mask so that the access
8663   // is aligned the same as the access width.
8664   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8665
8666   Result.first = MaskedBytes;
8667   Result.second = NotMaskTZ/8;
8668   return Result;
8669 }
8670
8671
8672 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8673 /// provides a value as specified by MaskInfo.  If so, replace the specified
8674 /// store with a narrower store of truncated IVal.
8675 static SDNode *
8676 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8677                                 SDValue IVal, StoreSDNode *St,
8678                                 DAGCombiner *DC) {
8679   unsigned NumBytes = MaskInfo.first;
8680   unsigned ByteShift = MaskInfo.second;
8681   SelectionDAG &DAG = DC->getDAG();
8682
8683   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8684   // that uses this.  If not, this is not a replacement.
8685   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8686                                   ByteShift*8, (ByteShift+NumBytes)*8);
8687   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8688
8689   // Check that it is legal on the target to do this.  It is legal if the new
8690   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8691   // legalization.
8692   MVT VT = MVT::getIntegerVT(NumBytes*8);
8693   if (!DC->isTypeLegal(VT))
8694     return nullptr;
8695
8696   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8697   // shifted by ByteShift and truncated down to NumBytes.
8698   if (ByteShift)
8699     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8700                        DAG.getConstant(ByteShift*8,
8701                                     DC->getShiftAmountTy(IVal.getValueType())));
8702
8703   // Figure out the offset for the store and the alignment of the access.
8704   unsigned StOffset;
8705   unsigned NewAlign = St->getAlignment();
8706
8707   if (DAG.getTargetLoweringInfo().isLittleEndian())
8708     StOffset = ByteShift;
8709   else
8710     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8711
8712   SDValue Ptr = St->getBasePtr();
8713   if (StOffset) {
8714     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8715                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8716     NewAlign = MinAlign(NewAlign, StOffset);
8717   }
8718
8719   // Truncate down to the new size.
8720   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8721
8722   ++OpsNarrowed;
8723   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8724                       St->getPointerInfo().getWithOffset(StOffset),
8725                       false, false, NewAlign).getNode();
8726 }
8727
8728
8729 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8730 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8731 /// of the loaded bits, try narrowing the load and store if it would end up
8732 /// being a win for performance or code size.
8733 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8734   StoreSDNode *ST  = cast<StoreSDNode>(N);
8735   if (ST->isVolatile())
8736     return SDValue();
8737
8738   SDValue Chain = ST->getChain();
8739   SDValue Value = ST->getValue();
8740   SDValue Ptr   = ST->getBasePtr();
8741   EVT VT = Value.getValueType();
8742
8743   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8744     return SDValue();
8745
8746   unsigned Opc = Value.getOpcode();
8747
8748   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8749   // is a byte mask indicating a consecutive number of bytes, check to see if
8750   // Y is known to provide just those bytes.  If so, we try to replace the
8751   // load + replace + store sequence with a single (narrower) store, which makes
8752   // the load dead.
8753   if (Opc == ISD::OR) {
8754     std::pair<unsigned, unsigned> MaskedLoad;
8755     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8756     if (MaskedLoad.first)
8757       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8758                                                   Value.getOperand(1), ST,this))
8759         return SDValue(NewST, 0);
8760
8761     // Or is commutative, so try swapping X and Y.
8762     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8763     if (MaskedLoad.first)
8764       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8765                                                   Value.getOperand(0), ST,this))
8766         return SDValue(NewST, 0);
8767   }
8768
8769   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8770       Value.getOperand(1).getOpcode() != ISD::Constant)
8771     return SDValue();
8772
8773   SDValue N0 = Value.getOperand(0);
8774   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8775       Chain == SDValue(N0.getNode(), 1)) {
8776     LoadSDNode *LD = cast<LoadSDNode>(N0);
8777     if (LD->getBasePtr() != Ptr ||
8778         LD->getPointerInfo().getAddrSpace() !=
8779         ST->getPointerInfo().getAddrSpace())
8780       return SDValue();
8781
8782     // Find the type to narrow it the load / op / store to.
8783     SDValue N1 = Value.getOperand(1);
8784     unsigned BitWidth = N1.getValueSizeInBits();
8785     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8786     if (Opc == ISD::AND)
8787       Imm ^= APInt::getAllOnesValue(BitWidth);
8788     if (Imm == 0 || Imm.isAllOnesValue())
8789       return SDValue();
8790     unsigned ShAmt = Imm.countTrailingZeros();
8791     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8792     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8793     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8794     while (NewBW < BitWidth &&
8795            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8796              TLI.isNarrowingProfitable(VT, NewVT))) {
8797       NewBW = NextPowerOf2(NewBW);
8798       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8799     }
8800     if (NewBW >= BitWidth)
8801       return SDValue();
8802
8803     // If the lsb changed does not start at the type bitwidth boundary,
8804     // start at the previous one.
8805     if (ShAmt % NewBW)
8806       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8807     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8808                                    std::min(BitWidth, ShAmt + NewBW));
8809     if ((Imm & Mask) == Imm) {
8810       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8811       if (Opc == ISD::AND)
8812         NewImm ^= APInt::getAllOnesValue(NewBW);
8813       uint64_t PtrOff = ShAmt / 8;
8814       // For big endian targets, we need to adjust the offset to the pointer to
8815       // load the correct bytes.
8816       if (TLI.isBigEndian())
8817         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8818
8819       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8820       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8821       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8822         return SDValue();
8823
8824       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8825                                    Ptr.getValueType(), Ptr,
8826                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8827       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8828                                   LD->getChain(), NewPtr,
8829                                   LD->getPointerInfo().getWithOffset(PtrOff),
8830                                   LD->isVolatile(), LD->isNonTemporal(),
8831                                   LD->isInvariant(), NewAlign,
8832                                   LD->getTBAAInfo());
8833       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8834                                    DAG.getConstant(NewImm, NewVT));
8835       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8836                                    NewVal, NewPtr,
8837                                    ST->getPointerInfo().getWithOffset(PtrOff),
8838                                    false, false, NewAlign);
8839
8840       AddToWorkList(NewPtr.getNode());
8841       AddToWorkList(NewLD.getNode());
8842       AddToWorkList(NewVal.getNode());
8843       WorkListRemover DeadNodes(*this);
8844       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8845       ++OpsNarrowed;
8846       return NewST;
8847     }
8848   }
8849
8850   return SDValue();
8851 }
8852
8853 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8854 /// if the load value isn't used by any other operations, then consider
8855 /// transforming the pair to integer load / store operations if the target
8856 /// deems the transformation profitable.
8857 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8858   StoreSDNode *ST  = cast<StoreSDNode>(N);
8859   SDValue Chain = ST->getChain();
8860   SDValue Value = ST->getValue();
8861   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8862       Value.hasOneUse() &&
8863       Chain == SDValue(Value.getNode(), 1)) {
8864     LoadSDNode *LD = cast<LoadSDNode>(Value);
8865     EVT VT = LD->getMemoryVT();
8866     if (!VT.isFloatingPoint() ||
8867         VT != ST->getMemoryVT() ||
8868         LD->isNonTemporal() ||
8869         ST->isNonTemporal() ||
8870         LD->getPointerInfo().getAddrSpace() != 0 ||
8871         ST->getPointerInfo().getAddrSpace() != 0)
8872       return SDValue();
8873
8874     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8875     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8876         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8877         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8878         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8879       return SDValue();
8880
8881     unsigned LDAlign = LD->getAlignment();
8882     unsigned STAlign = ST->getAlignment();
8883     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8884     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8885     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8886       return SDValue();
8887
8888     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8889                                 LD->getChain(), LD->getBasePtr(),
8890                                 LD->getPointerInfo(),
8891                                 false, false, false, LDAlign);
8892
8893     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8894                                  NewLD, ST->getBasePtr(),
8895                                  ST->getPointerInfo(),
8896                                  false, false, STAlign);
8897
8898     AddToWorkList(NewLD.getNode());
8899     AddToWorkList(NewST.getNode());
8900     WorkListRemover DeadNodes(*this);
8901     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8902     ++LdStFP2Int;
8903     return NewST;
8904   }
8905
8906   return SDValue();
8907 }
8908
8909 /// Helper struct to parse and store a memory address as base + index + offset.
8910 /// We ignore sign extensions when it is safe to do so.
8911 /// The following two expressions are not equivalent. To differentiate we need
8912 /// to store whether there was a sign extension involved in the index
8913 /// computation.
8914 ///  (load (i64 add (i64 copyfromreg %c)
8915 ///                 (i64 signextend (add (i8 load %index)
8916 ///                                      (i8 1))))
8917 /// vs
8918 ///
8919 /// (load (i64 add (i64 copyfromreg %c)
8920 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8921 ///                                         (i32 1)))))
8922 struct BaseIndexOffset {
8923   SDValue Base;
8924   SDValue Index;
8925   int64_t Offset;
8926   bool IsIndexSignExt;
8927
8928   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8929
8930   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8931                   bool IsIndexSignExt) :
8932     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8933
8934   bool equalBaseIndex(const BaseIndexOffset &Other) {
8935     return Other.Base == Base && Other.Index == Index &&
8936       Other.IsIndexSignExt == IsIndexSignExt;
8937   }
8938
8939   /// Parses tree in Ptr for base, index, offset addresses.
8940   static BaseIndexOffset match(SDValue Ptr) {
8941     bool IsIndexSignExt = false;
8942
8943     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8944     // instruction, then it could be just the BASE or everything else we don't
8945     // know how to handle. Just use Ptr as BASE and give up.
8946     if (Ptr->getOpcode() != ISD::ADD)
8947       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8948
8949     // We know that we have at least an ADD instruction. Try to pattern match
8950     // the simple case of BASE + OFFSET.
8951     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8952       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8953       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8954                               IsIndexSignExt);
8955     }
8956
8957     // Inside a loop the current BASE pointer is calculated using an ADD and a
8958     // MUL instruction. In this case Ptr is the actual BASE pointer.
8959     // (i64 add (i64 %array_ptr)
8960     //          (i64 mul (i64 %induction_var)
8961     //                   (i64 %element_size)))
8962     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8963       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8964
8965     // Look at Base + Index + Offset cases.
8966     SDValue Base = Ptr->getOperand(0);
8967     SDValue IndexOffset = Ptr->getOperand(1);
8968
8969     // Skip signextends.
8970     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8971       IndexOffset = IndexOffset->getOperand(0);
8972       IsIndexSignExt = true;
8973     }
8974
8975     // Either the case of Base + Index (no offset) or something else.
8976     if (IndexOffset->getOpcode() != ISD::ADD)
8977       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8978
8979     // Now we have the case of Base + Index + offset.
8980     SDValue Index = IndexOffset->getOperand(0);
8981     SDValue Offset = IndexOffset->getOperand(1);
8982
8983     if (!isa<ConstantSDNode>(Offset))
8984       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8985
8986     // Ignore signextends.
8987     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8988       Index = Index->getOperand(0);
8989       IsIndexSignExt = true;
8990     } else IsIndexSignExt = false;
8991
8992     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8993     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8994   }
8995 };
8996
8997 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8998 /// is located in a sequence of memory operations connected by a chain.
8999 struct MemOpLink {
9000   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9001     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9002   // Ptr to the mem node.
9003   LSBaseSDNode *MemNode;
9004   // Offset from the base ptr.
9005   int64_t OffsetFromBase;
9006   // What is the sequence number of this mem node.
9007   // Lowest mem operand in the DAG starts at zero.
9008   unsigned SequenceNum;
9009 };
9010
9011 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9012   EVT MemVT = St->getMemoryVT();
9013   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9014   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9015     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9016
9017   // Don't merge vectors into wider inputs.
9018   if (MemVT.isVector() || !MemVT.isSimple())
9019     return false;
9020
9021   // Perform an early exit check. Do not bother looking at stored values that
9022   // are not constants or loads.
9023   SDValue StoredVal = St->getValue();
9024   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9025   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9026       !IsLoadSrc)
9027     return false;
9028
9029   // Only look at ends of store sequences.
9030   SDValue Chain = SDValue(St, 1);
9031   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9032     return false;
9033
9034   // This holds the base pointer, index, and the offset in bytes from the base
9035   // pointer.
9036   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9037
9038   // We must have a base and an offset.
9039   if (!BasePtr.Base.getNode())
9040     return false;
9041
9042   // Do not handle stores to undef base pointers.
9043   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9044     return false;
9045
9046   // Save the LoadSDNodes that we find in the chain.
9047   // We need to make sure that these nodes do not interfere with
9048   // any of the store nodes.
9049   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9050
9051   // Save the StoreSDNodes that we find in the chain.
9052   SmallVector<MemOpLink, 8> StoreNodes;
9053
9054   // Walk up the chain and look for nodes with offsets from the same
9055   // base pointer. Stop when reaching an instruction with a different kind
9056   // or instruction which has a different base pointer.
9057   unsigned Seq = 0;
9058   StoreSDNode *Index = St;
9059   while (Index) {
9060     // If the chain has more than one use, then we can't reorder the mem ops.
9061     if (Index != St && !SDValue(Index, 1)->hasOneUse())
9062       break;
9063
9064     // Find the base pointer and offset for this memory node.
9065     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9066
9067     // Check that the base pointer is the same as the original one.
9068     if (!Ptr.equalBaseIndex(BasePtr))
9069       break;
9070
9071     // Check that the alignment is the same.
9072     if (Index->getAlignment() != St->getAlignment())
9073       break;
9074
9075     // The memory operands must not be volatile.
9076     if (Index->isVolatile() || Index->isIndexed())
9077       break;
9078
9079     // No truncation.
9080     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9081       if (St->isTruncatingStore())
9082         break;
9083
9084     // The stored memory type must be the same.
9085     if (Index->getMemoryVT() != MemVT)
9086       break;
9087
9088     // We do not allow unaligned stores because we want to prevent overriding
9089     // stores.
9090     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9091       break;
9092
9093     // We found a potential memory operand to merge.
9094     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9095
9096     // Find the next memory operand in the chain. If the next operand in the
9097     // chain is a store then move up and continue the scan with the next
9098     // memory operand. If the next operand is a load save it and use alias
9099     // information to check if it interferes with anything.
9100     SDNode *NextInChain = Index->getChain().getNode();
9101     while (1) {
9102       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9103         // We found a store node. Use it for the next iteration.
9104         Index = STn;
9105         break;
9106       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9107         if (Ldn->isVolatile()) {
9108           Index = nullptr;
9109           break;
9110         }
9111
9112         // Save the load node for later. Continue the scan.
9113         AliasLoadNodes.push_back(Ldn);
9114         NextInChain = Ldn->getChain().getNode();
9115         continue;
9116       } else {
9117         Index = nullptr;
9118         break;
9119       }
9120     }
9121   }
9122
9123   // Check if there is anything to merge.
9124   if (StoreNodes.size() < 2)
9125     return false;
9126
9127   // Sort the memory operands according to their distance from the base pointer.
9128   std::sort(StoreNodes.begin(), StoreNodes.end(),
9129             [](MemOpLink LHS, MemOpLink RHS) {
9130     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9131            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9132             LHS.SequenceNum > RHS.SequenceNum);
9133   });
9134
9135   // Scan the memory operations on the chain and find the first non-consecutive
9136   // store memory address.
9137   unsigned LastConsecutiveStore = 0;
9138   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9139   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9140
9141     // Check that the addresses are consecutive starting from the second
9142     // element in the list of stores.
9143     if (i > 0) {
9144       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9145       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9146         break;
9147     }
9148
9149     bool Alias = false;
9150     // Check if this store interferes with any of the loads that we found.
9151     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9152       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9153         Alias = true;
9154         break;
9155       }
9156     // We found a load that alias with this store. Stop the sequence.
9157     if (Alias)
9158       break;
9159
9160     // Mark this node as useful.
9161     LastConsecutiveStore = i;
9162   }
9163
9164   // The node with the lowest store address.
9165   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9166
9167   // Store the constants into memory as one consecutive store.
9168   if (!IsLoadSrc) {
9169     unsigned LastLegalType = 0;
9170     unsigned LastLegalVectorType = 0;
9171     bool NonZero = false;
9172     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9173       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9174       SDValue StoredVal = St->getValue();
9175
9176       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9177         NonZero |= !C->isNullValue();
9178       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9179         NonZero |= !C->getConstantFPValue()->isNullValue();
9180       } else {
9181         // Non-constant.
9182         break;
9183       }
9184
9185       // Find a legal type for the constant store.
9186       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9187       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9188       if (TLI.isTypeLegal(StoreTy))
9189         LastLegalType = i+1;
9190       // Or check whether a truncstore is legal.
9191       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9192                TargetLowering::TypePromoteInteger) {
9193         EVT LegalizedStoredValueTy =
9194           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9195         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9196           LastLegalType = i+1;
9197       }
9198
9199       // Find a legal type for the vector store.
9200       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9201       if (TLI.isTypeLegal(Ty))
9202         LastLegalVectorType = i + 1;
9203     }
9204
9205     // We only use vectors if the constant is known to be zero and the
9206     // function is not marked with the noimplicitfloat attribute.
9207     if (NonZero || NoVectors)
9208       LastLegalVectorType = 0;
9209
9210     // Check if we found a legal integer type to store.
9211     if (LastLegalType == 0 && LastLegalVectorType == 0)
9212       return false;
9213
9214     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9215     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9216
9217     // Make sure we have something to merge.
9218     if (NumElem < 2)
9219       return false;
9220
9221     unsigned EarliestNodeUsed = 0;
9222     for (unsigned i=0; i < NumElem; ++i) {
9223       // Find a chain for the new wide-store operand. Notice that some
9224       // of the store nodes that we found may not be selected for inclusion
9225       // in the wide store. The chain we use needs to be the chain of the
9226       // earliest store node which is *used* and replaced by the wide store.
9227       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9228         EarliestNodeUsed = i;
9229     }
9230
9231     // The earliest Node in the DAG.
9232     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9233     SDLoc DL(StoreNodes[0].MemNode);
9234
9235     SDValue StoredVal;
9236     if (UseVector) {
9237       // Find a legal type for the vector store.
9238       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9239       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9240       StoredVal = DAG.getConstant(0, Ty);
9241     } else {
9242       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9243       APInt StoreInt(StoreBW, 0);
9244
9245       // Construct a single integer constant which is made of the smaller
9246       // constant inputs.
9247       bool IsLE = TLI.isLittleEndian();
9248       for (unsigned i = 0; i < NumElem ; ++i) {
9249         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9250         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9251         SDValue Val = St->getValue();
9252         StoreInt<<=ElementSizeBytes*8;
9253         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9254           StoreInt|=C->getAPIntValue().zext(StoreBW);
9255         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9256           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9257         } else {
9258           assert(false && "Invalid constant element type");
9259         }
9260       }
9261
9262       // Create the new Load and Store operations.
9263       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9264       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9265     }
9266
9267     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9268                                     FirstInChain->getBasePtr(),
9269                                     FirstInChain->getPointerInfo(),
9270                                     false, false,
9271                                     FirstInChain->getAlignment());
9272
9273     // Replace the first store with the new store
9274     CombineTo(EarliestOp, NewStore);
9275     // Erase all other stores.
9276     for (unsigned i = 0; i < NumElem ; ++i) {
9277       if (StoreNodes[i].MemNode == EarliestOp)
9278         continue;
9279       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9280       // ReplaceAllUsesWith will replace all uses that existed when it was
9281       // called, but graph optimizations may cause new ones to appear. For
9282       // example, the case in pr14333 looks like
9283       //
9284       //  St's chain -> St -> another store -> X
9285       //
9286       // And the only difference from St to the other store is the chain.
9287       // When we change it's chain to be St's chain they become identical,
9288       // get CSEed and the net result is that X is now a use of St.
9289       // Since we know that St is redundant, just iterate.
9290       while (!St->use_empty())
9291         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9292       removeFromWorkList(St);
9293       DAG.DeleteNode(St);
9294     }
9295
9296     return true;
9297   }
9298
9299   // Below we handle the case of multiple consecutive stores that
9300   // come from multiple consecutive loads. We merge them into a single
9301   // wide load and a single wide store.
9302
9303   // Look for load nodes which are used by the stored values.
9304   SmallVector<MemOpLink, 8> LoadNodes;
9305
9306   // Find acceptable loads. Loads need to have the same chain (token factor),
9307   // must not be zext, volatile, indexed, and they must be consecutive.
9308   BaseIndexOffset LdBasePtr;
9309   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9310     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9311     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9312     if (!Ld) break;
9313
9314     // Loads must only have one use.
9315     if (!Ld->hasNUsesOfValue(1, 0))
9316       break;
9317
9318     // Check that the alignment is the same as the stores.
9319     if (Ld->getAlignment() != St->getAlignment())
9320       break;
9321
9322     // The memory operands must not be volatile.
9323     if (Ld->isVolatile() || Ld->isIndexed())
9324       break;
9325
9326     // We do not accept ext loads.
9327     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9328       break;
9329
9330     // The stored memory type must be the same.
9331     if (Ld->getMemoryVT() != MemVT)
9332       break;
9333
9334     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9335     // If this is not the first ptr that we check.
9336     if (LdBasePtr.Base.getNode()) {
9337       // The base ptr must be the same.
9338       if (!LdPtr.equalBaseIndex(LdBasePtr))
9339         break;
9340     } else {
9341       // Check that all other base pointers are the same as this one.
9342       LdBasePtr = LdPtr;
9343     }
9344
9345     // We found a potential memory operand to merge.
9346     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9347   }
9348
9349   if (LoadNodes.size() < 2)
9350     return false;
9351
9352   // Scan the memory operations on the chain and find the first non-consecutive
9353   // load memory address. These variables hold the index in the store node
9354   // array.
9355   unsigned LastConsecutiveLoad = 0;
9356   // This variable refers to the size and not index in the array.
9357   unsigned LastLegalVectorType = 0;
9358   unsigned LastLegalIntegerType = 0;
9359   StartAddress = LoadNodes[0].OffsetFromBase;
9360   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9361   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9362     // All loads much share the same chain.
9363     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9364       break;
9365
9366     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9367     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9368       break;
9369     LastConsecutiveLoad = i;
9370
9371     // Find a legal type for the vector store.
9372     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9373     if (TLI.isTypeLegal(StoreTy))
9374       LastLegalVectorType = i + 1;
9375
9376     // Find a legal type for the integer store.
9377     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9378     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9379     if (TLI.isTypeLegal(StoreTy))
9380       LastLegalIntegerType = i + 1;
9381     // Or check whether a truncstore and extload is legal.
9382     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9383              TargetLowering::TypePromoteInteger) {
9384       EVT LegalizedStoredValueTy =
9385         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9386       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9387           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9388           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9389           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9390         LastLegalIntegerType = i+1;
9391     }
9392   }
9393
9394   // Only use vector types if the vector type is larger than the integer type.
9395   // If they are the same, use integers.
9396   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9397   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9398
9399   // We add +1 here because the LastXXX variables refer to location while
9400   // the NumElem refers to array/index size.
9401   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9402   NumElem = std::min(LastLegalType, NumElem);
9403
9404   if (NumElem < 2)
9405     return false;
9406
9407   // The earliest Node in the DAG.
9408   unsigned EarliestNodeUsed = 0;
9409   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9410   for (unsigned i=1; i<NumElem; ++i) {
9411     // Find a chain for the new wide-store operand. Notice that some
9412     // of the store nodes that we found may not be selected for inclusion
9413     // in the wide store. The chain we use needs to be the chain of the
9414     // earliest store node which is *used* and replaced by the wide store.
9415     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9416       EarliestNodeUsed = i;
9417   }
9418
9419   // Find if it is better to use vectors or integers to load and store
9420   // to memory.
9421   EVT JointMemOpVT;
9422   if (UseVectorTy) {
9423     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9424   } else {
9425     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9426     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9427   }
9428
9429   SDLoc LoadDL(LoadNodes[0].MemNode);
9430   SDLoc StoreDL(StoreNodes[0].MemNode);
9431
9432   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9433   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9434                                 FirstLoad->getChain(),
9435                                 FirstLoad->getBasePtr(),
9436                                 FirstLoad->getPointerInfo(),
9437                                 false, false, false,
9438                                 FirstLoad->getAlignment());
9439
9440   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9441                                   FirstInChain->getBasePtr(),
9442                                   FirstInChain->getPointerInfo(), false, false,
9443                                   FirstInChain->getAlignment());
9444
9445   // Replace one of the loads with the new load.
9446   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9447   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9448                                 SDValue(NewLoad.getNode(), 1));
9449
9450   // Remove the rest of the load chains.
9451   for (unsigned i = 1; i < NumElem ; ++i) {
9452     // Replace all chain users of the old load nodes with the chain of the new
9453     // load node.
9454     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9455     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9456   }
9457
9458   // Replace the first store with the new store.
9459   CombineTo(EarliestOp, NewStore);
9460   // Erase all other stores.
9461   for (unsigned i = 0; i < NumElem ; ++i) {
9462     // Remove all Store nodes.
9463     if (StoreNodes[i].MemNode == EarliestOp)
9464       continue;
9465     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9466     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9467     removeFromWorkList(St);
9468     DAG.DeleteNode(St);
9469   }
9470
9471   return true;
9472 }
9473
9474 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9475   StoreSDNode *ST  = cast<StoreSDNode>(N);
9476   SDValue Chain = ST->getChain();
9477   SDValue Value = ST->getValue();
9478   SDValue Ptr   = ST->getBasePtr();
9479
9480   // If this is a store of a bit convert, store the input value if the
9481   // resultant store does not need a higher alignment than the original.
9482   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9483       ST->isUnindexed()) {
9484     unsigned OrigAlign = ST->getAlignment();
9485     EVT SVT = Value.getOperand(0).getValueType();
9486     unsigned Align = TLI.getDataLayout()->
9487       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9488     if (Align <= OrigAlign &&
9489         ((!LegalOperations && !ST->isVolatile()) ||
9490          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9491       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9492                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9493                           ST->isNonTemporal(), OrigAlign,
9494                           ST->getTBAAInfo());
9495   }
9496
9497   // Turn 'store undef, Ptr' -> nothing.
9498   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9499     return Chain;
9500
9501   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9502   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9503     // NOTE: If the original store is volatile, this transform must not increase
9504     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9505     // processor operation but an i64 (which is not legal) requires two.  So the
9506     // transform should not be done in this case.
9507     if (Value.getOpcode() != ISD::TargetConstantFP) {
9508       SDValue Tmp;
9509       switch (CFP->getSimpleValueType(0).SimpleTy) {
9510       default: llvm_unreachable("Unknown FP type");
9511       case MVT::f16:    // We don't do this for these yet.
9512       case MVT::f80:
9513       case MVT::f128:
9514       case MVT::ppcf128:
9515         break;
9516       case MVT::f32:
9517         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9518             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9519           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9520                               bitcastToAPInt().getZExtValue(), MVT::i32);
9521           return DAG.getStore(Chain, SDLoc(N), Tmp,
9522                               Ptr, ST->getMemOperand());
9523         }
9524         break;
9525       case MVT::f64:
9526         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9527              !ST->isVolatile()) ||
9528             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9529           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9530                                 getZExtValue(), MVT::i64);
9531           return DAG.getStore(Chain, SDLoc(N), Tmp,
9532                               Ptr, ST->getMemOperand());
9533         }
9534
9535         if (!ST->isVolatile() &&
9536             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9537           // Many FP stores are not made apparent until after legalize, e.g. for
9538           // argument passing.  Since this is so common, custom legalize the
9539           // 64-bit integer store into two 32-bit stores.
9540           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9541           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9542           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9543           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9544
9545           unsigned Alignment = ST->getAlignment();
9546           bool isVolatile = ST->isVolatile();
9547           bool isNonTemporal = ST->isNonTemporal();
9548           const MDNode *TBAAInfo = ST->getTBAAInfo();
9549
9550           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9551                                      Ptr, ST->getPointerInfo(),
9552                                      isVolatile, isNonTemporal,
9553                                      ST->getAlignment(), TBAAInfo);
9554           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9555                             DAG.getConstant(4, Ptr.getValueType()));
9556           Alignment = MinAlign(Alignment, 4U);
9557           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9558                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9559                                      isVolatile, isNonTemporal,
9560                                      Alignment, TBAAInfo);
9561           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9562                              St0, St1);
9563         }
9564
9565         break;
9566       }
9567     }
9568   }
9569
9570   // Try to infer better alignment information than the store already has.
9571   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9572     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9573       if (Align > ST->getAlignment())
9574         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9575                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9576                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9577                                  ST->getTBAAInfo());
9578     }
9579   }
9580
9581   // Try transforming a pair floating point load / store ops to integer
9582   // load / store ops.
9583   SDValue NewST = TransformFPLoadStorePair(N);
9584   if (NewST.getNode())
9585     return NewST;
9586
9587   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9588     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9589 #ifndef NDEBUG
9590   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9591       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9592     UseAA = false;
9593 #endif
9594   if (UseAA && ST->isUnindexed()) {
9595     // Walk up chain skipping non-aliasing memory nodes.
9596     SDValue BetterChain = FindBetterChain(N, Chain);
9597
9598     // If there is a better chain.
9599     if (Chain != BetterChain) {
9600       SDValue ReplStore;
9601
9602       // Replace the chain to avoid dependency.
9603       if (ST->isTruncatingStore()) {
9604         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9605                                       ST->getMemoryVT(), ST->getMemOperand());
9606       } else {
9607         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9608                                  ST->getMemOperand());
9609       }
9610
9611       // Create token to keep both nodes around.
9612       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9613                                   MVT::Other, Chain, ReplStore);
9614
9615       // Make sure the new and old chains are cleaned up.
9616       AddToWorkList(Token.getNode());
9617
9618       // Don't add users to work list.
9619       return CombineTo(N, Token, false);
9620     }
9621   }
9622
9623   // Try transforming N to an indexed store.
9624   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9625     return SDValue(N, 0);
9626
9627   // FIXME: is there such a thing as a truncating indexed store?
9628   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9629       Value.getValueType().isInteger()) {
9630     // See if we can simplify the input to this truncstore with knowledge that
9631     // only the low bits are being used.  For example:
9632     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9633     SDValue Shorter =
9634       GetDemandedBits(Value,
9635                       APInt::getLowBitsSet(
9636                         Value.getValueType().getScalarType().getSizeInBits(),
9637                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9638     AddToWorkList(Value.getNode());
9639     if (Shorter.getNode())
9640       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9641                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9642
9643     // Otherwise, see if we can simplify the operation with
9644     // SimplifyDemandedBits, which only works if the value has a single use.
9645     if (SimplifyDemandedBits(Value,
9646                         APInt::getLowBitsSet(
9647                           Value.getValueType().getScalarType().getSizeInBits(),
9648                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9649       return SDValue(N, 0);
9650   }
9651
9652   // If this is a load followed by a store to the same location, then the store
9653   // is dead/noop.
9654   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9655     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9656         ST->isUnindexed() && !ST->isVolatile() &&
9657         // There can't be any side effects between the load and store, such as
9658         // a call or store.
9659         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9660       // The store is dead, remove it.
9661       return Chain;
9662     }
9663   }
9664
9665   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9666   // truncating store.  We can do this even if this is already a truncstore.
9667   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9668       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9669       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9670                             ST->getMemoryVT())) {
9671     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9672                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9673   }
9674
9675   // Only perform this optimization before the types are legal, because we
9676   // don't want to perform this optimization on every DAGCombine invocation.
9677   if (!LegalTypes) {
9678     bool EverChanged = false;
9679
9680     do {
9681       // There can be multiple store sequences on the same chain.
9682       // Keep trying to merge store sequences until we are unable to do so
9683       // or until we merge the last store on the chain.
9684       bool Changed = MergeConsecutiveStores(ST);
9685       EverChanged |= Changed;
9686       if (!Changed) break;
9687     } while (ST->getOpcode() != ISD::DELETED_NODE);
9688
9689     if (EverChanged)
9690       return SDValue(N, 0);
9691   }
9692
9693   return ReduceLoadOpStoreWidth(N);
9694 }
9695
9696 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9697   SDValue InVec = N->getOperand(0);
9698   SDValue InVal = N->getOperand(1);
9699   SDValue EltNo = N->getOperand(2);
9700   SDLoc dl(N);
9701
9702   // If the inserted element is an UNDEF, just use the input vector.
9703   if (InVal.getOpcode() == ISD::UNDEF)
9704     return InVec;
9705
9706   EVT VT = InVec.getValueType();
9707
9708   // If we can't generate a legal BUILD_VECTOR, exit
9709   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9710     return SDValue();
9711
9712   // Check that we know which element is being inserted
9713   if (!isa<ConstantSDNode>(EltNo))
9714     return SDValue();
9715   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9716
9717   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9718   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9719   // vector elements.
9720   SmallVector<SDValue, 8> Ops;
9721   // Do not combine these two vectors if the output vector will not replace
9722   // the input vector.
9723   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9724     Ops.append(InVec.getNode()->op_begin(),
9725                InVec.getNode()->op_end());
9726   } else if (InVec.getOpcode() == ISD::UNDEF) {
9727     unsigned NElts = VT.getVectorNumElements();
9728     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9729   } else {
9730     return SDValue();
9731   }
9732
9733   // Insert the element
9734   if (Elt < Ops.size()) {
9735     // All the operands of BUILD_VECTOR must have the same type;
9736     // we enforce that here.
9737     EVT OpVT = Ops[0].getValueType();
9738     if (InVal.getValueType() != OpVT)
9739       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9740                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9741                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9742     Ops[Elt] = InVal;
9743   }
9744
9745   // Return the new vector
9746   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9747 }
9748
9749 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9750     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9751   EVT ResultVT = EVE->getValueType(0);
9752   EVT VecEltVT = InVecVT.getVectorElementType();
9753   unsigned Align = OriginalLoad->getAlignment();
9754   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9755       VecEltVT.getTypeForEVT(*DAG.getContext()));
9756
9757   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9758     return SDValue();
9759
9760   Align = NewAlign;
9761
9762   SDValue NewPtr = OriginalLoad->getBasePtr();
9763   SDValue Offset;
9764   EVT PtrType = NewPtr.getValueType();
9765   MachinePointerInfo MPI;
9766   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9767     int Elt = ConstEltNo->getZExtValue();
9768     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9769     if (TLI.isBigEndian())
9770       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9771     Offset = DAG.getConstant(PtrOff, PtrType);
9772     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9773   } else {
9774     Offset = DAG.getNode(
9775         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9776         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9777     if (TLI.isBigEndian())
9778       Offset = DAG.getNode(
9779           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9780           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9781     MPI = OriginalLoad->getPointerInfo();
9782   }
9783   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9784
9785   // The replacement we need to do here is a little tricky: we need to
9786   // replace an extractelement of a load with a load.
9787   // Use ReplaceAllUsesOfValuesWith to do the replacement.
9788   // Note that this replacement assumes that the extractvalue is the only
9789   // use of the load; that's okay because we don't want to perform this
9790   // transformation in other cases anyway.
9791   SDValue Load;
9792   SDValue Chain;
9793   if (ResultVT.bitsGT(VecEltVT)) {
9794     // If the result type of vextract is wider than the load, then issue an
9795     // extending load instead.
9796     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9797                                    ? ISD::ZEXTLOAD
9798                                    : ISD::EXTLOAD;
9799     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(),
9800                           NewPtr, MPI, VecEltVT, OriginalLoad->isVolatile(),
9801                           OriginalLoad->isNonTemporal(), Align,
9802                           OriginalLoad->getTBAAInfo());
9803     Chain = Load.getValue(1);
9804   } else {
9805     Load = DAG.getLoad(
9806         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9807         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9808         OriginalLoad->isInvariant(), Align, OriginalLoad->getTBAAInfo());
9809     Chain = Load.getValue(1);
9810     if (ResultVT.bitsLT(VecEltVT))
9811       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9812     else
9813       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9814   }
9815   WorkListRemover DeadNodes(*this);
9816   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9817   SDValue To[] = { Load, Chain };
9818   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9819   // Since we're explicitly calling ReplaceAllUses, add the new node to the
9820   // worklist explicitly as well.
9821   AddToWorkList(Load.getNode());
9822   AddUsersToWorkList(Load.getNode()); // Add users too
9823   // Make sure to revisit this node to clean it up; it will usually be dead.
9824   AddToWorkList(EVE);
9825   ++OpsNarrowed;
9826   return SDValue(EVE, 0);
9827 }
9828
9829 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9830   // (vextract (scalar_to_vector val, 0) -> val
9831   SDValue InVec = N->getOperand(0);
9832   EVT VT = InVec.getValueType();
9833   EVT NVT = N->getValueType(0);
9834
9835   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9836     // Check if the result type doesn't match the inserted element type. A
9837     // SCALAR_TO_VECTOR may truncate the inserted element and the
9838     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9839     SDValue InOp = InVec.getOperand(0);
9840     if (InOp.getValueType() != NVT) {
9841       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9842       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9843     }
9844     return InOp;
9845   }
9846
9847   SDValue EltNo = N->getOperand(1);
9848   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9849
9850   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9851   // We only perform this optimization before the op legalization phase because
9852   // we may introduce new vector instructions which are not backed by TD
9853   // patterns. For example on AVX, extracting elements from a wide vector
9854   // without using extract_subvector. However, if we can find an underlying
9855   // scalar value, then we can always use that.
9856   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9857       && ConstEltNo) {
9858     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9859     int NumElem = VT.getVectorNumElements();
9860     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9861     // Find the new index to extract from.
9862     int OrigElt = SVOp->getMaskElt(Elt);
9863
9864     // Extracting an undef index is undef.
9865     if (OrigElt == -1)
9866       return DAG.getUNDEF(NVT);
9867
9868     // Select the right vector half to extract from.
9869     SDValue SVInVec;
9870     if (OrigElt < NumElem) {
9871       SVInVec = InVec->getOperand(0);
9872     } else {
9873       SVInVec = InVec->getOperand(1);
9874       OrigElt -= NumElem;
9875     }
9876
9877     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9878       SDValue InOp = SVInVec.getOperand(OrigElt);
9879       if (InOp.getValueType() != NVT) {
9880         assert(InOp.getValueType().isInteger() && NVT.isInteger());
9881         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9882       }
9883
9884       return InOp;
9885     }
9886
9887     // FIXME: We should handle recursing on other vector shuffles and
9888     // scalar_to_vector here as well.
9889
9890     if (!LegalOperations) {
9891       EVT IndexTy = TLI.getVectorIdxTy();
9892       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9893                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
9894     }
9895   }
9896
9897   bool BCNumEltsChanged = false;
9898   EVT ExtVT = VT.getVectorElementType();
9899   EVT LVT = ExtVT;
9900
9901   // If the result of load has to be truncated, then it's not necessarily
9902   // profitable.
9903   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9904     return SDValue();
9905
9906   if (InVec.getOpcode() == ISD::BITCAST) {
9907     // Don't duplicate a load with other uses.
9908     if (!InVec.hasOneUse())
9909       return SDValue();
9910
9911     EVT BCVT = InVec.getOperand(0).getValueType();
9912     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9913       return SDValue();
9914     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9915       BCNumEltsChanged = true;
9916     InVec = InVec.getOperand(0);
9917     ExtVT = BCVT.getVectorElementType();
9918   }
9919
9920   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
9921   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
9922       ISD::isNormalLoad(InVec.getNode())) {
9923     SDValue Index = N->getOperand(1);
9924     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
9925       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
9926                                                            OrigLoad);
9927   }
9928
9929   // Perform only after legalization to ensure build_vector / vector_shuffle
9930   // optimizations have already been done.
9931   if (!LegalOperations) return SDValue();
9932
9933   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9934   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9935   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9936
9937   if (ConstEltNo) {
9938     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9939
9940     LoadSDNode *LN0 = nullptr;
9941     const ShuffleVectorSDNode *SVN = nullptr;
9942     if (ISD::isNormalLoad(InVec.getNode())) {
9943       LN0 = cast<LoadSDNode>(InVec);
9944     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9945                InVec.getOperand(0).getValueType() == ExtVT &&
9946                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9947       // Don't duplicate a load with other uses.
9948       if (!InVec.hasOneUse())
9949         return SDValue();
9950
9951       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9952     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9953       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9954       // =>
9955       // (load $addr+1*size)
9956
9957       // Don't duplicate a load with other uses.
9958       if (!InVec.hasOneUse())
9959         return SDValue();
9960
9961       // If the bit convert changed the number of elements, it is unsafe
9962       // to examine the mask.
9963       if (BCNumEltsChanged)
9964         return SDValue();
9965
9966       // Select the input vector, guarding against out of range extract vector.
9967       unsigned NumElems = VT.getVectorNumElements();
9968       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9969       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9970
9971       if (InVec.getOpcode() == ISD::BITCAST) {
9972         // Don't duplicate a load with other uses.
9973         if (!InVec.hasOneUse())
9974           return SDValue();
9975
9976         InVec = InVec.getOperand(0);
9977       }
9978       if (ISD::isNormalLoad(InVec.getNode())) {
9979         LN0 = cast<LoadSDNode>(InVec);
9980         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9981         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
9982       }
9983     }
9984
9985     // Make sure we found a non-volatile load and the extractelement is
9986     // the only use.
9987     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9988       return SDValue();
9989
9990     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9991     if (Elt == -1)
9992       return DAG.getUNDEF(LVT);
9993
9994     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
9995   }
9996
9997   return SDValue();
9998 }
9999
10000 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10001 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10002   // We perform this optimization post type-legalization because
10003   // the type-legalizer often scalarizes integer-promoted vectors.
10004   // Performing this optimization before may create bit-casts which
10005   // will be type-legalized to complex code sequences.
10006   // We perform this optimization only before the operation legalizer because we
10007   // may introduce illegal operations.
10008   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10009     return SDValue();
10010
10011   unsigned NumInScalars = N->getNumOperands();
10012   SDLoc dl(N);
10013   EVT VT = N->getValueType(0);
10014
10015   // Check to see if this is a BUILD_VECTOR of a bunch of values
10016   // which come from any_extend or zero_extend nodes. If so, we can create
10017   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10018   // optimizations. We do not handle sign-extend because we can't fill the sign
10019   // using shuffles.
10020   EVT SourceType = MVT::Other;
10021   bool AllAnyExt = true;
10022
10023   for (unsigned i = 0; i != NumInScalars; ++i) {
10024     SDValue In = N->getOperand(i);
10025     // Ignore undef inputs.
10026     if (In.getOpcode() == ISD::UNDEF) continue;
10027
10028     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10029     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10030
10031     // Abort if the element is not an extension.
10032     if (!ZeroExt && !AnyExt) {
10033       SourceType = MVT::Other;
10034       break;
10035     }
10036
10037     // The input is a ZeroExt or AnyExt. Check the original type.
10038     EVT InTy = In.getOperand(0).getValueType();
10039
10040     // Check that all of the widened source types are the same.
10041     if (SourceType == MVT::Other)
10042       // First time.
10043       SourceType = InTy;
10044     else if (InTy != SourceType) {
10045       // Multiple income types. Abort.
10046       SourceType = MVT::Other;
10047       break;
10048     }
10049
10050     // Check if all of the extends are ANY_EXTENDs.
10051     AllAnyExt &= AnyExt;
10052   }
10053
10054   // In order to have valid types, all of the inputs must be extended from the
10055   // same source type and all of the inputs must be any or zero extend.
10056   // Scalar sizes must be a power of two.
10057   EVT OutScalarTy = VT.getScalarType();
10058   bool ValidTypes = SourceType != MVT::Other &&
10059                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10060                  isPowerOf2_32(SourceType.getSizeInBits());
10061
10062   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10063   // turn into a single shuffle instruction.
10064   if (!ValidTypes)
10065     return SDValue();
10066
10067   bool isLE = TLI.isLittleEndian();
10068   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10069   assert(ElemRatio > 1 && "Invalid element size ratio");
10070   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10071                                DAG.getConstant(0, SourceType);
10072
10073   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10074   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10075
10076   // Populate the new build_vector
10077   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10078     SDValue Cast = N->getOperand(i);
10079     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10080             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10081             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10082     SDValue In;
10083     if (Cast.getOpcode() == ISD::UNDEF)
10084       In = DAG.getUNDEF(SourceType);
10085     else
10086       In = Cast->getOperand(0);
10087     unsigned Index = isLE ? (i * ElemRatio) :
10088                             (i * ElemRatio + (ElemRatio - 1));
10089
10090     assert(Index < Ops.size() && "Invalid index");
10091     Ops[Index] = In;
10092   }
10093
10094   // The type of the new BUILD_VECTOR node.
10095   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10096   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10097          "Invalid vector size");
10098   // Check if the new vector type is legal.
10099   if (!isTypeLegal(VecVT)) return SDValue();
10100
10101   // Make the new BUILD_VECTOR.
10102   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10103
10104   // The new BUILD_VECTOR node has the potential to be further optimized.
10105   AddToWorkList(BV.getNode());
10106   // Bitcast to the desired type.
10107   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10108 }
10109
10110 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10111   EVT VT = N->getValueType(0);
10112
10113   unsigned NumInScalars = N->getNumOperands();
10114   SDLoc dl(N);
10115
10116   EVT SrcVT = MVT::Other;
10117   unsigned Opcode = ISD::DELETED_NODE;
10118   unsigned NumDefs = 0;
10119
10120   for (unsigned i = 0; i != NumInScalars; ++i) {
10121     SDValue In = N->getOperand(i);
10122     unsigned Opc = In.getOpcode();
10123
10124     if (Opc == ISD::UNDEF)
10125       continue;
10126
10127     // If all scalar values are floats and converted from integers.
10128     if (Opcode == ISD::DELETED_NODE &&
10129         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10130       Opcode = Opc;
10131     }
10132
10133     if (Opc != Opcode)
10134       return SDValue();
10135
10136     EVT InVT = In.getOperand(0).getValueType();
10137
10138     // If all scalar values are typed differently, bail out. It's chosen to
10139     // simplify BUILD_VECTOR of integer types.
10140     if (SrcVT == MVT::Other)
10141       SrcVT = InVT;
10142     if (SrcVT != InVT)
10143       return SDValue();
10144     NumDefs++;
10145   }
10146
10147   // If the vector has just one element defined, it's not worth to fold it into
10148   // a vectorized one.
10149   if (NumDefs < 2)
10150     return SDValue();
10151
10152   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10153          && "Should only handle conversion from integer to float.");
10154   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10155
10156   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10157
10158   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10159     return SDValue();
10160
10161   SmallVector<SDValue, 8> Opnds;
10162   for (unsigned i = 0; i != NumInScalars; ++i) {
10163     SDValue In = N->getOperand(i);
10164
10165     if (In.getOpcode() == ISD::UNDEF)
10166       Opnds.push_back(DAG.getUNDEF(SrcVT));
10167     else
10168       Opnds.push_back(In.getOperand(0));
10169   }
10170   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10171   AddToWorkList(BV.getNode());
10172
10173   return DAG.getNode(Opcode, dl, VT, BV);
10174 }
10175
10176 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10177   unsigned NumInScalars = N->getNumOperands();
10178   SDLoc dl(N);
10179   EVT VT = N->getValueType(0);
10180
10181   // A vector built entirely of undefs is undef.
10182   if (ISD::allOperandsUndef(N))
10183     return DAG.getUNDEF(VT);
10184
10185   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10186   if (V.getNode())
10187     return V;
10188
10189   V = reduceBuildVecConvertToConvertBuildVec(N);
10190   if (V.getNode())
10191     return V;
10192
10193   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10194   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10195   // at most two distinct vectors, turn this into a shuffle node.
10196
10197   // May only combine to shuffle after legalize if shuffle is legal.
10198   if (LegalOperations &&
10199       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10200     return SDValue();
10201
10202   SDValue VecIn1, VecIn2;
10203   for (unsigned i = 0; i != NumInScalars; ++i) {
10204     // Ignore undef inputs.
10205     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10206
10207     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10208     // constant index, bail out.
10209     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10210         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10211       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10212       break;
10213     }
10214
10215     // We allow up to two distinct input vectors.
10216     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10217     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10218       continue;
10219
10220     if (!VecIn1.getNode()) {
10221       VecIn1 = ExtractedFromVec;
10222     } else if (!VecIn2.getNode()) {
10223       VecIn2 = ExtractedFromVec;
10224     } else {
10225       // Too many inputs.
10226       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10227       break;
10228     }
10229   }
10230
10231   // If everything is good, we can make a shuffle operation.
10232   if (VecIn1.getNode()) {
10233     SmallVector<int, 8> Mask;
10234     for (unsigned i = 0; i != NumInScalars; ++i) {
10235       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10236         Mask.push_back(-1);
10237         continue;
10238       }
10239
10240       // If extracting from the first vector, just use the index directly.
10241       SDValue Extract = N->getOperand(i);
10242       SDValue ExtVal = Extract.getOperand(1);
10243       if (Extract.getOperand(0) == VecIn1) {
10244         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10245         if (ExtIndex > VT.getVectorNumElements())
10246           return SDValue();
10247
10248         Mask.push_back(ExtIndex);
10249         continue;
10250       }
10251
10252       // Otherwise, use InIdx + VecSize
10253       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10254       Mask.push_back(Idx+NumInScalars);
10255     }
10256
10257     // We can't generate a shuffle node with mismatched input and output types.
10258     // Attempt to transform a single input vector to the correct type.
10259     if ((VT != VecIn1.getValueType())) {
10260       // We don't support shuffeling between TWO values of different types.
10261       if (VecIn2.getNode())
10262         return SDValue();
10263
10264       // We only support widening of vectors which are half the size of the
10265       // output registers. For example XMM->YMM widening on X86 with AVX.
10266       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10267         return SDValue();
10268
10269       // If the input vector type has a different base type to the output
10270       // vector type, bail out.
10271       if (VecIn1.getValueType().getVectorElementType() !=
10272           VT.getVectorElementType())
10273         return SDValue();
10274
10275       // Widen the input vector by adding undef values.
10276       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10277                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10278     }
10279
10280     // If VecIn2 is unused then change it to undef.
10281     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10282
10283     // Check that we were able to transform all incoming values to the same
10284     // type.
10285     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10286         VecIn1.getValueType() != VT)
10287           return SDValue();
10288
10289     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10290     if (!isTypeLegal(VT))
10291       return SDValue();
10292
10293     // Return the new VECTOR_SHUFFLE node.
10294     SDValue Ops[2];
10295     Ops[0] = VecIn1;
10296     Ops[1] = VecIn2;
10297     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10298   }
10299
10300   return SDValue();
10301 }
10302
10303 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10304   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10305   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10306   // inputs come from at most two distinct vectors, turn this into a shuffle
10307   // node.
10308
10309   // If we only have one input vector, we don't need to do any concatenation.
10310   if (N->getNumOperands() == 1)
10311     return N->getOperand(0);
10312
10313   // Check if all of the operands are undefs.
10314   EVT VT = N->getValueType(0);
10315   if (ISD::allOperandsUndef(N))
10316     return DAG.getUNDEF(VT);
10317
10318   // Optimize concat_vectors where one of the vectors is undef.
10319   if (N->getNumOperands() == 2 &&
10320       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10321     SDValue In = N->getOperand(0);
10322     assert(In.getValueType().isVector() && "Must concat vectors");
10323
10324     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10325     if (In->getOpcode() == ISD::BITCAST &&
10326         !In->getOperand(0)->getValueType(0).isVector()) {
10327       SDValue Scalar = In->getOperand(0);
10328       EVT SclTy = Scalar->getValueType(0);
10329
10330       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10331         return SDValue();
10332
10333       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10334                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10335       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10336         return SDValue();
10337
10338       SDLoc dl = SDLoc(N);
10339       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10340       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10341     }
10342   }
10343
10344   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10345   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10346   if (N->getNumOperands() == 2 &&
10347       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10348       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10349     EVT VT = N->getValueType(0);
10350     SDValue N0 = N->getOperand(0);
10351     SDValue N1 = N->getOperand(1);
10352     SmallVector<SDValue, 8> Opnds;
10353     unsigned BuildVecNumElts =  N0.getNumOperands();
10354
10355     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10356       Opnds.push_back(N0.getOperand(i));
10357     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10358       Opnds.push_back(N1.getOperand(i));
10359
10360     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10361   }
10362
10363   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10364   // nodes often generate nop CONCAT_VECTOR nodes.
10365   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10366   // place the incoming vectors at the exact same location.
10367   SDValue SingleSource = SDValue();
10368   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10369
10370   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10371     SDValue Op = N->getOperand(i);
10372
10373     if (Op.getOpcode() == ISD::UNDEF)
10374       continue;
10375
10376     // Check if this is the identity extract:
10377     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10378       return SDValue();
10379
10380     // Find the single incoming vector for the extract_subvector.
10381     if (SingleSource.getNode()) {
10382       if (Op.getOperand(0) != SingleSource)
10383         return SDValue();
10384     } else {
10385       SingleSource = Op.getOperand(0);
10386
10387       // Check the source type is the same as the type of the result.
10388       // If not, this concat may extend the vector, so we can not
10389       // optimize it away.
10390       if (SingleSource.getValueType() != N->getValueType(0))
10391         return SDValue();
10392     }
10393
10394     unsigned IdentityIndex = i * PartNumElem;
10395     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10396     // The extract index must be constant.
10397     if (!CS)
10398       return SDValue();
10399
10400     // Check that we are reading from the identity index.
10401     if (CS->getZExtValue() != IdentityIndex)
10402       return SDValue();
10403   }
10404
10405   if (SingleSource.getNode())
10406     return SingleSource;
10407
10408   return SDValue();
10409 }
10410
10411 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10412   EVT NVT = N->getValueType(0);
10413   SDValue V = N->getOperand(0);
10414
10415   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10416     // Combine:
10417     //    (extract_subvec (concat V1, V2, ...), i)
10418     // Into:
10419     //    Vi if possible
10420     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10421     // type.
10422     if (V->getOperand(0).getValueType() != NVT)
10423       return SDValue();
10424     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10425     unsigned NumElems = NVT.getVectorNumElements();
10426     assert((Idx % NumElems) == 0 &&
10427            "IDX in concat is not a multiple of the result vector length.");
10428     return V->getOperand(Idx / NumElems);
10429   }
10430
10431   // Skip bitcasting
10432   if (V->getOpcode() == ISD::BITCAST)
10433     V = V.getOperand(0);
10434
10435   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10436     SDLoc dl(N);
10437     // Handle only simple case where vector being inserted and vector
10438     // being extracted are of same type, and are half size of larger vectors.
10439     EVT BigVT = V->getOperand(0).getValueType();
10440     EVT SmallVT = V->getOperand(1).getValueType();
10441     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10442       return SDValue();
10443
10444     // Only handle cases where both indexes are constants with the same type.
10445     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10446     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10447
10448     if (InsIdx && ExtIdx &&
10449         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10450         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10451       // Combine:
10452       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10453       // Into:
10454       //    indices are equal or bit offsets are equal => V1
10455       //    otherwise => (extract_subvec V1, ExtIdx)
10456       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10457           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10458         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10459       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10460                          DAG.getNode(ISD::BITCAST, dl,
10461                                      N->getOperand(0).getValueType(),
10462                                      V->getOperand(0)), N->getOperand(1));
10463     }
10464   }
10465
10466   return SDValue();
10467 }
10468
10469 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10470 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10471   EVT VT = N->getValueType(0);
10472   unsigned NumElts = VT.getVectorNumElements();
10473
10474   SDValue N0 = N->getOperand(0);
10475   SDValue N1 = N->getOperand(1);
10476   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10477
10478   SmallVector<SDValue, 4> Ops;
10479   EVT ConcatVT = N0.getOperand(0).getValueType();
10480   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10481   unsigned NumConcats = NumElts / NumElemsPerConcat;
10482
10483   // Look at every vector that's inserted. We're looking for exact
10484   // subvector-sized copies from a concatenated vector
10485   for (unsigned I = 0; I != NumConcats; ++I) {
10486     // Make sure we're dealing with a copy.
10487     unsigned Begin = I * NumElemsPerConcat;
10488     bool AllUndef = true, NoUndef = true;
10489     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10490       if (SVN->getMaskElt(J) >= 0)
10491         AllUndef = false;
10492       else
10493         NoUndef = false;
10494     }
10495
10496     if (NoUndef) {
10497       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10498         return SDValue();
10499
10500       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10501         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10502           return SDValue();
10503
10504       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10505       if (FirstElt < N0.getNumOperands())
10506         Ops.push_back(N0.getOperand(FirstElt));
10507       else
10508         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10509
10510     } else if (AllUndef) {
10511       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10512     } else { // Mixed with general masks and undefs, can't do optimization.
10513       return SDValue();
10514     }
10515   }
10516
10517   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10518 }
10519
10520 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10521   EVT VT = N->getValueType(0);
10522   unsigned NumElts = VT.getVectorNumElements();
10523
10524   SDValue N0 = N->getOperand(0);
10525   SDValue N1 = N->getOperand(1);
10526
10527   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10528
10529   // Canonicalize shuffle undef, undef -> undef
10530   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10531     return DAG.getUNDEF(VT);
10532
10533   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10534
10535   // Canonicalize shuffle v, v -> v, undef
10536   if (N0 == N1) {
10537     SmallVector<int, 8> NewMask;
10538     for (unsigned i = 0; i != NumElts; ++i) {
10539       int Idx = SVN->getMaskElt(i);
10540       if (Idx >= (int)NumElts) Idx -= NumElts;
10541       NewMask.push_back(Idx);
10542     }
10543     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10544                                 &NewMask[0]);
10545   }
10546
10547   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10548   if (N0.getOpcode() == ISD::UNDEF) {
10549     SmallVector<int, 8> NewMask;
10550     for (unsigned i = 0; i != NumElts; ++i) {
10551       int Idx = SVN->getMaskElt(i);
10552       if (Idx >= 0) {
10553         if (Idx >= (int)NumElts)
10554           Idx -= NumElts;
10555         else
10556           Idx = -1; // remove reference to lhs
10557       }
10558       NewMask.push_back(Idx);
10559     }
10560     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10561                                 &NewMask[0]);
10562   }
10563
10564   // Remove references to rhs if it is undef
10565   if (N1.getOpcode() == ISD::UNDEF) {
10566     bool Changed = false;
10567     SmallVector<int, 8> NewMask;
10568     for (unsigned i = 0; i != NumElts; ++i) {
10569       int Idx = SVN->getMaskElt(i);
10570       if (Idx >= (int)NumElts) {
10571         Idx = -1;
10572         Changed = true;
10573       }
10574       NewMask.push_back(Idx);
10575     }
10576     if (Changed)
10577       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10578   }
10579
10580   // If it is a splat, check if the argument vector is another splat or a
10581   // build_vector with all scalar elements the same.
10582   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10583     SDNode *V = N0.getNode();
10584
10585     // If this is a bit convert that changes the element type of the vector but
10586     // not the number of vector elements, look through it.  Be careful not to
10587     // look though conversions that change things like v4f32 to v2f64.
10588     if (V->getOpcode() == ISD::BITCAST) {
10589       SDValue ConvInput = V->getOperand(0);
10590       if (ConvInput.getValueType().isVector() &&
10591           ConvInput.getValueType().getVectorNumElements() == NumElts)
10592         V = ConvInput.getNode();
10593     }
10594
10595     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10596       assert(V->getNumOperands() == NumElts &&
10597              "BUILD_VECTOR has wrong number of operands");
10598       SDValue Base;
10599       bool AllSame = true;
10600       for (unsigned i = 0; i != NumElts; ++i) {
10601         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10602           Base = V->getOperand(i);
10603           break;
10604         }
10605       }
10606       // Splat of <u, u, u, u>, return <u, u, u, u>
10607       if (!Base.getNode())
10608         return N0;
10609       for (unsigned i = 0; i != NumElts; ++i) {
10610         if (V->getOperand(i) != Base) {
10611           AllSame = false;
10612           break;
10613         }
10614       }
10615       // Splat of <x, x, x, x>, return <x, x, x, x>
10616       if (AllSame)
10617         return N0;
10618     }
10619   }
10620
10621   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10622       Level < AfterLegalizeVectorOps &&
10623       (N1.getOpcode() == ISD::UNDEF ||
10624       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10625        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10626     SDValue V = partitionShuffleOfConcats(N, DAG);
10627
10628     if (V.getNode())
10629       return V;
10630   }
10631
10632   // If this shuffle node is simply a swizzle of another shuffle node,
10633   // and it reverses the swizzle of the previous shuffle then we can
10634   // optimize shuffle(shuffle(x, undef), undef) -> x.
10635   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10636       N1.getOpcode() == ISD::UNDEF) {
10637
10638     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10639
10640     // Shuffle nodes can only reverse shuffles with a single non-undef value.
10641     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10642       return SDValue();
10643
10644     // The incoming shuffle must be of the same type as the result of the
10645     // current shuffle.
10646     assert(OtherSV->getOperand(0).getValueType() == VT &&
10647            "Shuffle types don't match");
10648
10649     for (unsigned i = 0; i != NumElts; ++i) {
10650       int Idx = SVN->getMaskElt(i);
10651       assert(Idx < (int)NumElts && "Index references undef operand");
10652       // Next, this index comes from the first value, which is the incoming
10653       // shuffle. Adopt the incoming index.
10654       if (Idx >= 0)
10655         Idx = OtherSV->getMaskElt(Idx);
10656
10657       // The combined shuffle must map each index to itself.
10658       if (Idx >= 0 && (unsigned)Idx != i)
10659         return SDValue();
10660     }
10661
10662     return OtherSV->getOperand(0);
10663   }
10664
10665   return SDValue();
10666 }
10667
10668 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10669   SDValue N0 = N->getOperand(0);
10670   SDValue N2 = N->getOperand(2);
10671
10672   // If the input vector is a concatenation, and the insert replaces
10673   // one of the halves, we can optimize into a single concat_vectors.
10674   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10675       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10676     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10677     EVT VT = N->getValueType(0);
10678
10679     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10680     // (concat_vectors Z, Y)
10681     if (InsIdx == 0)
10682       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10683                          N->getOperand(1), N0.getOperand(1));
10684
10685     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10686     // (concat_vectors X, Z)
10687     if (InsIdx == VT.getVectorNumElements()/2)
10688       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10689                          N0.getOperand(0), N->getOperand(1));
10690   }
10691
10692   return SDValue();
10693 }
10694
10695 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10696 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10697 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10698 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10699 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10700   EVT VT = N->getValueType(0);
10701   SDLoc dl(N);
10702   SDValue LHS = N->getOperand(0);
10703   SDValue RHS = N->getOperand(1);
10704   if (N->getOpcode() == ISD::AND) {
10705     if (RHS.getOpcode() == ISD::BITCAST)
10706       RHS = RHS.getOperand(0);
10707     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10708       SmallVector<int, 8> Indices;
10709       unsigned NumElts = RHS.getNumOperands();
10710       for (unsigned i = 0; i != NumElts; ++i) {
10711         SDValue Elt = RHS.getOperand(i);
10712         if (!isa<ConstantSDNode>(Elt))
10713           return SDValue();
10714
10715         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10716           Indices.push_back(i);
10717         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10718           Indices.push_back(NumElts);
10719         else
10720           return SDValue();
10721       }
10722
10723       // Let's see if the target supports this vector_shuffle.
10724       EVT RVT = RHS.getValueType();
10725       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10726         return SDValue();
10727
10728       // Return the new VECTOR_SHUFFLE node.
10729       EVT EltVT = RVT.getVectorElementType();
10730       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10731                                      DAG.getConstant(0, EltVT));
10732       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10733       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10734       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10735       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10736     }
10737   }
10738
10739   return SDValue();
10740 }
10741
10742 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10743 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10744   assert(N->getValueType(0).isVector() &&
10745          "SimplifyVBinOp only works on vectors!");
10746
10747   SDValue LHS = N->getOperand(0);
10748   SDValue RHS = N->getOperand(1);
10749   SDValue Shuffle = XformToShuffleWithZero(N);
10750   if (Shuffle.getNode()) return Shuffle;
10751
10752   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10753   // this operation.
10754   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10755       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10756     // Check if both vectors are constants. If not bail out.
10757     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10758           cast<BuildVectorSDNode>(RHS)->isConstant()))
10759       return SDValue();
10760
10761     SmallVector<SDValue, 8> Ops;
10762     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10763       SDValue LHSOp = LHS.getOperand(i);
10764       SDValue RHSOp = RHS.getOperand(i);
10765
10766       // Can't fold divide by zero.
10767       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10768           N->getOpcode() == ISD::FDIV) {
10769         if ((RHSOp.getOpcode() == ISD::Constant &&
10770              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10771             (RHSOp.getOpcode() == ISD::ConstantFP &&
10772              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10773           break;
10774       }
10775
10776       EVT VT = LHSOp.getValueType();
10777       EVT RVT = RHSOp.getValueType();
10778       if (RVT != VT) {
10779         // Integer BUILD_VECTOR operands may have types larger than the element
10780         // size (e.g., when the element type is not legal).  Prior to type
10781         // legalization, the types may not match between the two BUILD_VECTORS.
10782         // Truncate one of the operands to make them match.
10783         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10784           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10785         } else {
10786           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10787           VT = RVT;
10788         }
10789       }
10790       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10791                                    LHSOp, RHSOp);
10792       if (FoldOp.getOpcode() != ISD::UNDEF &&
10793           FoldOp.getOpcode() != ISD::Constant &&
10794           FoldOp.getOpcode() != ISD::ConstantFP)
10795         break;
10796       Ops.push_back(FoldOp);
10797       AddToWorkList(FoldOp.getNode());
10798     }
10799
10800     if (Ops.size() == LHS.getNumOperands())
10801       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
10802   }
10803
10804   // Type legalization might introduce new shuffles in the DAG.
10805   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
10806   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
10807   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
10808       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
10809       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
10810       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
10811     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
10812     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
10813
10814     if (SVN0->getMask().equals(SVN1->getMask())) {
10815       EVT VT = N->getValueType(0);
10816       SDValue UndefVector = LHS.getOperand(1);
10817       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10818                                      LHS.getOperand(0), RHS.getOperand(0));
10819       AddUsersToWorkList(N);
10820       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
10821                                   &SVN0->getMask()[0]);
10822     }
10823   }
10824
10825   return SDValue();
10826 }
10827
10828 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10829 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10830   assert(N->getValueType(0).isVector() &&
10831          "SimplifyVUnaryOp only works on vectors!");
10832
10833   SDValue N0 = N->getOperand(0);
10834
10835   if (N0.getOpcode() != ISD::BUILD_VECTOR)
10836     return SDValue();
10837
10838   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10839   SmallVector<SDValue, 8> Ops;
10840   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10841     SDValue Op = N0.getOperand(i);
10842     if (Op.getOpcode() != ISD::UNDEF &&
10843         Op.getOpcode() != ISD::ConstantFP)
10844       break;
10845     EVT EltVT = Op.getValueType();
10846     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10847     if (FoldOp.getOpcode() != ISD::UNDEF &&
10848         FoldOp.getOpcode() != ISD::ConstantFP)
10849       break;
10850     Ops.push_back(FoldOp);
10851     AddToWorkList(FoldOp.getNode());
10852   }
10853
10854   if (Ops.size() != N0.getNumOperands())
10855     return SDValue();
10856
10857   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
10858 }
10859
10860 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10861                                     SDValue N1, SDValue N2){
10862   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10863
10864   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10865                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
10866
10867   // If we got a simplified select_cc node back from SimplifySelectCC, then
10868   // break it down into a new SETCC node, and a new SELECT node, and then return
10869   // the SELECT node, since we were called with a SELECT node.
10870   if (SCC.getNode()) {
10871     // Check to see if we got a select_cc back (to turn into setcc/select).
10872     // Otherwise, just return whatever node we got back, like fabs.
10873     if (SCC.getOpcode() == ISD::SELECT_CC) {
10874       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10875                                   N0.getValueType(),
10876                                   SCC.getOperand(0), SCC.getOperand(1),
10877                                   SCC.getOperand(4));
10878       AddToWorkList(SETCC.getNode());
10879       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10880                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
10881     }
10882
10883     return SCC;
10884   }
10885   return SDValue();
10886 }
10887
10888 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10889 /// are the two values being selected between, see if we can simplify the
10890 /// select.  Callers of this should assume that TheSelect is deleted if this
10891 /// returns true.  As such, they should return the appropriate thing (e.g. the
10892 /// node) back to the top-level of the DAG combiner loop to avoid it being
10893 /// looked at.
10894 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10895                                     SDValue RHS) {
10896
10897   // Cannot simplify select with vector condition
10898   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10899
10900   // If this is a select from two identical things, try to pull the operation
10901   // through the select.
10902   if (LHS.getOpcode() != RHS.getOpcode() ||
10903       !LHS.hasOneUse() || !RHS.hasOneUse())
10904     return false;
10905
10906   // If this is a load and the token chain is identical, replace the select
10907   // of two loads with a load through a select of the address to load from.
10908   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10909   // constants have been dropped into the constant pool.
10910   if (LHS.getOpcode() == ISD::LOAD) {
10911     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10912     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10913
10914     // Token chains must be identical.
10915     if (LHS.getOperand(0) != RHS.getOperand(0) ||
10916         // Do not let this transformation reduce the number of volatile loads.
10917         LLD->isVolatile() || RLD->isVolatile() ||
10918         // If this is an EXTLOAD, the VT's must match.
10919         LLD->getMemoryVT() != RLD->getMemoryVT() ||
10920         // If this is an EXTLOAD, the kind of extension must match.
10921         (LLD->getExtensionType() != RLD->getExtensionType() &&
10922          // The only exception is if one of the extensions is anyext.
10923          LLD->getExtensionType() != ISD::EXTLOAD &&
10924          RLD->getExtensionType() != ISD::EXTLOAD) ||
10925         // FIXME: this discards src value information.  This is
10926         // over-conservative. It would be beneficial to be able to remember
10927         // both potential memory locations.  Since we are discarding
10928         // src value info, don't do the transformation if the memory
10929         // locations are not in the default address space.
10930         LLD->getPointerInfo().getAddrSpace() != 0 ||
10931         RLD->getPointerInfo().getAddrSpace() != 0 ||
10932         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10933                                       LLD->getBasePtr().getValueType()))
10934       return false;
10935
10936     // Check that the select condition doesn't reach either load.  If so,
10937     // folding this will induce a cycle into the DAG.  If not, this is safe to
10938     // xform, so create a select of the addresses.
10939     SDValue Addr;
10940     if (TheSelect->getOpcode() == ISD::SELECT) {
10941       SDNode *CondNode = TheSelect->getOperand(0).getNode();
10942       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10943           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10944         return false;
10945       // The loads must not depend on one another.
10946       if (LLD->isPredecessorOf(RLD) ||
10947           RLD->isPredecessorOf(LLD))
10948         return false;
10949       Addr = DAG.getSelect(SDLoc(TheSelect),
10950                            LLD->getBasePtr().getValueType(),
10951                            TheSelect->getOperand(0), LLD->getBasePtr(),
10952                            RLD->getBasePtr());
10953     } else {  // Otherwise SELECT_CC
10954       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10955       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10956
10957       if ((LLD->hasAnyUseOfValue(1) &&
10958            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10959           (RLD->hasAnyUseOfValue(1) &&
10960            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10961         return false;
10962
10963       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10964                          LLD->getBasePtr().getValueType(),
10965                          TheSelect->getOperand(0),
10966                          TheSelect->getOperand(1),
10967                          LLD->getBasePtr(), RLD->getBasePtr(),
10968                          TheSelect->getOperand(4));
10969     }
10970
10971     SDValue Load;
10972     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10973       Load = DAG.getLoad(TheSelect->getValueType(0),
10974                          SDLoc(TheSelect),
10975                          // FIXME: Discards pointer and TBAA info.
10976                          LLD->getChain(), Addr, MachinePointerInfo(),
10977                          LLD->isVolatile(), LLD->isNonTemporal(),
10978                          LLD->isInvariant(), LLD->getAlignment());
10979     } else {
10980       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10981                             RLD->getExtensionType() : LLD->getExtensionType(),
10982                             SDLoc(TheSelect),
10983                             TheSelect->getValueType(0),
10984                             // FIXME: Discards pointer and TBAA info.
10985                             LLD->getChain(), Addr, MachinePointerInfo(),
10986                             LLD->getMemoryVT(), LLD->isVolatile(),
10987                             LLD->isNonTemporal(), LLD->getAlignment());
10988     }
10989
10990     // Users of the select now use the result of the load.
10991     CombineTo(TheSelect, Load);
10992
10993     // Users of the old loads now use the new load's chain.  We know the
10994     // old-load value is dead now.
10995     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10996     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10997     return true;
10998   }
10999
11000   return false;
11001 }
11002
11003 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11004 /// where 'cond' is the comparison specified by CC.
11005 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11006                                       SDValue N2, SDValue N3,
11007                                       ISD::CondCode CC, bool NotExtCompare) {
11008   // (x ? y : y) -> y.
11009   if (N2 == N3) return N2;
11010
11011   EVT VT = N2.getValueType();
11012   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11013   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11014   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11015
11016   // Determine if the condition we're dealing with is constant
11017   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11018                               N0, N1, CC, DL, false);
11019   if (SCC.getNode()) AddToWorkList(SCC.getNode());
11020   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11021
11022   // fold select_cc true, x, y -> x
11023   if (SCCC && !SCCC->isNullValue())
11024     return N2;
11025   // fold select_cc false, x, y -> y
11026   if (SCCC && SCCC->isNullValue())
11027     return N3;
11028
11029   // Check to see if we can simplify the select into an fabs node
11030   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11031     // Allow either -0.0 or 0.0
11032     if (CFP->getValueAPF().isZero()) {
11033       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11034       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11035           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11036           N2 == N3.getOperand(0))
11037         return DAG.getNode(ISD::FABS, DL, VT, N0);
11038
11039       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11040       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11041           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11042           N2.getOperand(0) == N3)
11043         return DAG.getNode(ISD::FABS, DL, VT, N3);
11044     }
11045   }
11046
11047   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11048   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11049   // in it.  This is a win when the constant is not otherwise available because
11050   // it replaces two constant pool loads with one.  We only do this if the FP
11051   // type is known to be legal, because if it isn't, then we are before legalize
11052   // types an we want the other legalization to happen first (e.g. to avoid
11053   // messing with soft float) and if the ConstantFP is not legal, because if
11054   // it is legal, we may not need to store the FP constant in a constant pool.
11055   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11056     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11057       if (TLI.isTypeLegal(N2.getValueType()) &&
11058           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11059                TargetLowering::Legal &&
11060            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11061            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11062           // If both constants have multiple uses, then we won't need to do an
11063           // extra load, they are likely around in registers for other users.
11064           (TV->hasOneUse() || FV->hasOneUse())) {
11065         Constant *Elts[] = {
11066           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11067           const_cast<ConstantFP*>(TV->getConstantFPValue())
11068         };
11069         Type *FPTy = Elts[0]->getType();
11070         const DataLayout &TD = *TLI.getDataLayout();
11071
11072         // Create a ConstantArray of the two constants.
11073         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11074         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11075                                             TD.getPrefTypeAlignment(FPTy));
11076         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11077
11078         // Get the offsets to the 0 and 1 element of the array so that we can
11079         // select between them.
11080         SDValue Zero = DAG.getIntPtrConstant(0);
11081         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11082         SDValue One = DAG.getIntPtrConstant(EltSize);
11083
11084         SDValue Cond = DAG.getSetCC(DL,
11085                                     getSetCCResultType(N0.getValueType()),
11086                                     N0, N1, CC);
11087         AddToWorkList(Cond.getNode());
11088         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11089                                           Cond, One, Zero);
11090         AddToWorkList(CstOffset.getNode());
11091         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11092                             CstOffset);
11093         AddToWorkList(CPIdx.getNode());
11094         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11095                            MachinePointerInfo::getConstantPool(), false,
11096                            false, false, Alignment);
11097
11098       }
11099     }
11100
11101   // Check to see if we can perform the "gzip trick", transforming
11102   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11103   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11104       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11105        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11106     EVT XType = N0.getValueType();
11107     EVT AType = N2.getValueType();
11108     if (XType.bitsGE(AType)) {
11109       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11110       // single-bit constant.
11111       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11112         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11113         ShCtV = XType.getSizeInBits()-ShCtV-1;
11114         SDValue ShCt = DAG.getConstant(ShCtV,
11115                                        getShiftAmountTy(N0.getValueType()));
11116         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11117                                     XType, N0, ShCt);
11118         AddToWorkList(Shift.getNode());
11119
11120         if (XType.bitsGT(AType)) {
11121           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11122           AddToWorkList(Shift.getNode());
11123         }
11124
11125         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11126       }
11127
11128       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11129                                   XType, N0,
11130                                   DAG.getConstant(XType.getSizeInBits()-1,
11131                                          getShiftAmountTy(N0.getValueType())));
11132       AddToWorkList(Shift.getNode());
11133
11134       if (XType.bitsGT(AType)) {
11135         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11136         AddToWorkList(Shift.getNode());
11137       }
11138
11139       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11140     }
11141   }
11142
11143   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11144   // where y is has a single bit set.
11145   // A plaintext description would be, we can turn the SELECT_CC into an AND
11146   // when the condition can be materialized as an all-ones register.  Any
11147   // single bit-test can be materialized as an all-ones register with
11148   // shift-left and shift-right-arith.
11149   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11150       N0->getValueType(0) == VT &&
11151       N1C && N1C->isNullValue() &&
11152       N2C && N2C->isNullValue()) {
11153     SDValue AndLHS = N0->getOperand(0);
11154     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11155     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11156       // Shift the tested bit over the sign bit.
11157       APInt AndMask = ConstAndRHS->getAPIntValue();
11158       SDValue ShlAmt =
11159         DAG.getConstant(AndMask.countLeadingZeros(),
11160                         getShiftAmountTy(AndLHS.getValueType()));
11161       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11162
11163       // Now arithmetic right shift it all the way over, so the result is either
11164       // all-ones, or zero.
11165       SDValue ShrAmt =
11166         DAG.getConstant(AndMask.getBitWidth()-1,
11167                         getShiftAmountTy(Shl.getValueType()));
11168       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11169
11170       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11171     }
11172   }
11173
11174   // fold select C, 16, 0 -> shl C, 4
11175   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11176     TLI.getBooleanContents(N0.getValueType().isVector()) ==
11177       TargetLowering::ZeroOrOneBooleanContent) {
11178
11179     // If the caller doesn't want us to simplify this into a zext of a compare,
11180     // don't do it.
11181     if (NotExtCompare && N2C->getAPIntValue() == 1)
11182       return SDValue();
11183
11184     // Get a SetCC of the condition
11185     // NOTE: Don't create a SETCC if it's not legal on this target.
11186     if (!LegalOperations ||
11187         TLI.isOperationLegal(ISD::SETCC,
11188           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11189       SDValue Temp, SCC;
11190       // cast from setcc result type to select result type
11191       if (LegalTypes) {
11192         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11193                             N0, N1, CC);
11194         if (N2.getValueType().bitsLT(SCC.getValueType()))
11195           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11196                                         N2.getValueType());
11197         else
11198           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11199                              N2.getValueType(), SCC);
11200       } else {
11201         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11202         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11203                            N2.getValueType(), SCC);
11204       }
11205
11206       AddToWorkList(SCC.getNode());
11207       AddToWorkList(Temp.getNode());
11208
11209       if (N2C->getAPIntValue() == 1)
11210         return Temp;
11211
11212       // shl setcc result by log2 n2c
11213       return DAG.getNode(
11214           ISD::SHL, DL, N2.getValueType(), Temp,
11215           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11216                           getShiftAmountTy(Temp.getValueType())));
11217     }
11218   }
11219
11220   // Check to see if this is the equivalent of setcc
11221   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11222   // otherwise, go ahead with the folds.
11223   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11224     EVT XType = N0.getValueType();
11225     if (!LegalOperations ||
11226         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11227       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11228       if (Res.getValueType() != VT)
11229         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11230       return Res;
11231     }
11232
11233     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11234     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11235         (!LegalOperations ||
11236          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11237       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11238       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11239                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11240                                        getShiftAmountTy(Ctlz.getValueType())));
11241     }
11242     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11243     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11244       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11245                                   XType, DAG.getConstant(0, XType), N0);
11246       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11247       return DAG.getNode(ISD::SRL, DL, XType,
11248                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11249                          DAG.getConstant(XType.getSizeInBits()-1,
11250                                          getShiftAmountTy(XType)));
11251     }
11252     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11253     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11254       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11255                                  DAG.getConstant(XType.getSizeInBits()-1,
11256                                          getShiftAmountTy(N0.getValueType())));
11257       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11258     }
11259   }
11260
11261   // Check to see if this is an integer abs.
11262   // select_cc setg[te] X,  0,  X, -X ->
11263   // select_cc setgt    X, -1,  X, -X ->
11264   // select_cc setl[te] X,  0, -X,  X ->
11265   // select_cc setlt    X,  1, -X,  X ->
11266   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11267   if (N1C) {
11268     ConstantSDNode *SubC = nullptr;
11269     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11270          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11271         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11272       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11273     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11274               (N1C->isOne() && CC == ISD::SETLT)) &&
11275              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11276       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11277
11278     EVT XType = N0.getValueType();
11279     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11280       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11281                                   N0,
11282                                   DAG.getConstant(XType.getSizeInBits()-1,
11283                                          getShiftAmountTy(N0.getValueType())));
11284       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11285                                 XType, N0, Shift);
11286       AddToWorkList(Shift.getNode());
11287       AddToWorkList(Add.getNode());
11288       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11289     }
11290   }
11291
11292   return SDValue();
11293 }
11294
11295 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11296 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11297                                    SDValue N1, ISD::CondCode Cond,
11298                                    SDLoc DL, bool foldBooleans) {
11299   TargetLowering::DAGCombinerInfo
11300     DagCombineInfo(DAG, Level, false, this);
11301   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11302 }
11303
11304 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11305 /// return a DAG expression to select that will generate the same value by
11306 /// multiplying by a magic number.  See:
11307 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11308 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11309   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11310   if (!C)
11311     return SDValue();
11312
11313   // Avoid division by zero.
11314   if (!C->getAPIntValue())
11315     return SDValue();
11316
11317   std::vector<SDNode*> Built;
11318   SDValue S =
11319       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11320
11321   for (SDNode *N : Built)
11322     AddToWorkList(N);
11323   return S;
11324 }
11325
11326 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11327 /// return a DAG expression to select that will generate the same value by
11328 /// multiplying by a magic number.  See:
11329 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11330 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11331   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11332   if (!C)
11333     return SDValue();
11334
11335   // Avoid division by zero.
11336   if (!C->getAPIntValue())
11337     return SDValue();
11338
11339   std::vector<SDNode*> Built;
11340   SDValue S =
11341       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11342
11343   for (SDNode *N : Built)
11344     AddToWorkList(N);
11345   return S;
11346 }
11347
11348 /// FindBaseOffset - Return true if base is a frame index, which is known not
11349 // to alias with anything but itself.  Provides base object and offset as
11350 // results.
11351 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11352                            const GlobalValue *&GV, const void *&CV) {
11353   // Assume it is a primitive operation.
11354   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11355
11356   // If it's an adding a simple constant then integrate the offset.
11357   if (Base.getOpcode() == ISD::ADD) {
11358     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11359       Base = Base.getOperand(0);
11360       Offset += C->getZExtValue();
11361     }
11362   }
11363
11364   // Return the underlying GlobalValue, and update the Offset.  Return false
11365   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11366   // by multiple nodes with different offsets.
11367   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11368     GV = G->getGlobal();
11369     Offset += G->getOffset();
11370     return false;
11371   }
11372
11373   // Return the underlying Constant value, and update the Offset.  Return false
11374   // for ConstantSDNodes since the same constant pool entry may be represented
11375   // by multiple nodes with different offsets.
11376   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11377     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11378                                          : (const void *)C->getConstVal();
11379     Offset += C->getOffset();
11380     return false;
11381   }
11382   // If it's any of the following then it can't alias with anything but itself.
11383   return isa<FrameIndexSDNode>(Base);
11384 }
11385
11386 /// isAlias - Return true if there is any possibility that the two addresses
11387 /// overlap.
11388 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11389   // If they are the same then they must be aliases.
11390   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11391
11392   // If they are both volatile then they cannot be reordered.
11393   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11394
11395   // Gather base node and offset information.
11396   SDValue Base1, Base2;
11397   int64_t Offset1, Offset2;
11398   const GlobalValue *GV1, *GV2;
11399   const void *CV1, *CV2;
11400   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11401                                       Base1, Offset1, GV1, CV1);
11402   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11403                                       Base2, Offset2, GV2, CV2);
11404
11405   // If they have a same base address then check to see if they overlap.
11406   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11407     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11408              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11409
11410   // It is possible for different frame indices to alias each other, mostly
11411   // when tail call optimization reuses return address slots for arguments.
11412   // To catch this case, look up the actual index of frame indices to compute
11413   // the real alias relationship.
11414   if (isFrameIndex1 && isFrameIndex2) {
11415     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11416     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11417     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11418     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11419              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11420   }
11421
11422   // Otherwise, if we know what the bases are, and they aren't identical, then
11423   // we know they cannot alias.
11424   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11425     return false;
11426
11427   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11428   // compared to the size and offset of the access, we may be able to prove they
11429   // do not alias.  This check is conservative for now to catch cases created by
11430   // splitting vector types.
11431   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11432       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11433       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11434        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11435       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11436     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11437     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11438
11439     // There is no overlap between these relatively aligned accesses of similar
11440     // size, return no alias.
11441     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11442         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11443       return false;
11444   }
11445
11446   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11447     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11448 #ifndef NDEBUG
11449   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11450       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11451     UseAA = false;
11452 #endif
11453   if (UseAA &&
11454       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11455     // Use alias analysis information.
11456     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11457                                  Op1->getSrcValueOffset());
11458     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11459         Op0->getSrcValueOffset() - MinOffset;
11460     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11461         Op1->getSrcValueOffset() - MinOffset;
11462     AliasAnalysis::AliasResult AAResult =
11463         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11464                                          Overlap1,
11465                                          UseTBAA ? Op0->getTBAAInfo() : nullptr),
11466                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11467                                          Overlap2,
11468                                          UseTBAA ? Op1->getTBAAInfo() : nullptr));
11469     if (AAResult == AliasAnalysis::NoAlias)
11470       return false;
11471   }
11472
11473   // Otherwise we have to assume they alias.
11474   return true;
11475 }
11476
11477 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11478 /// looking for aliasing nodes and adding them to the Aliases vector.
11479 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11480                                    SmallVectorImpl<SDValue> &Aliases) {
11481   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11482   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11483
11484   // Get alias information for node.
11485   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11486
11487   // Starting off.
11488   Chains.push_back(OriginalChain);
11489   unsigned Depth = 0;
11490
11491   // Look at each chain and determine if it is an alias.  If so, add it to the
11492   // aliases list.  If not, then continue up the chain looking for the next
11493   // candidate.
11494   while (!Chains.empty()) {
11495     SDValue Chain = Chains.back();
11496     Chains.pop_back();
11497
11498     // For TokenFactor nodes, look at each operand and only continue up the
11499     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11500     // find more and revert to original chain since the xform is unlikely to be
11501     // profitable.
11502     //
11503     // FIXME: The depth check could be made to return the last non-aliasing
11504     // chain we found before we hit a tokenfactor rather than the original
11505     // chain.
11506     if (Depth > 6 || Aliases.size() == 2) {
11507       Aliases.clear();
11508       Aliases.push_back(OriginalChain);
11509       return;
11510     }
11511
11512     // Don't bother if we've been before.
11513     if (!Visited.insert(Chain.getNode()))
11514       continue;
11515
11516     switch (Chain.getOpcode()) {
11517     case ISD::EntryToken:
11518       // Entry token is ideal chain operand, but handled in FindBetterChain.
11519       break;
11520
11521     case ISD::LOAD:
11522     case ISD::STORE: {
11523       // Get alias information for Chain.
11524       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11525           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11526
11527       // If chain is alias then stop here.
11528       if (!(IsLoad && IsOpLoad) &&
11529           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11530         Aliases.push_back(Chain);
11531       } else {
11532         // Look further up the chain.
11533         Chains.push_back(Chain.getOperand(0));
11534         ++Depth;
11535       }
11536       break;
11537     }
11538
11539     case ISD::TokenFactor:
11540       // We have to check each of the operands of the token factor for "small"
11541       // token factors, so we queue them up.  Adding the operands to the queue
11542       // (stack) in reverse order maintains the original order and increases the
11543       // likelihood that getNode will find a matching token factor (CSE.)
11544       if (Chain.getNumOperands() > 16) {
11545         Aliases.push_back(Chain);
11546         break;
11547       }
11548       for (unsigned n = Chain.getNumOperands(); n;)
11549         Chains.push_back(Chain.getOperand(--n));
11550       ++Depth;
11551       break;
11552
11553     default:
11554       // For all other instructions we will just have to take what we can get.
11555       Aliases.push_back(Chain);
11556       break;
11557     }
11558   }
11559
11560   // We need to be careful here to also search for aliases through the
11561   // value operand of a store, etc. Consider the following situation:
11562   //   Token1 = ...
11563   //   L1 = load Token1, %52
11564   //   S1 = store Token1, L1, %51
11565   //   L2 = load Token1, %52+8
11566   //   S2 = store Token1, L2, %51+8
11567   //   Token2 = Token(S1, S2)
11568   //   L3 = load Token2, %53
11569   //   S3 = store Token2, L3, %52
11570   //   L4 = load Token2, %53+8
11571   //   S4 = store Token2, L4, %52+8
11572   // If we search for aliases of S3 (which loads address %52), and we look
11573   // only through the chain, then we'll miss the trivial dependence on L1
11574   // (which also loads from %52). We then might change all loads and
11575   // stores to use Token1 as their chain operand, which could result in
11576   // copying %53 into %52 before copying %52 into %51 (which should
11577   // happen first).
11578   //
11579   // The problem is, however, that searching for such data dependencies
11580   // can become expensive, and the cost is not directly related to the
11581   // chain depth. Instead, we'll rule out such configurations here by
11582   // insisting that we've visited all chain users (except for users
11583   // of the original chain, which is not necessary). When doing this,
11584   // we need to look through nodes we don't care about (otherwise, things
11585   // like register copies will interfere with trivial cases).
11586
11587   SmallVector<const SDNode *, 16> Worklist;
11588   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11589        IE = Visited.end(); I != IE; ++I)
11590     if (*I != OriginalChain.getNode())
11591       Worklist.push_back(*I);
11592
11593   while (!Worklist.empty()) {
11594     const SDNode *M = Worklist.pop_back_val();
11595
11596     // We have already visited M, and want to make sure we've visited any uses
11597     // of M that we care about. For uses that we've not visisted, and don't
11598     // care about, queue them to the worklist.
11599
11600     for (SDNode::use_iterator UI = M->use_begin(),
11601          UIE = M->use_end(); UI != UIE; ++UI)
11602       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11603         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11604           // We've not visited this use, and we care about it (it could have an
11605           // ordering dependency with the original node).
11606           Aliases.clear();
11607           Aliases.push_back(OriginalChain);
11608           return;
11609         }
11610
11611         // We've not visited this use, but we don't care about it. Mark it as
11612         // visited and enqueue it to the worklist.
11613         Worklist.push_back(*UI);
11614       }
11615   }
11616 }
11617
11618 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11619 /// for a better chain (aliasing node.)
11620 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11621   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11622
11623   // Accumulate all the aliases to this node.
11624   GatherAllAliases(N, OldChain, Aliases);
11625
11626   // If no operands then chain to entry token.
11627   if (Aliases.size() == 0)
11628     return DAG.getEntryNode();
11629
11630   // If a single operand then chain to it.  We don't need to revisit it.
11631   if (Aliases.size() == 1)
11632     return Aliases[0];
11633
11634   // Construct a custom tailored token factor.
11635   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11636 }
11637
11638 // SelectionDAG::Combine - This is the entry point for the file.
11639 //
11640 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11641                            CodeGenOpt::Level OptLevel) {
11642   /// run - This is the main entry point to this class.
11643   ///
11644   DAGCombiner(*this, AA, OptLevel).Run(Level);
11645 }