[DAGCombiner] Add more rules to fold shuffles.
[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     BitVector UndefElements;
659     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
660
661     // BuildVectors can truncate their operands. Ignore that case here.
662     // FIXME: We blindly ignore splats which include undef which is overly
663     // pessimistic.
664     if (CN && UndefElements.none() &&
665         CN->getValueType(0) == N.getValueType().getScalarType())
666       return CN;
667   }
668
669   return nullptr;
670 }
671
672 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
673                                     SDValue N0, SDValue N1) {
674   EVT VT = N0.getValueType();
675   if (N0.getOpcode() == Opc) {
676     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
677       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
678         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
679         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
680         if (!OpNode.getNode())
681           return SDValue();
682         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
683       }
684       if (N0.hasOneUse()) {
685         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
686         // use
687         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
688         if (!OpNode.getNode())
689           return SDValue();
690         AddToWorkList(OpNode.getNode());
691         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
692       }
693     }
694   }
695
696   if (N1.getOpcode() == Opc) {
697     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
698       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
699         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
700         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
701         if (!OpNode.getNode())
702           return SDValue();
703         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
704       }
705       if (N1.hasOneUse()) {
706         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
707         // use
708         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
709         if (!OpNode.getNode())
710           return SDValue();
711         AddToWorkList(OpNode.getNode());
712         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
713       }
714     }
715   }
716
717   return SDValue();
718 }
719
720 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
721                                bool AddTo) {
722   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
723   ++NodesCombined;
724   DEBUG(dbgs() << "\nReplacing.1 ";
725         N->dump(&DAG);
726         dbgs() << "\nWith: ";
727         To[0].getNode()->dump(&DAG);
728         dbgs() << " and " << NumTo-1 << " other values\n";
729         for (unsigned i = 0, e = NumTo; i != e; ++i)
730           assert((!To[i].getNode() ||
731                   N->getValueType(i) == To[i].getValueType()) &&
732                  "Cannot combine value to value of different type!"));
733   WorkListRemover DeadNodes(*this);
734   DAG.ReplaceAllUsesWith(N, To);
735   if (AddTo) {
736     // Push the new nodes and any users onto the worklist
737     for (unsigned i = 0, e = NumTo; i != e; ++i) {
738       if (To[i].getNode()) {
739         AddToWorkList(To[i].getNode());
740         AddUsersToWorkList(To[i].getNode());
741       }
742     }
743   }
744
745   // Finally, if the node is now dead, remove it from the graph.  The node
746   // may not be dead if the replacement process recursively simplified to
747   // something else needing this node.
748   if (N->use_empty()) {
749     // Nodes can be reintroduced into the worklist.  Make sure we do not
750     // process a node that has been replaced.
751     removeFromWorkList(N);
752
753     // Finally, since the node is now dead, remove it from the graph.
754     DAG.DeleteNode(N);
755   }
756   return SDValue(N, 0);
757 }
758
759 void DAGCombiner::
760 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
761   // Replace all uses.  If any nodes become isomorphic to other nodes and
762   // are deleted, make sure to remove them from our worklist.
763   WorkListRemover DeadNodes(*this);
764   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
765
766   // Push the new node and any (possibly new) users onto the worklist.
767   AddToWorkList(TLO.New.getNode());
768   AddUsersToWorkList(TLO.New.getNode());
769
770   // Finally, if the node is now dead, remove it from the graph.  The node
771   // may not be dead if the replacement process recursively simplified to
772   // something else needing this node.
773   if (TLO.Old.getNode()->use_empty()) {
774     removeFromWorkList(TLO.Old.getNode());
775
776     // If the operands of this node are only used by the node, they will now
777     // be dead.  Make sure to visit them first to delete dead nodes early.
778     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
779       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
780         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
781
782     DAG.DeleteNode(TLO.Old.getNode());
783   }
784 }
785
786 /// SimplifyDemandedBits - Check the specified integer node value to see if
787 /// it can be simplified or if things it uses can be simplified by bit
788 /// propagation.  If so, return true.
789 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
790   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
791   APInt KnownZero, KnownOne;
792   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
793     return false;
794
795   // Revisit the node.
796   AddToWorkList(Op.getNode());
797
798   // Replace the old value with the new one.
799   ++NodesCombined;
800   DEBUG(dbgs() << "\nReplacing.2 ";
801         TLO.Old.getNode()->dump(&DAG);
802         dbgs() << "\nWith: ";
803         TLO.New.getNode()->dump(&DAG);
804         dbgs() << '\n');
805
806   CommitTargetLoweringOpt(TLO);
807   return true;
808 }
809
810 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
811   SDLoc dl(Load);
812   EVT VT = Load->getValueType(0);
813   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
814
815   DEBUG(dbgs() << "\nReplacing.9 ";
816         Load->dump(&DAG);
817         dbgs() << "\nWith: ";
818         Trunc.getNode()->dump(&DAG);
819         dbgs() << '\n');
820   WorkListRemover DeadNodes(*this);
821   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
822   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
823   removeFromWorkList(Load);
824   DAG.DeleteNode(Load);
825   AddToWorkList(Trunc.getNode());
826 }
827
828 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
829   Replace = false;
830   SDLoc dl(Op);
831   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
832     EVT MemVT = LD->getMemoryVT();
833     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
834       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
835                                                   : ISD::EXTLOAD)
836       : LD->getExtensionType();
837     Replace = true;
838     return DAG.getExtLoad(ExtType, dl, PVT,
839                           LD->getChain(), LD->getBasePtr(),
840                           MemVT, LD->getMemOperand());
841   }
842
843   unsigned Opc = Op.getOpcode();
844   switch (Opc) {
845   default: break;
846   case ISD::AssertSext:
847     return DAG.getNode(ISD::AssertSext, dl, PVT,
848                        SExtPromoteOperand(Op.getOperand(0), PVT),
849                        Op.getOperand(1));
850   case ISD::AssertZext:
851     return DAG.getNode(ISD::AssertZext, dl, PVT,
852                        ZExtPromoteOperand(Op.getOperand(0), PVT),
853                        Op.getOperand(1));
854   case ISD::Constant: {
855     unsigned ExtOpc =
856       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
857     return DAG.getNode(ExtOpc, dl, PVT, Op);
858   }
859   }
860
861   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
862     return SDValue();
863   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
864 }
865
866 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
867   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
868     return SDValue();
869   EVT OldVT = Op.getValueType();
870   SDLoc dl(Op);
871   bool Replace = false;
872   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
873   if (!NewOp.getNode())
874     return SDValue();
875   AddToWorkList(NewOp.getNode());
876
877   if (Replace)
878     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
879   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
880                      DAG.getValueType(OldVT));
881 }
882
883 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
884   EVT OldVT = Op.getValueType();
885   SDLoc dl(Op);
886   bool Replace = false;
887   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
888   if (!NewOp.getNode())
889     return SDValue();
890   AddToWorkList(NewOp.getNode());
891
892   if (Replace)
893     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
894   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
895 }
896
897 /// PromoteIntBinOp - Promote the specified integer binary operation if the
898 /// target indicates it is beneficial. e.g. On x86, it's usually better to
899 /// promote i16 operations to i32 since i16 instructions are longer.
900 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
901   if (!LegalOperations)
902     return SDValue();
903
904   EVT VT = Op.getValueType();
905   if (VT.isVector() || !VT.isInteger())
906     return SDValue();
907
908   // If operation type is 'undesirable', e.g. i16 on x86, consider
909   // promoting it.
910   unsigned Opc = Op.getOpcode();
911   if (TLI.isTypeDesirableForOp(Opc, VT))
912     return SDValue();
913
914   EVT PVT = VT;
915   // Consult target whether it is a good idea to promote this operation and
916   // what's the right type to promote it to.
917   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
918     assert(PVT != VT && "Don't know what type to promote to!");
919
920     bool Replace0 = false;
921     SDValue N0 = Op.getOperand(0);
922     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
923     if (!NN0.getNode())
924       return SDValue();
925
926     bool Replace1 = false;
927     SDValue N1 = Op.getOperand(1);
928     SDValue NN1;
929     if (N0 == N1)
930       NN1 = NN0;
931     else {
932       NN1 = PromoteOperand(N1, PVT, Replace1);
933       if (!NN1.getNode())
934         return SDValue();
935     }
936
937     AddToWorkList(NN0.getNode());
938     if (NN1.getNode())
939       AddToWorkList(NN1.getNode());
940
941     if (Replace0)
942       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
943     if (Replace1)
944       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
945
946     DEBUG(dbgs() << "\nPromoting ";
947           Op.getNode()->dump(&DAG));
948     SDLoc dl(Op);
949     return DAG.getNode(ISD::TRUNCATE, dl, VT,
950                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
951   }
952   return SDValue();
953 }
954
955 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
956 /// target indicates it is beneficial. e.g. On x86, it's usually better to
957 /// promote i16 operations to i32 since i16 instructions are longer.
958 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
959   if (!LegalOperations)
960     return SDValue();
961
962   EVT VT = Op.getValueType();
963   if (VT.isVector() || !VT.isInteger())
964     return SDValue();
965
966   // If operation type is 'undesirable', e.g. i16 on x86, consider
967   // promoting it.
968   unsigned Opc = Op.getOpcode();
969   if (TLI.isTypeDesirableForOp(Opc, VT))
970     return SDValue();
971
972   EVT PVT = VT;
973   // Consult target whether it is a good idea to promote this operation and
974   // what's the right type to promote it to.
975   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
976     assert(PVT != VT && "Don't know what type to promote to!");
977
978     bool Replace = false;
979     SDValue N0 = Op.getOperand(0);
980     if (Opc == ISD::SRA)
981       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
982     else if (Opc == ISD::SRL)
983       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
984     else
985       N0 = PromoteOperand(N0, PVT, Replace);
986     if (!N0.getNode())
987       return SDValue();
988
989     AddToWorkList(N0.getNode());
990     if (Replace)
991       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
992
993     DEBUG(dbgs() << "\nPromoting ";
994           Op.getNode()->dump(&DAG));
995     SDLoc dl(Op);
996     return DAG.getNode(ISD::TRUNCATE, dl, VT,
997                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
998   }
999   return SDValue();
1000 }
1001
1002 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1003   if (!LegalOperations)
1004     return SDValue();
1005
1006   EVT VT = Op.getValueType();
1007   if (VT.isVector() || !VT.isInteger())
1008     return SDValue();
1009
1010   // If operation type is 'undesirable', e.g. i16 on x86, consider
1011   // promoting it.
1012   unsigned Opc = Op.getOpcode();
1013   if (TLI.isTypeDesirableForOp(Opc, VT))
1014     return SDValue();
1015
1016   EVT PVT = VT;
1017   // Consult target whether it is a good idea to promote this operation and
1018   // what's the right type to promote it to.
1019   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1020     assert(PVT != VT && "Don't know what type to promote to!");
1021     // fold (aext (aext x)) -> (aext x)
1022     // fold (aext (zext x)) -> (zext x)
1023     // fold (aext (sext x)) -> (sext x)
1024     DEBUG(dbgs() << "\nPromoting ";
1025           Op.getNode()->dump(&DAG));
1026     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1027   }
1028   return SDValue();
1029 }
1030
1031 bool DAGCombiner::PromoteLoad(SDValue Op) {
1032   if (!LegalOperations)
1033     return false;
1034
1035   EVT VT = Op.getValueType();
1036   if (VT.isVector() || !VT.isInteger())
1037     return false;
1038
1039   // If operation type is 'undesirable', e.g. i16 on x86, consider
1040   // promoting it.
1041   unsigned Opc = Op.getOpcode();
1042   if (TLI.isTypeDesirableForOp(Opc, VT))
1043     return false;
1044
1045   EVT PVT = VT;
1046   // Consult target whether it is a good idea to promote this operation and
1047   // what's the right type to promote it to.
1048   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1049     assert(PVT != VT && "Don't know what type to promote to!");
1050
1051     SDLoc dl(Op);
1052     SDNode *N = Op.getNode();
1053     LoadSDNode *LD = cast<LoadSDNode>(N);
1054     EVT MemVT = LD->getMemoryVT();
1055     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1056       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1057                                                   : ISD::EXTLOAD)
1058       : LD->getExtensionType();
1059     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1060                                    LD->getChain(), LD->getBasePtr(),
1061                                    MemVT, LD->getMemOperand());
1062     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1063
1064     DEBUG(dbgs() << "\nPromoting ";
1065           N->dump(&DAG);
1066           dbgs() << "\nTo: ";
1067           Result.getNode()->dump(&DAG);
1068           dbgs() << '\n');
1069     WorkListRemover DeadNodes(*this);
1070     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1071     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1072     removeFromWorkList(N);
1073     DAG.DeleteNode(N);
1074     AddToWorkList(Result.getNode());
1075     return true;
1076   }
1077   return false;
1078 }
1079
1080
1081 //===----------------------------------------------------------------------===//
1082 //  Main DAG Combiner implementation
1083 //===----------------------------------------------------------------------===//
1084
1085 void DAGCombiner::Run(CombineLevel AtLevel) {
1086   // set the instance variables, so that the various visit routines may use it.
1087   Level = AtLevel;
1088   LegalOperations = Level >= AfterLegalizeVectorOps;
1089   LegalTypes = Level >= AfterLegalizeTypes;
1090
1091   // Add all the dag nodes to the worklist.
1092   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1093        E = DAG.allnodes_end(); I != E; ++I)
1094     AddToWorkList(I);
1095
1096   // Create a dummy node (which is not added to allnodes), that adds a reference
1097   // to the root node, preventing it from being deleted, and tracking any
1098   // changes of the root.
1099   HandleSDNode Dummy(DAG.getRoot());
1100
1101   // The root of the dag may dangle to deleted nodes until the dag combiner is
1102   // done.  Set it to null to avoid confusion.
1103   DAG.setRoot(SDValue());
1104
1105   // while the worklist isn't empty, find a node and
1106   // try and combine it.
1107   while (!WorkListContents.empty()) {
1108     SDNode *N;
1109     // The WorkListOrder holds the SDNodes in order, but it may contain
1110     // duplicates.
1111     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1112     // worklist *should* contain, and check the node we want to visit is should
1113     // actually be visited.
1114     do {
1115       N = WorkListOrder.pop_back_val();
1116     } while (!WorkListContents.erase(N));
1117
1118     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1119     // N is deleted from the DAG, since they too may now be dead or may have a
1120     // reduced number of uses, allowing other xforms.
1121     if (N->use_empty() && N != &Dummy) {
1122       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1123         AddToWorkList(N->getOperand(i).getNode());
1124
1125       DAG.DeleteNode(N);
1126       continue;
1127     }
1128
1129     SDValue RV = combine(N);
1130
1131     if (!RV.getNode())
1132       continue;
1133
1134     ++NodesCombined;
1135
1136     // If we get back the same node we passed in, rather than a new node or
1137     // zero, we know that the node must have defined multiple values and
1138     // CombineTo was used.  Since CombineTo takes care of the worklist
1139     // mechanics for us, we have no work to do in this case.
1140     if (RV.getNode() == N)
1141       continue;
1142
1143     assert(N->getOpcode() != ISD::DELETED_NODE &&
1144            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1145            "Node was deleted but visit returned new node!");
1146
1147     DEBUG(dbgs() << "\nReplacing.3 ";
1148           N->dump(&DAG);
1149           dbgs() << "\nWith: ";
1150           RV.getNode()->dump(&DAG);
1151           dbgs() << '\n');
1152
1153     // Transfer debug value.
1154     DAG.TransferDbgValues(SDValue(N, 0), RV);
1155     WorkListRemover DeadNodes(*this);
1156     if (N->getNumValues() == RV.getNode()->getNumValues())
1157       DAG.ReplaceAllUsesWith(N, RV.getNode());
1158     else {
1159       assert(N->getValueType(0) == RV.getValueType() &&
1160              N->getNumValues() == 1 && "Type mismatch");
1161       SDValue OpV = RV;
1162       DAG.ReplaceAllUsesWith(N, &OpV);
1163     }
1164
1165     // Push the new node and any users onto the worklist
1166     AddToWorkList(RV.getNode());
1167     AddUsersToWorkList(RV.getNode());
1168
1169     // Add any uses of the old node to the worklist in case this node is the
1170     // last one that uses them.  They may become dead after this node is
1171     // deleted.
1172     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1173       AddToWorkList(N->getOperand(i).getNode());
1174
1175     // Finally, if the node is now dead, remove it from the graph.  The node
1176     // may not be dead if the replacement process recursively simplified to
1177     // something else needing this node.
1178     if (N->use_empty()) {
1179       // Nodes can be reintroduced into the worklist.  Make sure we do not
1180       // process a node that has been replaced.
1181       removeFromWorkList(N);
1182
1183       // Finally, since the node is now dead, remove it from the graph.
1184       DAG.DeleteNode(N);
1185     }
1186   }
1187
1188   // If the root changed (e.g. it was a dead load, update the root).
1189   DAG.setRoot(Dummy.getValue());
1190   DAG.RemoveDeadNodes();
1191 }
1192
1193 SDValue DAGCombiner::visit(SDNode *N) {
1194   switch (N->getOpcode()) {
1195   default: break;
1196   case ISD::TokenFactor:        return visitTokenFactor(N);
1197   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1198   case ISD::ADD:                return visitADD(N);
1199   case ISD::SUB:                return visitSUB(N);
1200   case ISD::ADDC:               return visitADDC(N);
1201   case ISD::SUBC:               return visitSUBC(N);
1202   case ISD::ADDE:               return visitADDE(N);
1203   case ISD::SUBE:               return visitSUBE(N);
1204   case ISD::MUL:                return visitMUL(N);
1205   case ISD::SDIV:               return visitSDIV(N);
1206   case ISD::UDIV:               return visitUDIV(N);
1207   case ISD::SREM:               return visitSREM(N);
1208   case ISD::UREM:               return visitUREM(N);
1209   case ISD::MULHU:              return visitMULHU(N);
1210   case ISD::MULHS:              return visitMULHS(N);
1211   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1212   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1213   case ISD::SMULO:              return visitSMULO(N);
1214   case ISD::UMULO:              return visitUMULO(N);
1215   case ISD::SDIVREM:            return visitSDIVREM(N);
1216   case ISD::UDIVREM:            return visitUDIVREM(N);
1217   case ISD::AND:                return visitAND(N);
1218   case ISD::OR:                 return visitOR(N);
1219   case ISD::XOR:                return visitXOR(N);
1220   case ISD::SHL:                return visitSHL(N);
1221   case ISD::SRA:                return visitSRA(N);
1222   case ISD::SRL:                return visitSRL(N);
1223   case ISD::ROTR:
1224   case ISD::ROTL:               return visitRotate(N);
1225   case ISD::CTLZ:               return visitCTLZ(N);
1226   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1227   case ISD::CTTZ:               return visitCTTZ(N);
1228   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1229   case ISD::CTPOP:              return visitCTPOP(N);
1230   case ISD::SELECT:             return visitSELECT(N);
1231   case ISD::VSELECT:            return visitVSELECT(N);
1232   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1233   case ISD::SETCC:              return visitSETCC(N);
1234   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1235   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1236   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1237   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1238   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1239   case ISD::BITCAST:            return visitBITCAST(N);
1240   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1241   case ISD::FADD:               return visitFADD(N);
1242   case ISD::FSUB:               return visitFSUB(N);
1243   case ISD::FMUL:               return visitFMUL(N);
1244   case ISD::FMA:                return visitFMA(N);
1245   case ISD::FDIV:               return visitFDIV(N);
1246   case ISD::FREM:               return visitFREM(N);
1247   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1248   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1249   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1250   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1251   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1252   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1253   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1254   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1255   case ISD::FNEG:               return visitFNEG(N);
1256   case ISD::FABS:               return visitFABS(N);
1257   case ISD::FFLOOR:             return visitFFLOOR(N);
1258   case ISD::FCEIL:              return visitFCEIL(N);
1259   case ISD::FTRUNC:             return visitFTRUNC(N);
1260   case ISD::BRCOND:             return visitBRCOND(N);
1261   case ISD::BR_CC:              return visitBR_CC(N);
1262   case ISD::LOAD:               return visitLOAD(N);
1263   case ISD::STORE:              return visitSTORE(N);
1264   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1265   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1266   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1267   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1268   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1269   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1270   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1271   }
1272   return SDValue();
1273 }
1274
1275 SDValue DAGCombiner::combine(SDNode *N) {
1276   SDValue RV = visit(N);
1277
1278   // If nothing happened, try a target-specific DAG combine.
1279   if (!RV.getNode()) {
1280     assert(N->getOpcode() != ISD::DELETED_NODE &&
1281            "Node was deleted but visit returned NULL!");
1282
1283     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1284         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1285
1286       // Expose the DAG combiner to the target combiner impls.
1287       TargetLowering::DAGCombinerInfo
1288         DagCombineInfo(DAG, Level, false, this);
1289
1290       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1291     }
1292   }
1293
1294   // If nothing happened still, try promoting the operation.
1295   if (!RV.getNode()) {
1296     switch (N->getOpcode()) {
1297     default: break;
1298     case ISD::ADD:
1299     case ISD::SUB:
1300     case ISD::MUL:
1301     case ISD::AND:
1302     case ISD::OR:
1303     case ISD::XOR:
1304       RV = PromoteIntBinOp(SDValue(N, 0));
1305       break;
1306     case ISD::SHL:
1307     case ISD::SRA:
1308     case ISD::SRL:
1309       RV = PromoteIntShiftOp(SDValue(N, 0));
1310       break;
1311     case ISD::SIGN_EXTEND:
1312     case ISD::ZERO_EXTEND:
1313     case ISD::ANY_EXTEND:
1314       RV = PromoteExtend(SDValue(N, 0));
1315       break;
1316     case ISD::LOAD:
1317       if (PromoteLoad(SDValue(N, 0)))
1318         RV = SDValue(N, 0);
1319       break;
1320     }
1321   }
1322
1323   // If N is a commutative binary node, try commuting it to enable more
1324   // sdisel CSE.
1325   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1326       N->getNumValues() == 1) {
1327     SDValue N0 = N->getOperand(0);
1328     SDValue N1 = N->getOperand(1);
1329
1330     // Constant operands are canonicalized to RHS.
1331     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1332       SDValue Ops[] = {N1, N0};
1333       SDNode *CSENode;
1334       if (const BinaryWithFlagsSDNode *BinNode =
1335               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1336         CSENode = DAG.getNodeIfExists(
1337             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1338             BinNode->hasNoSignedWrap(), BinNode->isExact());
1339       } else {
1340         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1341       }
1342       if (CSENode)
1343         return SDValue(CSENode, 0);
1344     }
1345   }
1346
1347   return RV;
1348 }
1349
1350 /// getInputChainForNode - Given a node, return its input chain if it has one,
1351 /// otherwise return a null sd operand.
1352 static SDValue getInputChainForNode(SDNode *N) {
1353   if (unsigned NumOps = N->getNumOperands()) {
1354     if (N->getOperand(0).getValueType() == MVT::Other)
1355       return N->getOperand(0);
1356     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1357       return N->getOperand(NumOps-1);
1358     for (unsigned i = 1; i < NumOps-1; ++i)
1359       if (N->getOperand(i).getValueType() == MVT::Other)
1360         return N->getOperand(i);
1361   }
1362   return SDValue();
1363 }
1364
1365 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1366   // If N has two operands, where one has an input chain equal to the other,
1367   // the 'other' chain is redundant.
1368   if (N->getNumOperands() == 2) {
1369     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1370       return N->getOperand(0);
1371     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1372       return N->getOperand(1);
1373   }
1374
1375   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1376   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1377   SmallPtrSet<SDNode*, 16> SeenOps;
1378   bool Changed = false;             // If we should replace this token factor.
1379
1380   // Start out with this token factor.
1381   TFs.push_back(N);
1382
1383   // Iterate through token factors.  The TFs grows when new token factors are
1384   // encountered.
1385   for (unsigned i = 0; i < TFs.size(); ++i) {
1386     SDNode *TF = TFs[i];
1387
1388     // Check each of the operands.
1389     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1390       SDValue Op = TF->getOperand(i);
1391
1392       switch (Op.getOpcode()) {
1393       case ISD::EntryToken:
1394         // Entry tokens don't need to be added to the list. They are
1395         // rededundant.
1396         Changed = true;
1397         break;
1398
1399       case ISD::TokenFactor:
1400         if (Op.hasOneUse() &&
1401             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1402           // Queue up for processing.
1403           TFs.push_back(Op.getNode());
1404           // Clean up in case the token factor is removed.
1405           AddToWorkList(Op.getNode());
1406           Changed = true;
1407           break;
1408         }
1409         // Fall thru
1410
1411       default:
1412         // Only add if it isn't already in the list.
1413         if (SeenOps.insert(Op.getNode()))
1414           Ops.push_back(Op);
1415         else
1416           Changed = true;
1417         break;
1418       }
1419     }
1420   }
1421
1422   SDValue Result;
1423
1424   // If we've change things around then replace token factor.
1425   if (Changed) {
1426     if (Ops.empty()) {
1427       // The entry token is the only possible outcome.
1428       Result = DAG.getEntryNode();
1429     } else {
1430       // New and improved token factor.
1431       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1432     }
1433
1434     // Don't add users to work list.
1435     return CombineTo(N, Result, false);
1436   }
1437
1438   return Result;
1439 }
1440
1441 /// MERGE_VALUES can always be eliminated.
1442 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1443   WorkListRemover DeadNodes(*this);
1444   // Replacing results may cause a different MERGE_VALUES to suddenly
1445   // be CSE'd with N, and carry its uses with it. Iterate until no
1446   // uses remain, to ensure that the node can be safely deleted.
1447   // First add the users of this node to the work list so that they
1448   // can be tried again once they have new operands.
1449   AddUsersToWorkList(N);
1450   do {
1451     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1452       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1453   } while (!N->use_empty());
1454   removeFromWorkList(N);
1455   DAG.DeleteNode(N);
1456   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1457 }
1458
1459 static
1460 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1461                               SelectionDAG &DAG) {
1462   EVT VT = N0.getValueType();
1463   SDValue N00 = N0.getOperand(0);
1464   SDValue N01 = N0.getOperand(1);
1465   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1466
1467   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1468       isa<ConstantSDNode>(N00.getOperand(1))) {
1469     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1470     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1471                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1472                                  N00.getOperand(0), N01),
1473                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1474                                  N00.getOperand(1), N01));
1475     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1476   }
1477
1478   return SDValue();
1479 }
1480
1481 SDValue DAGCombiner::visitADD(SDNode *N) {
1482   SDValue N0 = N->getOperand(0);
1483   SDValue N1 = N->getOperand(1);
1484   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1485   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1486   EVT VT = N0.getValueType();
1487
1488   // fold vector ops
1489   if (VT.isVector()) {
1490     SDValue FoldedVOp = SimplifyVBinOp(N);
1491     if (FoldedVOp.getNode()) return FoldedVOp;
1492
1493     // fold (add x, 0) -> x, vector edition
1494     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1495       return N0;
1496     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1497       return N1;
1498   }
1499
1500   // fold (add x, undef) -> undef
1501   if (N0.getOpcode() == ISD::UNDEF)
1502     return N0;
1503   if (N1.getOpcode() == ISD::UNDEF)
1504     return N1;
1505   // fold (add c1, c2) -> c1+c2
1506   if (N0C && N1C)
1507     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1508   // canonicalize constant to RHS
1509   if (N0C && !N1C)
1510     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1511   // fold (add x, 0) -> x
1512   if (N1C && N1C->isNullValue())
1513     return N0;
1514   // fold (add Sym, c) -> Sym+c
1515   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1516     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1517         GA->getOpcode() == ISD::GlobalAddress)
1518       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1519                                   GA->getOffset() +
1520                                     (uint64_t)N1C->getSExtValue());
1521   // fold ((c1-A)+c2) -> (c1+c2)-A
1522   if (N1C && N0.getOpcode() == ISD::SUB)
1523     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1524       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1525                          DAG.getConstant(N1C->getAPIntValue()+
1526                                          N0C->getAPIntValue(), VT),
1527                          N0.getOperand(1));
1528   // reassociate add
1529   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1530   if (RADD.getNode())
1531     return RADD;
1532   // fold ((0-A) + B) -> B-A
1533   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1534       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1535     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1536   // fold (A + (0-B)) -> A-B
1537   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1538       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1539     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1540   // fold (A+(B-A)) -> B
1541   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1542     return N1.getOperand(0);
1543   // fold ((B-A)+A) -> B
1544   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1545     return N0.getOperand(0);
1546   // fold (A+(B-(A+C))) to (B-C)
1547   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1548       N0 == N1.getOperand(1).getOperand(0))
1549     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1550                        N1.getOperand(1).getOperand(1));
1551   // fold (A+(B-(C+A))) to (B-C)
1552   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1553       N0 == N1.getOperand(1).getOperand(1))
1554     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1555                        N1.getOperand(1).getOperand(0));
1556   // fold (A+((B-A)+or-C)) to (B+or-C)
1557   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1558       N1.getOperand(0).getOpcode() == ISD::SUB &&
1559       N0 == N1.getOperand(0).getOperand(1))
1560     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1561                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1562
1563   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1564   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1565     SDValue N00 = N0.getOperand(0);
1566     SDValue N01 = N0.getOperand(1);
1567     SDValue N10 = N1.getOperand(0);
1568     SDValue N11 = N1.getOperand(1);
1569
1570     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1571       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1572                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1573                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1574   }
1575
1576   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1577     return SDValue(N, 0);
1578
1579   // fold (a+b) -> (a|b) iff a and b share no bits.
1580   if (VT.isInteger() && !VT.isVector()) {
1581     APInt LHSZero, LHSOne;
1582     APInt RHSZero, RHSOne;
1583     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1584
1585     if (LHSZero.getBoolValue()) {
1586       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1587
1588       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1589       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1590       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1591         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1592           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1593       }
1594     }
1595   }
1596
1597   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1598   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1599     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1600     if (Result.getNode()) return Result;
1601   }
1602   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1603     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1604     if (Result.getNode()) return Result;
1605   }
1606
1607   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1608   if (N1.getOpcode() == ISD::SHL &&
1609       N1.getOperand(0).getOpcode() == ISD::SUB)
1610     if (ConstantSDNode *C =
1611           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1612       if (C->getAPIntValue() == 0)
1613         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1614                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1615                                        N1.getOperand(0).getOperand(1),
1616                                        N1.getOperand(1)));
1617   if (N0.getOpcode() == ISD::SHL &&
1618       N0.getOperand(0).getOpcode() == ISD::SUB)
1619     if (ConstantSDNode *C =
1620           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1621       if (C->getAPIntValue() == 0)
1622         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1623                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1624                                        N0.getOperand(0).getOperand(1),
1625                                        N0.getOperand(1)));
1626
1627   if (N1.getOpcode() == ISD::AND) {
1628     SDValue AndOp0 = N1.getOperand(0);
1629     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1630     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1631     unsigned DestBits = VT.getScalarType().getSizeInBits();
1632
1633     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1634     // and similar xforms where the inner op is either ~0 or 0.
1635     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1636       SDLoc DL(N);
1637       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1638     }
1639   }
1640
1641   // add (sext i1), X -> sub X, (zext i1)
1642   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1643       N0.getOperand(0).getValueType() == MVT::i1 &&
1644       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1645     SDLoc DL(N);
1646     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1647     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1648   }
1649
1650   return SDValue();
1651 }
1652
1653 SDValue DAGCombiner::visitADDC(SDNode *N) {
1654   SDValue N0 = N->getOperand(0);
1655   SDValue N1 = N->getOperand(1);
1656   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1657   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1658   EVT VT = N0.getValueType();
1659
1660   // If the flag result is dead, turn this into an ADD.
1661   if (!N->hasAnyUseOfValue(1))
1662     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1663                      DAG.getNode(ISD::CARRY_FALSE,
1664                                  SDLoc(N), MVT::Glue));
1665
1666   // canonicalize constant to RHS.
1667   if (N0C && !N1C)
1668     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1669
1670   // fold (addc x, 0) -> x + no carry out
1671   if (N1C && N1C->isNullValue())
1672     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1673                                         SDLoc(N), MVT::Glue));
1674
1675   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1676   APInt LHSZero, LHSOne;
1677   APInt RHSZero, RHSOne;
1678   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1679
1680   if (LHSZero.getBoolValue()) {
1681     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1682
1683     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1684     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1685     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1686       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1687                        DAG.getNode(ISD::CARRY_FALSE,
1688                                    SDLoc(N), MVT::Glue));
1689   }
1690
1691   return SDValue();
1692 }
1693
1694 SDValue DAGCombiner::visitADDE(SDNode *N) {
1695   SDValue N0 = N->getOperand(0);
1696   SDValue N1 = N->getOperand(1);
1697   SDValue CarryIn = N->getOperand(2);
1698   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1699   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1700
1701   // canonicalize constant to RHS
1702   if (N0C && !N1C)
1703     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1704                        N1, N0, CarryIn);
1705
1706   // fold (adde x, y, false) -> (addc x, y)
1707   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1708     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1709
1710   return SDValue();
1711 }
1712
1713 // Since it may not be valid to emit a fold to zero for vector initializers
1714 // check if we can before folding.
1715 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1716                              SelectionDAG &DAG,
1717                              bool LegalOperations, bool LegalTypes) {
1718   if (!VT.isVector())
1719     return DAG.getConstant(0, VT);
1720   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1721     return DAG.getConstant(0, VT);
1722   return SDValue();
1723 }
1724
1725 SDValue DAGCombiner::visitSUB(SDNode *N) {
1726   SDValue N0 = N->getOperand(0);
1727   SDValue N1 = N->getOperand(1);
1728   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1729   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1730   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1731     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1732   EVT VT = N0.getValueType();
1733
1734   // fold vector ops
1735   if (VT.isVector()) {
1736     SDValue FoldedVOp = SimplifyVBinOp(N);
1737     if (FoldedVOp.getNode()) return FoldedVOp;
1738
1739     // fold (sub x, 0) -> x, vector edition
1740     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1741       return N0;
1742   }
1743
1744   // fold (sub x, x) -> 0
1745   // FIXME: Refactor this and xor and other similar operations together.
1746   if (N0 == N1)
1747     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1748   // fold (sub c1, c2) -> c1-c2
1749   if (N0C && N1C)
1750     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1751   // fold (sub x, c) -> (add x, -c)
1752   if (N1C)
1753     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1754                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1755   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1756   if (N0C && N0C->isAllOnesValue())
1757     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1758   // fold A-(A-B) -> B
1759   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1760     return N1.getOperand(1);
1761   // fold (A+B)-A -> B
1762   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1763     return N0.getOperand(1);
1764   // fold (A+B)-B -> A
1765   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1766     return N0.getOperand(0);
1767   // fold C2-(A+C1) -> (C2-C1)-A
1768   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1769     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1770                                    VT);
1771     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1772                        N1.getOperand(0));
1773   }
1774   // fold ((A+(B+or-C))-B) -> A+or-C
1775   if (N0.getOpcode() == ISD::ADD &&
1776       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1777        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1778       N0.getOperand(1).getOperand(0) == N1)
1779     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1780                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1781   // fold ((A+(C+B))-B) -> A+C
1782   if (N0.getOpcode() == ISD::ADD &&
1783       N0.getOperand(1).getOpcode() == ISD::ADD &&
1784       N0.getOperand(1).getOperand(1) == N1)
1785     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1786                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1787   // fold ((A-(B-C))-C) -> A-B
1788   if (N0.getOpcode() == ISD::SUB &&
1789       N0.getOperand(1).getOpcode() == ISD::SUB &&
1790       N0.getOperand(1).getOperand(1) == N1)
1791     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1792                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1793
1794   // If either operand of a sub is undef, the result is undef
1795   if (N0.getOpcode() == ISD::UNDEF)
1796     return N0;
1797   if (N1.getOpcode() == ISD::UNDEF)
1798     return N1;
1799
1800   // If the relocation model supports it, consider symbol offsets.
1801   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1802     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1803       // fold (sub Sym, c) -> Sym-c
1804       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1805         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1806                                     GA->getOffset() -
1807                                       (uint64_t)N1C->getSExtValue());
1808       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1809       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1810         if (GA->getGlobal() == GB->getGlobal())
1811           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1812                                  VT);
1813     }
1814
1815   return SDValue();
1816 }
1817
1818 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1819   SDValue N0 = N->getOperand(0);
1820   SDValue N1 = N->getOperand(1);
1821   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1822   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1823   EVT VT = N0.getValueType();
1824
1825   // If the flag result is dead, turn this into an SUB.
1826   if (!N->hasAnyUseOfValue(1))
1827     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1828                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1829                                  MVT::Glue));
1830
1831   // fold (subc x, x) -> 0 + no borrow
1832   if (N0 == N1)
1833     return CombineTo(N, DAG.getConstant(0, VT),
1834                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1835                                  MVT::Glue));
1836
1837   // fold (subc x, 0) -> x + no borrow
1838   if (N1C && N1C->isNullValue())
1839     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1840                                         MVT::Glue));
1841
1842   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1843   if (N0C && N0C->isAllOnesValue())
1844     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1845                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1846                                  MVT::Glue));
1847
1848   return SDValue();
1849 }
1850
1851 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1852   SDValue N0 = N->getOperand(0);
1853   SDValue N1 = N->getOperand(1);
1854   SDValue CarryIn = N->getOperand(2);
1855
1856   // fold (sube x, y, false) -> (subc x, y)
1857   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1858     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1859
1860   return SDValue();
1861 }
1862
1863 SDValue DAGCombiner::visitMUL(SDNode *N) {
1864   SDValue N0 = N->getOperand(0);
1865   SDValue N1 = N->getOperand(1);
1866   EVT VT = N0.getValueType();
1867
1868   // fold (mul x, undef) -> 0
1869   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1870     return DAG.getConstant(0, VT);
1871
1872   bool N0IsConst = false;
1873   bool N1IsConst = false;
1874   APInt ConstValue0, ConstValue1;
1875   // fold vector ops
1876   if (VT.isVector()) {
1877     SDValue FoldedVOp = SimplifyVBinOp(N);
1878     if (FoldedVOp.getNode()) return FoldedVOp;
1879
1880     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1881     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1882   } else {
1883     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1884     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1885                             : APInt();
1886     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1887     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1888                             : APInt();
1889   }
1890
1891   // fold (mul c1, c2) -> c1*c2
1892   if (N0IsConst && N1IsConst)
1893     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1894
1895   // canonicalize constant to RHS
1896   if (N0IsConst && !N1IsConst)
1897     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1898   // fold (mul x, 0) -> 0
1899   if (N1IsConst && ConstValue1 == 0)
1900     return N1;
1901   // We require a splat of the entire scalar bit width for non-contiguous
1902   // bit patterns.
1903   bool IsFullSplat =
1904     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1905   // fold (mul x, 1) -> x
1906   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1907     return N0;
1908   // fold (mul x, -1) -> 0-x
1909   if (N1IsConst && ConstValue1.isAllOnesValue())
1910     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1911                        DAG.getConstant(0, VT), N0);
1912   // fold (mul x, (1 << c)) -> x << c
1913   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1914     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1915                        DAG.getConstant(ConstValue1.logBase2(),
1916                                        getShiftAmountTy(N0.getValueType())));
1917   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1918   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1919     unsigned Log2Val = (-ConstValue1).logBase2();
1920     // FIXME: If the input is something that is easily negated (e.g. a
1921     // single-use add), we should put the negate there.
1922     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1923                        DAG.getConstant(0, VT),
1924                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1925                             DAG.getConstant(Log2Val,
1926                                       getShiftAmountTy(N0.getValueType()))));
1927   }
1928
1929   APInt Val;
1930   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1931   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1932       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1933                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1934     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1935                              N1, N0.getOperand(1));
1936     AddToWorkList(C3.getNode());
1937     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1938                        N0.getOperand(0), C3);
1939   }
1940
1941   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1942   // use.
1943   {
1944     SDValue Sh(nullptr,0), Y(nullptr,0);
1945     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1946     if (N0.getOpcode() == ISD::SHL &&
1947         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1948                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1949         N0.getNode()->hasOneUse()) {
1950       Sh = N0; Y = N1;
1951     } else if (N1.getOpcode() == ISD::SHL &&
1952                isa<ConstantSDNode>(N1.getOperand(1)) &&
1953                N1.getNode()->hasOneUse()) {
1954       Sh = N1; Y = N0;
1955     }
1956
1957     if (Sh.getNode()) {
1958       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1959                                 Sh.getOperand(0), Y);
1960       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1961                          Mul, Sh.getOperand(1));
1962     }
1963   }
1964
1965   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1966   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1967       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1968                      isa<ConstantSDNode>(N0.getOperand(1))))
1969     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1970                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1971                                    N0.getOperand(0), N1),
1972                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1973                                    N0.getOperand(1), N1));
1974
1975   // reassociate mul
1976   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1977   if (RMUL.getNode())
1978     return RMUL;
1979
1980   return SDValue();
1981 }
1982
1983 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1984   SDValue N0 = N->getOperand(0);
1985   SDValue N1 = N->getOperand(1);
1986   ConstantSDNode *N0C = isConstOrConstSplat(N0);
1987   ConstantSDNode *N1C = isConstOrConstSplat(N1);
1988   EVT VT = N->getValueType(0);
1989
1990   // fold vector ops
1991   if (VT.isVector()) {
1992     SDValue FoldedVOp = SimplifyVBinOp(N);
1993     if (FoldedVOp.getNode()) return FoldedVOp;
1994   }
1995
1996   // fold (sdiv c1, c2) -> c1/c2
1997   if (N0C && N1C && !N1C->isNullValue())
1998     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1999   // fold (sdiv X, 1) -> X
2000   if (N1C && N1C->getAPIntValue() == 1LL)
2001     return N0;
2002   // fold (sdiv X, -1) -> 0-X
2003   if (N1C && N1C->isAllOnesValue())
2004     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2005                        DAG.getConstant(0, VT), N0);
2006   // If we know the sign bits of both operands are zero, strength reduce to a
2007   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2008   if (!VT.isVector()) {
2009     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2010       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2011                          N0, N1);
2012   }
2013
2014   // fold (sdiv X, pow2) -> simple ops after legalize
2015   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2016                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2017     // If dividing by powers of two is cheap, then don't perform the following
2018     // fold.
2019     if (TLI.isPow2DivCheap())
2020       return SDValue();
2021
2022     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2023
2024     // Splat the sign bit into the register
2025     SDValue SGN =
2026         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2027                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2028                                     getShiftAmountTy(N0.getValueType())));
2029     AddToWorkList(SGN.getNode());
2030
2031     // Add (N0 < 0) ? abs2 - 1 : 0;
2032     SDValue SRL =
2033         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2034                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2035                                     getShiftAmountTy(SGN.getValueType())));
2036     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2037     AddToWorkList(SRL.getNode());
2038     AddToWorkList(ADD.getNode());    // Divide by pow2
2039     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2040                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2041
2042     // If we're dividing by a positive value, we're done.  Otherwise, we must
2043     // negate the result.
2044     if (N1C->getAPIntValue().isNonNegative())
2045       return SRA;
2046
2047     AddToWorkList(SRA.getNode());
2048     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2049   }
2050
2051   // if integer divide is expensive and we satisfy the requirements, emit an
2052   // alternate sequence.
2053   if (N1C && !TLI.isIntDivCheap()) {
2054     SDValue Op = BuildSDIV(N);
2055     if (Op.getNode()) return Op;
2056   }
2057
2058   // undef / X -> 0
2059   if (N0.getOpcode() == ISD::UNDEF)
2060     return DAG.getConstant(0, VT);
2061   // X / undef -> undef
2062   if (N1.getOpcode() == ISD::UNDEF)
2063     return N1;
2064
2065   return SDValue();
2066 }
2067
2068 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2069   SDValue N0 = N->getOperand(0);
2070   SDValue N1 = N->getOperand(1);
2071   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2072   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2073   EVT VT = N->getValueType(0);
2074
2075   // fold vector ops
2076   if (VT.isVector()) {
2077     SDValue FoldedVOp = SimplifyVBinOp(N);
2078     if (FoldedVOp.getNode()) return FoldedVOp;
2079   }
2080
2081   // fold (udiv c1, c2) -> c1/c2
2082   if (N0C && N1C && !N1C->isNullValue())
2083     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2084   // fold (udiv x, (1 << c)) -> x >>u c
2085   if (N1C && N1C->getAPIntValue().isPowerOf2())
2086     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2087                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2088                                        getShiftAmountTy(N0.getValueType())));
2089   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2090   if (N1.getOpcode() == ISD::SHL) {
2091     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2092       if (SHC->getAPIntValue().isPowerOf2()) {
2093         EVT ADDVT = N1.getOperand(1).getValueType();
2094         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2095                                   N1.getOperand(1),
2096                                   DAG.getConstant(SHC->getAPIntValue()
2097                                                                   .logBase2(),
2098                                                   ADDVT));
2099         AddToWorkList(Add.getNode());
2100         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2101       }
2102     }
2103   }
2104   // fold (udiv x, c) -> alternate
2105   if (N1C && !TLI.isIntDivCheap()) {
2106     SDValue Op = BuildUDIV(N);
2107     if (Op.getNode()) return Op;
2108   }
2109
2110   // undef / X -> 0
2111   if (N0.getOpcode() == ISD::UNDEF)
2112     return DAG.getConstant(0, VT);
2113   // X / undef -> undef
2114   if (N1.getOpcode() == ISD::UNDEF)
2115     return N1;
2116
2117   return SDValue();
2118 }
2119
2120 SDValue DAGCombiner::visitSREM(SDNode *N) {
2121   SDValue N0 = N->getOperand(0);
2122   SDValue N1 = N->getOperand(1);
2123   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2124   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2125   EVT VT = N->getValueType(0);
2126
2127   // fold (srem c1, c2) -> c1%c2
2128   if (N0C && N1C && !N1C->isNullValue())
2129     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2130   // If we know the sign bits of both operands are zero, strength reduce to a
2131   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2132   if (!VT.isVector()) {
2133     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2134       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2135   }
2136
2137   // If X/C can be simplified by the division-by-constant logic, lower
2138   // X%C to the equivalent of X-X/C*C.
2139   if (N1C && !N1C->isNullValue()) {
2140     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2141     AddToWorkList(Div.getNode());
2142     SDValue OptimizedDiv = combine(Div.getNode());
2143     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2144       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2145                                 OptimizedDiv, N1);
2146       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2147       AddToWorkList(Mul.getNode());
2148       return Sub;
2149     }
2150   }
2151
2152   // undef % X -> 0
2153   if (N0.getOpcode() == ISD::UNDEF)
2154     return DAG.getConstant(0, VT);
2155   // X % undef -> undef
2156   if (N1.getOpcode() == ISD::UNDEF)
2157     return N1;
2158
2159   return SDValue();
2160 }
2161
2162 SDValue DAGCombiner::visitUREM(SDNode *N) {
2163   SDValue N0 = N->getOperand(0);
2164   SDValue N1 = N->getOperand(1);
2165   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2166   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2167   EVT VT = N->getValueType(0);
2168
2169   // fold (urem c1, c2) -> c1%c2
2170   if (N0C && N1C && !N1C->isNullValue())
2171     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2172   // fold (urem x, pow2) -> (and x, pow2-1)
2173   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2174     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2175                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2176   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2177   if (N1.getOpcode() == ISD::SHL) {
2178     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2179       if (SHC->getAPIntValue().isPowerOf2()) {
2180         SDValue Add =
2181           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2182                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2183                                  VT));
2184         AddToWorkList(Add.getNode());
2185         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2186       }
2187     }
2188   }
2189
2190   // If X/C can be simplified by the division-by-constant logic, lower
2191   // X%C to the equivalent of X-X/C*C.
2192   if (N1C && !N1C->isNullValue()) {
2193     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2194     AddToWorkList(Div.getNode());
2195     SDValue OptimizedDiv = combine(Div.getNode());
2196     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2197       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2198                                 OptimizedDiv, N1);
2199       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2200       AddToWorkList(Mul.getNode());
2201       return Sub;
2202     }
2203   }
2204
2205   // undef % X -> 0
2206   if (N0.getOpcode() == ISD::UNDEF)
2207     return DAG.getConstant(0, VT);
2208   // X % undef -> undef
2209   if (N1.getOpcode() == ISD::UNDEF)
2210     return N1;
2211
2212   return SDValue();
2213 }
2214
2215 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2216   SDValue N0 = N->getOperand(0);
2217   SDValue N1 = N->getOperand(1);
2218   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2219   EVT VT = N->getValueType(0);
2220   SDLoc DL(N);
2221
2222   // fold (mulhs x, 0) -> 0
2223   if (N1C && N1C->isNullValue())
2224     return N1;
2225   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2226   if (N1C && N1C->getAPIntValue() == 1)
2227     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2228                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2229                                        getShiftAmountTy(N0.getValueType())));
2230   // fold (mulhs x, undef) -> 0
2231   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2232     return DAG.getConstant(0, VT);
2233
2234   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2235   // plus a shift.
2236   if (VT.isSimple() && !VT.isVector()) {
2237     MVT Simple = VT.getSimpleVT();
2238     unsigned SimpleSize = Simple.getSizeInBits();
2239     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2240     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2241       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2242       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2243       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2244       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2245             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2246       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2247     }
2248   }
2249
2250   return SDValue();
2251 }
2252
2253 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2254   SDValue N0 = N->getOperand(0);
2255   SDValue N1 = N->getOperand(1);
2256   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2257   EVT VT = N->getValueType(0);
2258   SDLoc DL(N);
2259
2260   // fold (mulhu x, 0) -> 0
2261   if (N1C && N1C->isNullValue())
2262     return N1;
2263   // fold (mulhu x, 1) -> 0
2264   if (N1C && N1C->getAPIntValue() == 1)
2265     return DAG.getConstant(0, N0.getValueType());
2266   // fold (mulhu x, undef) -> 0
2267   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2268     return DAG.getConstant(0, VT);
2269
2270   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2271   // plus a shift.
2272   if (VT.isSimple() && !VT.isVector()) {
2273     MVT Simple = VT.getSimpleVT();
2274     unsigned SimpleSize = Simple.getSizeInBits();
2275     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2276     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2277       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2278       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2279       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2280       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2281             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2282       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2283     }
2284   }
2285
2286   return SDValue();
2287 }
2288
2289 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2290 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2291 /// that are being performed. Return true if a simplification was made.
2292 ///
2293 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2294                                                 unsigned HiOp) {
2295   // If the high half is not needed, just compute the low half.
2296   bool HiExists = N->hasAnyUseOfValue(1);
2297   if (!HiExists &&
2298       (!LegalOperations ||
2299        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2300     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2301                               ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2302     return CombineTo(N, Res, Res);
2303   }
2304
2305   // If the low half is not needed, just compute the high half.
2306   bool LoExists = N->hasAnyUseOfValue(0);
2307   if (!LoExists &&
2308       (!LegalOperations ||
2309        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2310     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2311                               ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2312     return CombineTo(N, Res, Res);
2313   }
2314
2315   // If both halves are used, return as it is.
2316   if (LoExists && HiExists)
2317     return SDValue();
2318
2319   // If the two computed results can be simplified separately, separate them.
2320   if (LoExists) {
2321     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2322                              ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2323     AddToWorkList(Lo.getNode());
2324     SDValue LoOpt = combine(Lo.getNode());
2325     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2326         (!LegalOperations ||
2327          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2328       return CombineTo(N, LoOpt, LoOpt);
2329   }
2330
2331   if (HiExists) {
2332     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2333                              ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2334     AddToWorkList(Hi.getNode());
2335     SDValue HiOpt = combine(Hi.getNode());
2336     if (HiOpt.getNode() && HiOpt != Hi &&
2337         (!LegalOperations ||
2338          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2339       return CombineTo(N, HiOpt, HiOpt);
2340   }
2341
2342   return SDValue();
2343 }
2344
2345 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2346   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2347   if (Res.getNode()) return Res;
2348
2349   EVT VT = N->getValueType(0);
2350   SDLoc DL(N);
2351
2352   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2353   // plus a shift.
2354   if (VT.isSimple() && !VT.isVector()) {
2355     MVT Simple = VT.getSimpleVT();
2356     unsigned SimpleSize = Simple.getSizeInBits();
2357     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2358     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2359       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2360       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2361       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2362       // Compute the high part as N1.
2363       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2364             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2365       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2366       // Compute the low part as N0.
2367       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2368       return CombineTo(N, Lo, Hi);
2369     }
2370   }
2371
2372   return SDValue();
2373 }
2374
2375 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2376   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2377   if (Res.getNode()) return Res;
2378
2379   EVT VT = N->getValueType(0);
2380   SDLoc DL(N);
2381
2382   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2383   // plus a shift.
2384   if (VT.isSimple() && !VT.isVector()) {
2385     MVT Simple = VT.getSimpleVT();
2386     unsigned SimpleSize = Simple.getSizeInBits();
2387     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2388     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2389       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2390       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2391       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2392       // Compute the high part as N1.
2393       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2394             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2395       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2396       // Compute the low part as N0.
2397       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2398       return CombineTo(N, Lo, Hi);
2399     }
2400   }
2401
2402   return SDValue();
2403 }
2404
2405 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2406   // (smulo x, 2) -> (saddo x, x)
2407   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2408     if (C2->getAPIntValue() == 2)
2409       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2410                          N->getOperand(0), N->getOperand(0));
2411
2412   return SDValue();
2413 }
2414
2415 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2416   // (umulo x, 2) -> (uaddo x, x)
2417   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2418     if (C2->getAPIntValue() == 2)
2419       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2420                          N->getOperand(0), N->getOperand(0));
2421
2422   return SDValue();
2423 }
2424
2425 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2426   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2427   if (Res.getNode()) return Res;
2428
2429   return SDValue();
2430 }
2431
2432 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2433   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2434   if (Res.getNode()) return Res;
2435
2436   return SDValue();
2437 }
2438
2439 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2440 /// two operands of the same opcode, try to simplify it.
2441 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2442   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2443   EVT VT = N0.getValueType();
2444   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2445
2446   // Bail early if none of these transforms apply.
2447   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2448
2449   // For each of OP in AND/OR/XOR:
2450   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2451   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2452   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2453   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2454   //
2455   // do not sink logical op inside of a vector extend, since it may combine
2456   // into a vsetcc.
2457   EVT Op0VT = N0.getOperand(0).getValueType();
2458   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2459        N0.getOpcode() == ISD::SIGN_EXTEND ||
2460        // Avoid infinite looping with PromoteIntBinOp.
2461        (N0.getOpcode() == ISD::ANY_EXTEND &&
2462         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2463        (N0.getOpcode() == ISD::TRUNCATE &&
2464         (!TLI.isZExtFree(VT, Op0VT) ||
2465          !TLI.isTruncateFree(Op0VT, VT)) &&
2466         TLI.isTypeLegal(Op0VT))) &&
2467       !VT.isVector() &&
2468       Op0VT == N1.getOperand(0).getValueType() &&
2469       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2470     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2471                                  N0.getOperand(0).getValueType(),
2472                                  N0.getOperand(0), N1.getOperand(0));
2473     AddToWorkList(ORNode.getNode());
2474     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2475   }
2476
2477   // For each of OP in SHL/SRL/SRA/AND...
2478   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2479   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2480   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2481   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2482        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2483       N0.getOperand(1) == N1.getOperand(1)) {
2484     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2485                                  N0.getOperand(0).getValueType(),
2486                                  N0.getOperand(0), N1.getOperand(0));
2487     AddToWorkList(ORNode.getNode());
2488     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2489                        ORNode, N0.getOperand(1));
2490   }
2491
2492   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2493   // Only perform this optimization after type legalization and before
2494   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2495   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2496   // we don't want to undo this promotion.
2497   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2498   // on scalars.
2499   if ((N0.getOpcode() == ISD::BITCAST ||
2500        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2501       Level == AfterLegalizeTypes) {
2502     SDValue In0 = N0.getOperand(0);
2503     SDValue In1 = N1.getOperand(0);
2504     EVT In0Ty = In0.getValueType();
2505     EVT In1Ty = In1.getValueType();
2506     SDLoc DL(N);
2507     // If both incoming values are integers, and the original types are the
2508     // same.
2509     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2510       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2511       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2512       AddToWorkList(Op.getNode());
2513       return BC;
2514     }
2515   }
2516
2517   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2518   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2519   // If both shuffles use the same mask, and both shuffle within a single
2520   // vector, then it is worthwhile to move the swizzle after the operation.
2521   // The type-legalizer generates this pattern when loading illegal
2522   // vector types from memory. In many cases this allows additional shuffle
2523   // optimizations.
2524   // There are other cases where moving the shuffle after the xor/and/or
2525   // is profitable even if shuffles don't perform a swizzle.
2526   // If both shuffles use the same mask, and both shuffles have the same first
2527   // or second operand, then it might still be profitable to move the shuffle
2528   // after the xor/and/or operation.
2529   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2530     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2531     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2532
2533     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2534            "Inputs to shuffles are not the same type");
2535
2536     // Check that both shuffles use the same mask. The masks are known to be of
2537     // the same length because the result vector type is the same.
2538     // Check also that shuffles have only one use to avoid introducing extra
2539     // instructions.
2540     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2541         SVN0->getMask().equals(SVN1->getMask())) {
2542       SDValue ShOp = N0->getOperand(1);
2543
2544       // Don't try to fold this node if it requires introducing a
2545       // build vector of all zeros that might be illegal at this stage.
2546       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2547         if (!LegalTypes)
2548           ShOp = DAG.getConstant(0, VT);
2549         else
2550           ShOp = SDValue();
2551       }
2552
2553       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2554       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2555       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2556       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2557         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2558                                       N0->getOperand(0), N1->getOperand(0));
2559         AddToWorkList(NewNode.getNode());
2560         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2561                                     &SVN0->getMask()[0]);
2562       }
2563
2564       // Don't try to fold this node if it requires introducing a
2565       // build vector of all zeros that might be illegal at this stage.
2566       ShOp = N0->getOperand(0);
2567       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2568         if (!LegalTypes)
2569           ShOp = DAG.getConstant(0, VT);
2570         else
2571           ShOp = SDValue();
2572       }
2573
2574       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2575       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2576       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2577       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2578         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2579                                       N0->getOperand(1), N1->getOperand(1));
2580         AddToWorkList(NewNode.getNode());
2581         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2582                                     &SVN0->getMask()[0]);
2583       }
2584     }
2585   }
2586
2587   return SDValue();
2588 }
2589
2590 SDValue DAGCombiner::visitAND(SDNode *N) {
2591   SDValue N0 = N->getOperand(0);
2592   SDValue N1 = N->getOperand(1);
2593   SDValue LL, LR, RL, RR, CC0, CC1;
2594   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2595   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2596   EVT VT = N1.getValueType();
2597   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2598
2599   // fold vector ops
2600   if (VT.isVector()) {
2601     SDValue FoldedVOp = SimplifyVBinOp(N);
2602     if (FoldedVOp.getNode()) return FoldedVOp;
2603
2604     // fold (and x, 0) -> 0, vector edition
2605     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2606       return N0;
2607     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2608       return N1;
2609
2610     // fold (and x, -1) -> x, vector edition
2611     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2612       return N1;
2613     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2614       return N0;
2615   }
2616
2617   // fold (and x, undef) -> 0
2618   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2619     return DAG.getConstant(0, VT);
2620   // fold (and c1, c2) -> c1&c2
2621   if (N0C && N1C)
2622     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2623   // canonicalize constant to RHS
2624   if (N0C && !N1C)
2625     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2626   // fold (and x, -1) -> x
2627   if (N1C && N1C->isAllOnesValue())
2628     return N0;
2629   // if (and x, c) is known to be zero, return 0
2630   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2631                                    APInt::getAllOnesValue(BitWidth)))
2632     return DAG.getConstant(0, VT);
2633   // reassociate and
2634   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2635   if (RAND.getNode())
2636     return RAND;
2637   // fold (and (or x, C), D) -> D if (C & D) == D
2638   if (N1C && N0.getOpcode() == ISD::OR)
2639     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2640       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2641         return N1;
2642   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2643   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2644     SDValue N0Op0 = N0.getOperand(0);
2645     APInt Mask = ~N1C->getAPIntValue();
2646     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2647     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2648       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2649                                  N0.getValueType(), N0Op0);
2650
2651       // Replace uses of the AND with uses of the Zero extend node.
2652       CombineTo(N, Zext);
2653
2654       // We actually want to replace all uses of the any_extend with the
2655       // zero_extend, to avoid duplicating things.  This will later cause this
2656       // AND to be folded.
2657       CombineTo(N0.getNode(), Zext);
2658       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2659     }
2660   }
2661   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2662   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2663   // already be zero by virtue of the width of the base type of the load.
2664   //
2665   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2666   // more cases.
2667   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2668        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2669       N0.getOpcode() == ISD::LOAD) {
2670     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2671                                          N0 : N0.getOperand(0) );
2672
2673     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2674     // This can be a pure constant or a vector splat, in which case we treat the
2675     // vector as a scalar and use the splat value.
2676     APInt Constant = APInt::getNullValue(1);
2677     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2678       Constant = C->getAPIntValue();
2679     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2680       APInt SplatValue, SplatUndef;
2681       unsigned SplatBitSize;
2682       bool HasAnyUndefs;
2683       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2684                                              SplatBitSize, HasAnyUndefs);
2685       if (IsSplat) {
2686         // Undef bits can contribute to a possible optimisation if set, so
2687         // set them.
2688         SplatValue |= SplatUndef;
2689
2690         // The splat value may be something like "0x00FFFFFF", which means 0 for
2691         // the first vector value and FF for the rest, repeating. We need a mask
2692         // that will apply equally to all members of the vector, so AND all the
2693         // lanes of the constant together.
2694         EVT VT = Vector->getValueType(0);
2695         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2696
2697         // If the splat value has been compressed to a bitlength lower
2698         // than the size of the vector lane, we need to re-expand it to
2699         // the lane size.
2700         if (BitWidth > SplatBitSize)
2701           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2702                SplatBitSize < BitWidth;
2703                SplatBitSize = SplatBitSize * 2)
2704             SplatValue |= SplatValue.shl(SplatBitSize);
2705
2706         Constant = APInt::getAllOnesValue(BitWidth);
2707         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2708           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2709       }
2710     }
2711
2712     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2713     // actually legal and isn't going to get expanded, else this is a false
2714     // optimisation.
2715     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2716                                                     Load->getMemoryVT());
2717
2718     // Resize the constant to the same size as the original memory access before
2719     // extension. If it is still the AllOnesValue then this AND is completely
2720     // unneeded.
2721     Constant =
2722       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2723
2724     bool B;
2725     switch (Load->getExtensionType()) {
2726     default: B = false; break;
2727     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2728     case ISD::ZEXTLOAD:
2729     case ISD::NON_EXTLOAD: B = true; break;
2730     }
2731
2732     if (B && Constant.isAllOnesValue()) {
2733       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2734       // preserve semantics once we get rid of the AND.
2735       SDValue NewLoad(Load, 0);
2736       if (Load->getExtensionType() == ISD::EXTLOAD) {
2737         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2738                               Load->getValueType(0), SDLoc(Load),
2739                               Load->getChain(), Load->getBasePtr(),
2740                               Load->getOffset(), Load->getMemoryVT(),
2741                               Load->getMemOperand());
2742         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2743         if (Load->getNumValues() == 3) {
2744           // PRE/POST_INC loads have 3 values.
2745           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2746                            NewLoad.getValue(2) };
2747           CombineTo(Load, To, 3, true);
2748         } else {
2749           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2750         }
2751       }
2752
2753       // Fold the AND away, taking care not to fold to the old load node if we
2754       // replaced it.
2755       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2756
2757       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2758     }
2759   }
2760   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2761   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2762     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2763     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2764
2765     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2766         LL.getValueType().isInteger()) {
2767       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2768       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2769         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2770                                      LR.getValueType(), LL, RL);
2771         AddToWorkList(ORNode.getNode());
2772         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2773       }
2774       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2775       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2776         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2777                                       LR.getValueType(), LL, RL);
2778         AddToWorkList(ANDNode.getNode());
2779         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2780       }
2781       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2782       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2783         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2784                                      LR.getValueType(), LL, RL);
2785         AddToWorkList(ORNode.getNode());
2786         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2787       }
2788     }
2789     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2790     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2791         Op0 == Op1 && LL.getValueType().isInteger() &&
2792       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2793                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2794                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2795                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2796       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2797                                     LL, DAG.getConstant(1, LL.getValueType()));
2798       AddToWorkList(ADDNode.getNode());
2799       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2800                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2801     }
2802     // canonicalize equivalent to ll == rl
2803     if (LL == RR && LR == RL) {
2804       Op1 = ISD::getSetCCSwappedOperands(Op1);
2805       std::swap(RL, RR);
2806     }
2807     if (LL == RL && LR == RR) {
2808       bool isInteger = LL.getValueType().isInteger();
2809       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2810       if (Result != ISD::SETCC_INVALID &&
2811           (!LegalOperations ||
2812            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2813             TLI.isOperationLegal(ISD::SETCC,
2814                             getSetCCResultType(N0.getSimpleValueType())))))
2815         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2816                             LL, LR, Result);
2817     }
2818   }
2819
2820   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2821   if (N0.getOpcode() == N1.getOpcode()) {
2822     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2823     if (Tmp.getNode()) return Tmp;
2824   }
2825
2826   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2827   // fold (and (sra)) -> (and (srl)) when possible.
2828   if (!VT.isVector() &&
2829       SimplifyDemandedBits(SDValue(N, 0)))
2830     return SDValue(N, 0);
2831
2832   // fold (zext_inreg (extload x)) -> (zextload x)
2833   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2834     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2835     EVT MemVT = LN0->getMemoryVT();
2836     // If we zero all the possible extended bits, then we can turn this into
2837     // a zextload if we are running before legalize or the operation is legal.
2838     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2839     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2840                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2841         ((!LegalOperations && !LN0->isVolatile()) ||
2842          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2843       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2844                                        LN0->getChain(), LN0->getBasePtr(),
2845                                        MemVT, LN0->getMemOperand());
2846       AddToWorkList(N);
2847       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2848       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2849     }
2850   }
2851   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2852   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2853       N0.hasOneUse()) {
2854     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2855     EVT MemVT = LN0->getMemoryVT();
2856     // If we zero all the possible extended bits, then we can turn this into
2857     // a zextload if we are running before legalize or the operation is legal.
2858     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2859     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2860                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2861         ((!LegalOperations && !LN0->isVolatile()) ||
2862          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2863       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2864                                        LN0->getChain(), LN0->getBasePtr(),
2865                                        MemVT, LN0->getMemOperand());
2866       AddToWorkList(N);
2867       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2868       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2869     }
2870   }
2871
2872   // fold (and (load x), 255) -> (zextload x, i8)
2873   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2874   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2875   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2876               (N0.getOpcode() == ISD::ANY_EXTEND &&
2877                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2878     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2879     LoadSDNode *LN0 = HasAnyExt
2880       ? cast<LoadSDNode>(N0.getOperand(0))
2881       : cast<LoadSDNode>(N0);
2882     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2883         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2884       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2885       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2886         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2887         EVT LoadedVT = LN0->getMemoryVT();
2888
2889         if (ExtVT == LoadedVT &&
2890             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2891           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2892
2893           SDValue NewLoad =
2894             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2895                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2896                            LN0->getMemOperand());
2897           AddToWorkList(N);
2898           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2899           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2900         }
2901
2902         // Do not change the width of a volatile load.
2903         // Do not generate loads of non-round integer types since these can
2904         // be expensive (and would be wrong if the type is not byte sized).
2905         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2906             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2907           EVT PtrType = LN0->getOperand(1).getValueType();
2908
2909           unsigned Alignment = LN0->getAlignment();
2910           SDValue NewPtr = LN0->getBasePtr();
2911
2912           // For big endian targets, we need to add an offset to the pointer
2913           // to load the correct bytes.  For little endian systems, we merely
2914           // need to read fewer bytes from the same pointer.
2915           if (TLI.isBigEndian()) {
2916             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2917             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2918             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2919             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2920                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2921             Alignment = MinAlign(Alignment, PtrOff);
2922           }
2923
2924           AddToWorkList(NewPtr.getNode());
2925
2926           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2927           SDValue Load =
2928             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2929                            LN0->getChain(), NewPtr,
2930                            LN0->getPointerInfo(),
2931                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2932                            Alignment, LN0->getTBAAInfo());
2933           AddToWorkList(N);
2934           CombineTo(LN0, Load, Load.getValue(1));
2935           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2936         }
2937       }
2938     }
2939   }
2940
2941   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2942       VT.getSizeInBits() <= 64) {
2943     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2944       APInt ADDC = ADDI->getAPIntValue();
2945       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2946         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2947         // immediate for an add, but it is legal if its top c2 bits are set,
2948         // transform the ADD so the immediate doesn't need to be materialized
2949         // in a register.
2950         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2951           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2952                                              SRLI->getZExtValue());
2953           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2954             ADDC |= Mask;
2955             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2956               SDValue NewAdd =
2957                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2958                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2959               CombineTo(N0.getNode(), NewAdd);
2960               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2961             }
2962           }
2963         }
2964       }
2965     }
2966   }
2967
2968   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2969   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2970     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2971                                        N0.getOperand(1), false);
2972     if (BSwap.getNode())
2973       return BSwap;
2974   }
2975
2976   return SDValue();
2977 }
2978
2979 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2980 ///
2981 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2982                                         bool DemandHighBits) {
2983   if (!LegalOperations)
2984     return SDValue();
2985
2986   EVT VT = N->getValueType(0);
2987   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2988     return SDValue();
2989   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2990     return SDValue();
2991
2992   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2993   bool LookPassAnd0 = false;
2994   bool LookPassAnd1 = false;
2995   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2996       std::swap(N0, N1);
2997   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2998       std::swap(N0, N1);
2999   if (N0.getOpcode() == ISD::AND) {
3000     if (!N0.getNode()->hasOneUse())
3001       return SDValue();
3002     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3003     if (!N01C || N01C->getZExtValue() != 0xFF00)
3004       return SDValue();
3005     N0 = N0.getOperand(0);
3006     LookPassAnd0 = true;
3007   }
3008
3009   if (N1.getOpcode() == ISD::AND) {
3010     if (!N1.getNode()->hasOneUse())
3011       return SDValue();
3012     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3013     if (!N11C || N11C->getZExtValue() != 0xFF)
3014       return SDValue();
3015     N1 = N1.getOperand(0);
3016     LookPassAnd1 = true;
3017   }
3018
3019   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3020     std::swap(N0, N1);
3021   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3022     return SDValue();
3023   if (!N0.getNode()->hasOneUse() ||
3024       !N1.getNode()->hasOneUse())
3025     return SDValue();
3026
3027   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3028   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3029   if (!N01C || !N11C)
3030     return SDValue();
3031   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3032     return SDValue();
3033
3034   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3035   SDValue N00 = N0->getOperand(0);
3036   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3037     if (!N00.getNode()->hasOneUse())
3038       return SDValue();
3039     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3040     if (!N001C || N001C->getZExtValue() != 0xFF)
3041       return SDValue();
3042     N00 = N00.getOperand(0);
3043     LookPassAnd0 = true;
3044   }
3045
3046   SDValue N10 = N1->getOperand(0);
3047   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3048     if (!N10.getNode()->hasOneUse())
3049       return SDValue();
3050     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3051     if (!N101C || N101C->getZExtValue() != 0xFF00)
3052       return SDValue();
3053     N10 = N10.getOperand(0);
3054     LookPassAnd1 = true;
3055   }
3056
3057   if (N00 != N10)
3058     return SDValue();
3059
3060   // Make sure everything beyond the low halfword gets set to zero since the SRL
3061   // 16 will clear the top bits.
3062   unsigned OpSizeInBits = VT.getSizeInBits();
3063   if (DemandHighBits && OpSizeInBits > 16) {
3064     // If the left-shift isn't masked out then the only way this is a bswap is
3065     // if all bits beyond the low 8 are 0. In that case the entire pattern
3066     // reduces to a left shift anyway: leave it for other parts of the combiner.
3067     if (!LookPassAnd0)
3068       return SDValue();
3069
3070     // However, if the right shift isn't masked out then it might be because
3071     // it's not needed. See if we can spot that too.
3072     if (!LookPassAnd1 &&
3073         !DAG.MaskedValueIsZero(
3074             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3075       return SDValue();
3076   }
3077
3078   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3079   if (OpSizeInBits > 16)
3080     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3081                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3082   return Res;
3083 }
3084
3085 /// isBSwapHWordElement - Return true if the specified node is an element
3086 /// that makes up a 32-bit packed halfword byteswap. i.e.
3087 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3088 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3089   if (!N.getNode()->hasOneUse())
3090     return false;
3091
3092   unsigned Opc = N.getOpcode();
3093   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3094     return false;
3095
3096   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3097   if (!N1C)
3098     return false;
3099
3100   unsigned Num;
3101   switch (N1C->getZExtValue()) {
3102   default:
3103     return false;
3104   case 0xFF:       Num = 0; break;
3105   case 0xFF00:     Num = 1; break;
3106   case 0xFF0000:   Num = 2; break;
3107   case 0xFF000000: Num = 3; break;
3108   }
3109
3110   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3111   SDValue N0 = N.getOperand(0);
3112   if (Opc == ISD::AND) {
3113     if (Num == 0 || Num == 2) {
3114       // (x >> 8) & 0xff
3115       // (x >> 8) & 0xff0000
3116       if (N0.getOpcode() != ISD::SRL)
3117         return false;
3118       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3119       if (!C || C->getZExtValue() != 8)
3120         return false;
3121     } else {
3122       // (x << 8) & 0xff00
3123       // (x << 8) & 0xff000000
3124       if (N0.getOpcode() != ISD::SHL)
3125         return false;
3126       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3127       if (!C || C->getZExtValue() != 8)
3128         return false;
3129     }
3130   } else if (Opc == ISD::SHL) {
3131     // (x & 0xff) << 8
3132     // (x & 0xff0000) << 8
3133     if (Num != 0 && Num != 2)
3134       return false;
3135     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3136     if (!C || C->getZExtValue() != 8)
3137       return false;
3138   } else { // Opc == ISD::SRL
3139     // (x & 0xff00) >> 8
3140     // (x & 0xff000000) >> 8
3141     if (Num != 1 && Num != 3)
3142       return false;
3143     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3144     if (!C || C->getZExtValue() != 8)
3145       return false;
3146   }
3147
3148   if (Parts[Num])
3149     return false;
3150
3151   Parts[Num] = N0.getOperand(0).getNode();
3152   return true;
3153 }
3154
3155 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3156 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3157 /// => (rotl (bswap x), 16)
3158 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3159   if (!LegalOperations)
3160     return SDValue();
3161
3162   EVT VT = N->getValueType(0);
3163   if (VT != MVT::i32)
3164     return SDValue();
3165   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3166     return SDValue();
3167
3168   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3169   // Look for either
3170   // (or (or (and), (and)), (or (and), (and)))
3171   // (or (or (or (and), (and)), (and)), (and))
3172   if (N0.getOpcode() != ISD::OR)
3173     return SDValue();
3174   SDValue N00 = N0.getOperand(0);
3175   SDValue N01 = N0.getOperand(1);
3176
3177   if (N1.getOpcode() == ISD::OR &&
3178       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3179     // (or (or (and), (and)), (or (and), (and)))
3180     SDValue N000 = N00.getOperand(0);
3181     if (!isBSwapHWordElement(N000, Parts))
3182       return SDValue();
3183
3184     SDValue N001 = N00.getOperand(1);
3185     if (!isBSwapHWordElement(N001, Parts))
3186       return SDValue();
3187     SDValue N010 = N01.getOperand(0);
3188     if (!isBSwapHWordElement(N010, Parts))
3189       return SDValue();
3190     SDValue N011 = N01.getOperand(1);
3191     if (!isBSwapHWordElement(N011, Parts))
3192       return SDValue();
3193   } else {
3194     // (or (or (or (and), (and)), (and)), (and))
3195     if (!isBSwapHWordElement(N1, Parts))
3196       return SDValue();
3197     if (!isBSwapHWordElement(N01, Parts))
3198       return SDValue();
3199     if (N00.getOpcode() != ISD::OR)
3200       return SDValue();
3201     SDValue N000 = N00.getOperand(0);
3202     if (!isBSwapHWordElement(N000, Parts))
3203       return SDValue();
3204     SDValue N001 = N00.getOperand(1);
3205     if (!isBSwapHWordElement(N001, Parts))
3206       return SDValue();
3207   }
3208
3209   // Make sure the parts are all coming from the same node.
3210   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3211     return SDValue();
3212
3213   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3214                               SDValue(Parts[0],0));
3215
3216   // Result of the bswap should be rotated by 16. If it's not legal, then
3217   // do  (x << 16) | (x >> 16).
3218   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3219   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3220     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3221   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3222     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3223   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3224                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3225                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3226 }
3227
3228 SDValue DAGCombiner::visitOR(SDNode *N) {
3229   SDValue N0 = N->getOperand(0);
3230   SDValue N1 = N->getOperand(1);
3231   SDValue LL, LR, RL, RR, CC0, CC1;
3232   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3233   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3234   EVT VT = N1.getValueType();
3235
3236   // fold vector ops
3237   if (VT.isVector()) {
3238     SDValue FoldedVOp = SimplifyVBinOp(N);
3239     if (FoldedVOp.getNode()) return FoldedVOp;
3240
3241     // fold (or x, 0) -> x, vector edition
3242     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3243       return N1;
3244     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3245       return N0;
3246
3247     // fold (or x, -1) -> -1, vector edition
3248     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3249       return N0;
3250     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3251       return N1;
3252
3253     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3254     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3255     // Do this only if the resulting shuffle is legal.
3256     if (isa<ShuffleVectorSDNode>(N0) &&
3257         isa<ShuffleVectorSDNode>(N1) &&
3258         // Avoid folding a node with illegal type.
3259         TLI.isTypeLegal(VT) &&
3260         N0->getOperand(1) == N1->getOperand(1) &&
3261         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3262       bool CanFold = true;
3263       unsigned NumElts = VT.getVectorNumElements();
3264       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3265       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3266       // We construct two shuffle masks:
3267       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3268       // and N1 as the second operand.
3269       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3270       // and N0 as the second operand.
3271       // We do this because OR is commutable and therefore there might be
3272       // two ways to fold this node into a shuffle.
3273       SmallVector<int,4> Mask1;
3274       SmallVector<int,4> Mask2;
3275
3276       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3277         int M0 = SV0->getMaskElt(i);
3278         int M1 = SV1->getMaskElt(i);
3279
3280         // Both shuffle indexes are undef. Propagate Undef.
3281         if (M0 < 0 && M1 < 0) {
3282           Mask1.push_back(M0);
3283           Mask2.push_back(M0);
3284           continue;
3285         }
3286
3287         if (M0 < 0 || M1 < 0 ||
3288             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3289             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3290           CanFold = false;
3291           break;
3292         }
3293
3294         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3295         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3296       }
3297
3298       if (CanFold) {
3299         // Fold this sequence only if the resulting shuffle is 'legal'.
3300         if (TLI.isShuffleMaskLegal(Mask1, VT))
3301           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3302                                       N1->getOperand(0), &Mask1[0]);
3303         if (TLI.isShuffleMaskLegal(Mask2, VT))
3304           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3305                                       N0->getOperand(0), &Mask2[0]);
3306       }
3307     }
3308   }
3309
3310   // fold (or x, undef) -> -1
3311   if (!LegalOperations &&
3312       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3313     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3314     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3315   }
3316   // fold (or c1, c2) -> c1|c2
3317   if (N0C && N1C)
3318     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3319   // canonicalize constant to RHS
3320   if (N0C && !N1C)
3321     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3322   // fold (or x, 0) -> x
3323   if (N1C && N1C->isNullValue())
3324     return N0;
3325   // fold (or x, -1) -> -1
3326   if (N1C && N1C->isAllOnesValue())
3327     return N1;
3328   // fold (or x, c) -> c iff (x & ~c) == 0
3329   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3330     return N1;
3331
3332   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3333   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3334   if (BSwap.getNode())
3335     return BSwap;
3336   BSwap = MatchBSwapHWordLow(N, N0, N1);
3337   if (BSwap.getNode())
3338     return BSwap;
3339
3340   // reassociate or
3341   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3342   if (ROR.getNode())
3343     return ROR;
3344   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3345   // iff (c1 & c2) == 0.
3346   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3347              isa<ConstantSDNode>(N0.getOperand(1))) {
3348     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3349     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3350       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3351       if (!COR.getNode())
3352         return SDValue();
3353       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3354                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3355                                      N0.getOperand(0), N1), COR);
3356     }
3357   }
3358   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3359   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3360     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3361     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3362
3363     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3364         LL.getValueType().isInteger()) {
3365       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3366       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3367       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3368           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3369         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3370                                      LR.getValueType(), LL, RL);
3371         AddToWorkList(ORNode.getNode());
3372         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3373       }
3374       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3375       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3376       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3377           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3378         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3379                                       LR.getValueType(), LL, RL);
3380         AddToWorkList(ANDNode.getNode());
3381         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3382       }
3383     }
3384     // canonicalize equivalent to ll == rl
3385     if (LL == RR && LR == RL) {
3386       Op1 = ISD::getSetCCSwappedOperands(Op1);
3387       std::swap(RL, RR);
3388     }
3389     if (LL == RL && LR == RR) {
3390       bool isInteger = LL.getValueType().isInteger();
3391       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3392       if (Result != ISD::SETCC_INVALID &&
3393           (!LegalOperations ||
3394            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3395             TLI.isOperationLegal(ISD::SETCC,
3396               getSetCCResultType(N0.getValueType())))))
3397         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3398                             LL, LR, Result);
3399     }
3400   }
3401
3402   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3403   if (N0.getOpcode() == N1.getOpcode()) {
3404     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3405     if (Tmp.getNode()) return Tmp;
3406   }
3407
3408   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3409   if (N0.getOpcode() == ISD::AND &&
3410       N1.getOpcode() == ISD::AND &&
3411       N0.getOperand(1).getOpcode() == ISD::Constant &&
3412       N1.getOperand(1).getOpcode() == ISD::Constant &&
3413       // Don't increase # computations.
3414       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3415     // We can only do this xform if we know that bits from X that are set in C2
3416     // but not in C1 are already zero.  Likewise for Y.
3417     const APInt &LHSMask =
3418       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3419     const APInt &RHSMask =
3420       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3421
3422     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3423         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3424       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3425                               N0.getOperand(0), N1.getOperand(0));
3426       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3427                          DAG.getConstant(LHSMask | RHSMask, VT));
3428     }
3429   }
3430
3431   // See if this is some rotate idiom.
3432   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3433     return SDValue(Rot, 0);
3434
3435   // Simplify the operands using demanded-bits information.
3436   if (!VT.isVector() &&
3437       SimplifyDemandedBits(SDValue(N, 0)))
3438     return SDValue(N, 0);
3439
3440   return SDValue();
3441 }
3442
3443 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3444 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3445   if (Op.getOpcode() == ISD::AND) {
3446     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3447       Mask = Op.getOperand(1);
3448       Op = Op.getOperand(0);
3449     } else {
3450       return false;
3451     }
3452   }
3453
3454   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3455     Shift = Op;
3456     return true;
3457   }
3458
3459   return false;
3460 }
3461
3462 // Return true if we can prove that, whenever Neg and Pos are both in the
3463 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3464 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3465 //
3466 //     (or (shift1 X, Neg), (shift2 X, Pos))
3467 //
3468 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3469 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3470 // to consider shift amounts with defined behavior.
3471 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3472   // If OpSize is a power of 2 then:
3473   //
3474   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3475   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3476   //
3477   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3478   // for the stronger condition:
3479   //
3480   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3481   //
3482   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3483   // we can just replace Neg with Neg' for the rest of the function.
3484   //
3485   // In other cases we check for the even stronger condition:
3486   //
3487   //     Neg == OpSize - Pos                                    [B]
3488   //
3489   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3490   // behavior if Pos == 0 (and consequently Neg == OpSize).
3491   //
3492   // We could actually use [A] whenever OpSize is a power of 2, but the
3493   // only extra cases that it would match are those uninteresting ones
3494   // where Neg and Pos are never in range at the same time.  E.g. for
3495   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3496   // as well as (sub 32, Pos), but:
3497   //
3498   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3499   //
3500   // always invokes undefined behavior for 32-bit X.
3501   //
3502   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3503   unsigned MaskLoBits = 0;
3504   if (Neg.getOpcode() == ISD::AND &&
3505       isPowerOf2_64(OpSize) &&
3506       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3507       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3508     Neg = Neg.getOperand(0);
3509     MaskLoBits = Log2_64(OpSize);
3510   }
3511
3512   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3513   if (Neg.getOpcode() != ISD::SUB)
3514     return 0;
3515   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3516   if (!NegC)
3517     return 0;
3518   SDValue NegOp1 = Neg.getOperand(1);
3519
3520   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3521   // Pos'.  The truncation is redundant for the purpose of the equality.
3522   if (MaskLoBits &&
3523       Pos.getOpcode() == ISD::AND &&
3524       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3525       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3526     Pos = Pos.getOperand(0);
3527
3528   // The condition we need is now:
3529   //
3530   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3531   //
3532   // If NegOp1 == Pos then we need:
3533   //
3534   //              OpSize & Mask == NegC & Mask
3535   //
3536   // (because "x & Mask" is a truncation and distributes through subtraction).
3537   APInt Width;
3538   if (Pos == NegOp1)
3539     Width = NegC->getAPIntValue();
3540   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3541   // Then the condition we want to prove becomes:
3542   //
3543   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3544   //
3545   // which, again because "x & Mask" is a truncation, becomes:
3546   //
3547   //                NegC & Mask == (OpSize - PosC) & Mask
3548   //              OpSize & Mask == (NegC + PosC) & Mask
3549   else if (Pos.getOpcode() == ISD::ADD &&
3550            Pos.getOperand(0) == NegOp1 &&
3551            Pos.getOperand(1).getOpcode() == ISD::Constant)
3552     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3553              NegC->getAPIntValue());
3554   else
3555     return false;
3556
3557   // Now we just need to check that OpSize & Mask == Width & Mask.
3558   if (MaskLoBits)
3559     // Opsize & Mask is 0 since Mask is Opsize - 1.
3560     return Width.getLoBits(MaskLoBits) == 0;
3561   return Width == OpSize;
3562 }
3563
3564 // A subroutine of MatchRotate used once we have found an OR of two opposite
3565 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3566 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3567 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3568 // Neg with outer conversions stripped away.
3569 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3570                                        SDValue Neg, SDValue InnerPos,
3571                                        SDValue InnerNeg, unsigned PosOpcode,
3572                                        unsigned NegOpcode, SDLoc DL) {
3573   // fold (or (shl x, (*ext y)),
3574   //          (srl x, (*ext (sub 32, y)))) ->
3575   //   (rotl x, y) or (rotr x, (sub 32, y))
3576   //
3577   // fold (or (shl x, (*ext (sub 32, y))),
3578   //          (srl x, (*ext y))) ->
3579   //   (rotr x, y) or (rotl x, (sub 32, y))
3580   EVT VT = Shifted.getValueType();
3581   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3582     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3583     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3584                        HasPos ? Pos : Neg).getNode();
3585   }
3586
3587   return nullptr;
3588 }
3589
3590 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3591 // idioms for rotate, and if the target supports rotation instructions, generate
3592 // a rot[lr].
3593 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3594   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3595   EVT VT = LHS.getValueType();
3596   if (!TLI.isTypeLegal(VT)) return nullptr;
3597
3598   // The target must have at least one rotate flavor.
3599   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3600   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3601   if (!HasROTL && !HasROTR) return nullptr;
3602
3603   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3604   SDValue LHSShift;   // The shift.
3605   SDValue LHSMask;    // AND value if any.
3606   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3607     return nullptr; // Not part of a rotate.
3608
3609   SDValue RHSShift;   // The shift.
3610   SDValue RHSMask;    // AND value if any.
3611   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3612     return nullptr; // Not part of a rotate.
3613
3614   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3615     return nullptr;   // Not shifting the same value.
3616
3617   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3618     return nullptr;   // Shifts must disagree.
3619
3620   // Canonicalize shl to left side in a shl/srl pair.
3621   if (RHSShift.getOpcode() == ISD::SHL) {
3622     std::swap(LHS, RHS);
3623     std::swap(LHSShift, RHSShift);
3624     std::swap(LHSMask , RHSMask );
3625   }
3626
3627   unsigned OpSizeInBits = VT.getSizeInBits();
3628   SDValue LHSShiftArg = LHSShift.getOperand(0);
3629   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3630   SDValue RHSShiftArg = RHSShift.getOperand(0);
3631   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3632
3633   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3634   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3635   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3636       RHSShiftAmt.getOpcode() == ISD::Constant) {
3637     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3638     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3639     if ((LShVal + RShVal) != OpSizeInBits)
3640       return nullptr;
3641
3642     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3643                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3644
3645     // If there is an AND of either shifted operand, apply it to the result.
3646     if (LHSMask.getNode() || RHSMask.getNode()) {
3647       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3648
3649       if (LHSMask.getNode()) {
3650         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3651         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3652       }
3653       if (RHSMask.getNode()) {
3654         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3655         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3656       }
3657
3658       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3659     }
3660
3661     return Rot.getNode();
3662   }
3663
3664   // If there is a mask here, and we have a variable shift, we can't be sure
3665   // that we're masking out the right stuff.
3666   if (LHSMask.getNode() || RHSMask.getNode())
3667     return nullptr;
3668
3669   // If the shift amount is sign/zext/any-extended just peel it off.
3670   SDValue LExtOp0 = LHSShiftAmt;
3671   SDValue RExtOp0 = RHSShiftAmt;
3672   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3673        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3674        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3675        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3676       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3677        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3678        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3679        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3680     LExtOp0 = LHSShiftAmt.getOperand(0);
3681     RExtOp0 = RHSShiftAmt.getOperand(0);
3682   }
3683
3684   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3685                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3686   if (TryL)
3687     return TryL;
3688
3689   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3690                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3691   if (TryR)
3692     return TryR;
3693
3694   return nullptr;
3695 }
3696
3697 SDValue DAGCombiner::visitXOR(SDNode *N) {
3698   SDValue N0 = N->getOperand(0);
3699   SDValue N1 = N->getOperand(1);
3700   SDValue LHS, RHS, CC;
3701   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3702   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3703   EVT VT = N0.getValueType();
3704
3705   // fold vector ops
3706   if (VT.isVector()) {
3707     SDValue FoldedVOp = SimplifyVBinOp(N);
3708     if (FoldedVOp.getNode()) return FoldedVOp;
3709
3710     // fold (xor x, 0) -> x, vector edition
3711     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3712       return N1;
3713     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3714       return N0;
3715   }
3716
3717   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3718   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3719     return DAG.getConstant(0, VT);
3720   // fold (xor x, undef) -> undef
3721   if (N0.getOpcode() == ISD::UNDEF)
3722     return N0;
3723   if (N1.getOpcode() == ISD::UNDEF)
3724     return N1;
3725   // fold (xor c1, c2) -> c1^c2
3726   if (N0C && N1C)
3727     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3728   // canonicalize constant to RHS
3729   if (N0C && !N1C)
3730     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3731   // fold (xor x, 0) -> x
3732   if (N1C && N1C->isNullValue())
3733     return N0;
3734   // reassociate xor
3735   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3736   if (RXOR.getNode())
3737     return RXOR;
3738
3739   // fold !(x cc y) -> (x !cc y)
3740   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3741     bool isInt = LHS.getValueType().isInteger();
3742     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3743                                                isInt);
3744
3745     if (!LegalOperations ||
3746         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3747       switch (N0.getOpcode()) {
3748       default:
3749         llvm_unreachable("Unhandled SetCC Equivalent!");
3750       case ISD::SETCC:
3751         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3752       case ISD::SELECT_CC:
3753         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3754                                N0.getOperand(3), NotCC);
3755       }
3756     }
3757   }
3758
3759   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3760   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3761       N0.getNode()->hasOneUse() &&
3762       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3763     SDValue V = N0.getOperand(0);
3764     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3765                     DAG.getConstant(1, V.getValueType()));
3766     AddToWorkList(V.getNode());
3767     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3768   }
3769
3770   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3771   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3772       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3773     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3774     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3775       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3776       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3777       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3778       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3779       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3780     }
3781   }
3782   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3783   if (N1C && N1C->isAllOnesValue() &&
3784       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3785     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3786     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3787       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3788       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3789       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3790       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3791       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3792     }
3793   }
3794   // fold (xor (and x, y), y) -> (and (not x), y)
3795   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3796       N0->getOperand(1) == N1) {
3797     SDValue X = N0->getOperand(0);
3798     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3799     AddToWorkList(NotX.getNode());
3800     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3801   }
3802   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3803   if (N1C && N0.getOpcode() == ISD::XOR) {
3804     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3805     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3806     if (N00C)
3807       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3808                          DAG.getConstant(N1C->getAPIntValue() ^
3809                                          N00C->getAPIntValue(), VT));
3810     if (N01C)
3811       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3812                          DAG.getConstant(N1C->getAPIntValue() ^
3813                                          N01C->getAPIntValue(), VT));
3814   }
3815   // fold (xor x, x) -> 0
3816   if (N0 == N1)
3817     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3818
3819   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3820   if (N0.getOpcode() == N1.getOpcode()) {
3821     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3822     if (Tmp.getNode()) return Tmp;
3823   }
3824
3825   // Simplify the expression using non-local knowledge.
3826   if (!VT.isVector() &&
3827       SimplifyDemandedBits(SDValue(N, 0)))
3828     return SDValue(N, 0);
3829
3830   return SDValue();
3831 }
3832
3833 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3834 /// the shift amount is a constant.
3835 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3836   // We can't and shouldn't fold opaque constants.
3837   if (Amt->isOpaque())
3838     return SDValue();
3839
3840   SDNode *LHS = N->getOperand(0).getNode();
3841   if (!LHS->hasOneUse()) return SDValue();
3842
3843   // We want to pull some binops through shifts, so that we have (and (shift))
3844   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3845   // thing happens with address calculations, so it's important to canonicalize
3846   // it.
3847   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3848
3849   switch (LHS->getOpcode()) {
3850   default: return SDValue();
3851   case ISD::OR:
3852   case ISD::XOR:
3853     HighBitSet = false; // We can only transform sra if the high bit is clear.
3854     break;
3855   case ISD::AND:
3856     HighBitSet = true;  // We can only transform sra if the high bit is set.
3857     break;
3858   case ISD::ADD:
3859     if (N->getOpcode() != ISD::SHL)
3860       return SDValue(); // only shl(add) not sr[al](add).
3861     HighBitSet = false; // We can only transform sra if the high bit is clear.
3862     break;
3863   }
3864
3865   // We require the RHS of the binop to be a constant and not opaque as well.
3866   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3867   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3868
3869   // FIXME: disable this unless the input to the binop is a shift by a constant.
3870   // If it is not a shift, it pessimizes some common cases like:
3871   //
3872   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3873   //    int bar(int *X, int i) { return X[i & 255]; }
3874   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3875   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3876        BinOpLHSVal->getOpcode() != ISD::SRA &&
3877        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3878       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3879     return SDValue();
3880
3881   EVT VT = N->getValueType(0);
3882
3883   // If this is a signed shift right, and the high bit is modified by the
3884   // logical operation, do not perform the transformation. The highBitSet
3885   // boolean indicates the value of the high bit of the constant which would
3886   // cause it to be modified for this operation.
3887   if (N->getOpcode() == ISD::SRA) {
3888     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3889     if (BinOpRHSSignSet != HighBitSet)
3890       return SDValue();
3891   }
3892
3893   if (!TLI.isDesirableToCommuteWithShift(LHS))
3894     return SDValue();
3895
3896   // Fold the constants, shifting the binop RHS by the shift amount.
3897   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3898                                N->getValueType(0),
3899                                LHS->getOperand(1), N->getOperand(1));
3900   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3901
3902   // Create the new shift.
3903   SDValue NewShift = DAG.getNode(N->getOpcode(),
3904                                  SDLoc(LHS->getOperand(0)),
3905                                  VT, LHS->getOperand(0), N->getOperand(1));
3906
3907   // Create the new binop.
3908   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3909 }
3910
3911 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3912   assert(N->getOpcode() == ISD::TRUNCATE);
3913   assert(N->getOperand(0).getOpcode() == ISD::AND);
3914
3915   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3916   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3917     SDValue N01 = N->getOperand(0).getOperand(1);
3918
3919     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3920       EVT TruncVT = N->getValueType(0);
3921       SDValue N00 = N->getOperand(0).getOperand(0);
3922       APInt TruncC = N01C->getAPIntValue();
3923       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3924
3925       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3926                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3927                          DAG.getConstant(TruncC, TruncVT));
3928     }
3929   }
3930
3931   return SDValue();
3932 }
3933
3934 SDValue DAGCombiner::visitRotate(SDNode *N) {
3935   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3936   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3937       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3938     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3939     if (NewOp1.getNode())
3940       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3941                          N->getOperand(0), NewOp1);
3942   }
3943   return SDValue();
3944 }
3945
3946 SDValue DAGCombiner::visitSHL(SDNode *N) {
3947   SDValue N0 = N->getOperand(0);
3948   SDValue N1 = N->getOperand(1);
3949   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3950   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3951   EVT VT = N0.getValueType();
3952   unsigned OpSizeInBits = VT.getScalarSizeInBits();
3953
3954   // fold vector ops
3955   if (VT.isVector()) {
3956     SDValue FoldedVOp = SimplifyVBinOp(N);
3957     if (FoldedVOp.getNode()) return FoldedVOp;
3958
3959     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3960     // If setcc produces all-one true value then:
3961     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3962     if (N1CV && N1CV->isConstant()) {
3963       if (N0.getOpcode() == ISD::AND) {
3964         SDValue N00 = N0->getOperand(0);
3965         SDValue N01 = N0->getOperand(1);
3966         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3967
3968         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
3969             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
3970                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3971           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3972           if (C.getNode())
3973             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3974         }
3975       } else {
3976         N1C = isConstOrConstSplat(N1);
3977       }
3978     }
3979   }
3980
3981   // fold (shl c1, c2) -> c1<<c2
3982   if (N0C && N1C)
3983     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3984   // fold (shl 0, x) -> 0
3985   if (N0C && N0C->isNullValue())
3986     return N0;
3987   // fold (shl x, c >= size(x)) -> undef
3988   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3989     return DAG.getUNDEF(VT);
3990   // fold (shl x, 0) -> x
3991   if (N1C && N1C->isNullValue())
3992     return N0;
3993   // fold (shl undef, x) -> 0
3994   if (N0.getOpcode() == ISD::UNDEF)
3995     return DAG.getConstant(0, VT);
3996   // if (shl x, c) is known to be zero, return 0
3997   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3998                             APInt::getAllOnesValue(OpSizeInBits)))
3999     return DAG.getConstant(0, VT);
4000   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4001   if (N1.getOpcode() == ISD::TRUNCATE &&
4002       N1.getOperand(0).getOpcode() == ISD::AND) {
4003     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4004     if (NewOp1.getNode())
4005       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4006   }
4007
4008   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4009     return SDValue(N, 0);
4010
4011   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4012   if (N1C && N0.getOpcode() == ISD::SHL) {
4013     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4014       uint64_t c1 = N0C1->getZExtValue();
4015       uint64_t c2 = N1C->getZExtValue();
4016       if (c1 + c2 >= OpSizeInBits)
4017         return DAG.getConstant(0, VT);
4018       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4019                          DAG.getConstant(c1 + c2, N1.getValueType()));
4020     }
4021   }
4022
4023   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4024   // For this to be valid, the second form must not preserve any of the bits
4025   // that are shifted out by the inner shift in the first form.  This means
4026   // the outer shift size must be >= the number of bits added by the ext.
4027   // As a corollary, we don't care what kind of ext it is.
4028   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4029               N0.getOpcode() == ISD::ANY_EXTEND ||
4030               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4031       N0.getOperand(0).getOpcode() == ISD::SHL) {
4032     SDValue N0Op0 = N0.getOperand(0);
4033     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4034       uint64_t c1 = N0Op0C1->getZExtValue();
4035       uint64_t c2 = N1C->getZExtValue();
4036       EVT InnerShiftVT = N0Op0.getValueType();
4037       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4038       if (c2 >= OpSizeInBits - InnerShiftSize) {
4039         if (c1 + c2 >= OpSizeInBits)
4040           return DAG.getConstant(0, VT);
4041         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4042                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4043                                        N0Op0->getOperand(0)),
4044                            DAG.getConstant(c1 + c2, N1.getValueType()));
4045       }
4046     }
4047   }
4048
4049   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4050   // Only fold this if the inner zext has no other uses to avoid increasing
4051   // the total number of instructions.
4052   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4053       N0.getOperand(0).getOpcode() == ISD::SRL) {
4054     SDValue N0Op0 = N0.getOperand(0);
4055     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4056       uint64_t c1 = N0Op0C1->getZExtValue();
4057       if (c1 < VT.getScalarSizeInBits()) {
4058         uint64_t c2 = N1C->getZExtValue();
4059         if (c1 == c2) {
4060           SDValue NewOp0 = N0.getOperand(0);
4061           EVT CountVT = NewOp0.getOperand(1).getValueType();
4062           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4063                                        NewOp0, DAG.getConstant(c2, CountVT));
4064           AddToWorkList(NewSHL.getNode());
4065           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4066         }
4067       }
4068     }
4069   }
4070
4071   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4072   //                               (and (srl x, (sub c1, c2), MASK)
4073   // Only fold this if the inner shift has no other uses -- if it does, folding
4074   // this will increase the total number of instructions.
4075   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4076     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4077       uint64_t c1 = N0C1->getZExtValue();
4078       if (c1 < OpSizeInBits) {
4079         uint64_t c2 = N1C->getZExtValue();
4080         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4081         SDValue Shift;
4082         if (c2 > c1) {
4083           Mask = Mask.shl(c2 - c1);
4084           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4085                               DAG.getConstant(c2 - c1, N1.getValueType()));
4086         } else {
4087           Mask = Mask.lshr(c1 - c2);
4088           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4089                               DAG.getConstant(c1 - c2, N1.getValueType()));
4090         }
4091         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4092                            DAG.getConstant(Mask, VT));
4093       }
4094     }
4095   }
4096   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4097   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4098     unsigned BitSize = VT.getScalarSizeInBits();
4099     SDValue HiBitsMask =
4100       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4101                                             BitSize - N1C->getZExtValue()), VT);
4102     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4103                        HiBitsMask);
4104   }
4105
4106   if (N1C) {
4107     SDValue NewSHL = visitShiftByConstant(N, N1C);
4108     if (NewSHL.getNode())
4109       return NewSHL;
4110   }
4111
4112   return SDValue();
4113 }
4114
4115 SDValue DAGCombiner::visitSRA(SDNode *N) {
4116   SDValue N0 = N->getOperand(0);
4117   SDValue N1 = N->getOperand(1);
4118   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4119   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4120   EVT VT = N0.getValueType();
4121   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4122
4123   // fold vector ops
4124   if (VT.isVector()) {
4125     SDValue FoldedVOp = SimplifyVBinOp(N);
4126     if (FoldedVOp.getNode()) return FoldedVOp;
4127
4128     N1C = isConstOrConstSplat(N1);
4129   }
4130
4131   // fold (sra c1, c2) -> (sra c1, c2)
4132   if (N0C && N1C)
4133     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4134   // fold (sra 0, x) -> 0
4135   if (N0C && N0C->isNullValue())
4136     return N0;
4137   // fold (sra -1, x) -> -1
4138   if (N0C && N0C->isAllOnesValue())
4139     return N0;
4140   // fold (sra x, (setge c, size(x))) -> undef
4141   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4142     return DAG.getUNDEF(VT);
4143   // fold (sra x, 0) -> x
4144   if (N1C && N1C->isNullValue())
4145     return N0;
4146   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4147   // sext_inreg.
4148   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4149     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4150     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4151     if (VT.isVector())
4152       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4153                                ExtVT, VT.getVectorNumElements());
4154     if ((!LegalOperations ||
4155          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4156       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4157                          N0.getOperand(0), DAG.getValueType(ExtVT));
4158   }
4159
4160   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4161   if (N1C && N0.getOpcode() == ISD::SRA) {
4162     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4163       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4164       if (Sum >= OpSizeInBits)
4165         Sum = OpSizeInBits - 1;
4166       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4167                          DAG.getConstant(Sum, N1.getValueType()));
4168     }
4169   }
4170
4171   // fold (sra (shl X, m), (sub result_size, n))
4172   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4173   // result_size - n != m.
4174   // If truncate is free for the target sext(shl) is likely to result in better
4175   // code.
4176   if (N0.getOpcode() == ISD::SHL && N1C) {
4177     // Get the two constanst of the shifts, CN0 = m, CN = n.
4178     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4179     if (N01C) {
4180       LLVMContext &Ctx = *DAG.getContext();
4181       // Determine what the truncate's result bitsize and type would be.
4182       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4183
4184       if (VT.isVector())
4185         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4186
4187       // Determine the residual right-shift amount.
4188       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4189
4190       // If the shift is not a no-op (in which case this should be just a sign
4191       // extend already), the truncated to type is legal, sign_extend is legal
4192       // on that type, and the truncate to that type is both legal and free,
4193       // perform the transform.
4194       if ((ShiftAmt > 0) &&
4195           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4196           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4197           TLI.isTruncateFree(VT, TruncVT)) {
4198
4199           SDValue Amt = DAG.getConstant(ShiftAmt,
4200               getShiftAmountTy(N0.getOperand(0).getValueType()));
4201           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4202                                       N0.getOperand(0), Amt);
4203           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4204                                       Shift);
4205           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4206                              N->getValueType(0), Trunc);
4207       }
4208     }
4209   }
4210
4211   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4212   if (N1.getOpcode() == ISD::TRUNCATE &&
4213       N1.getOperand(0).getOpcode() == ISD::AND) {
4214     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4215     if (NewOp1.getNode())
4216       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4217   }
4218
4219   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4220   //      if c1 is equal to the number of bits the trunc removes
4221   if (N0.getOpcode() == ISD::TRUNCATE &&
4222       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4223        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4224       N0.getOperand(0).hasOneUse() &&
4225       N0.getOperand(0).getOperand(1).hasOneUse() &&
4226       N1C) {
4227     SDValue N0Op0 = N0.getOperand(0);
4228     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4229       unsigned LargeShiftVal = LargeShift->getZExtValue();
4230       EVT LargeVT = N0Op0.getValueType();
4231
4232       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4233         SDValue Amt =
4234           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4235                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4236         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4237                                   N0Op0.getOperand(0), Amt);
4238         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4239       }
4240     }
4241   }
4242
4243   // Simplify, based on bits shifted out of the LHS.
4244   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4245     return SDValue(N, 0);
4246
4247
4248   // If the sign bit is known to be zero, switch this to a SRL.
4249   if (DAG.SignBitIsZero(N0))
4250     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4251
4252   if (N1C) {
4253     SDValue NewSRA = visitShiftByConstant(N, N1C);
4254     if (NewSRA.getNode())
4255       return NewSRA;
4256   }
4257
4258   return SDValue();
4259 }
4260
4261 SDValue DAGCombiner::visitSRL(SDNode *N) {
4262   SDValue N0 = N->getOperand(0);
4263   SDValue N1 = N->getOperand(1);
4264   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4265   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4266   EVT VT = N0.getValueType();
4267   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4268
4269   // fold vector ops
4270   if (VT.isVector()) {
4271     SDValue FoldedVOp = SimplifyVBinOp(N);
4272     if (FoldedVOp.getNode()) return FoldedVOp;
4273
4274     N1C = isConstOrConstSplat(N1);
4275   }
4276
4277   // fold (srl c1, c2) -> c1 >>u c2
4278   if (N0C && N1C)
4279     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4280   // fold (srl 0, x) -> 0
4281   if (N0C && N0C->isNullValue())
4282     return N0;
4283   // fold (srl x, c >= size(x)) -> undef
4284   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4285     return DAG.getUNDEF(VT);
4286   // fold (srl x, 0) -> x
4287   if (N1C && N1C->isNullValue())
4288     return N0;
4289   // if (srl x, c) is known to be zero, return 0
4290   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4291                                    APInt::getAllOnesValue(OpSizeInBits)))
4292     return DAG.getConstant(0, VT);
4293
4294   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4295   if (N1C && N0.getOpcode() == ISD::SRL) {
4296     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4297       uint64_t c1 = N01C->getZExtValue();
4298       uint64_t c2 = N1C->getZExtValue();
4299       if (c1 + c2 >= OpSizeInBits)
4300         return DAG.getConstant(0, VT);
4301       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4302                          DAG.getConstant(c1 + c2, N1.getValueType()));
4303     }
4304   }
4305
4306   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4307   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4308       N0.getOperand(0).getOpcode() == ISD::SRL &&
4309       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4310     uint64_t c1 =
4311       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4312     uint64_t c2 = N1C->getZExtValue();
4313     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4314     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4315     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4316     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4317     if (c1 + OpSizeInBits == InnerShiftSize) {
4318       if (c1 + c2 >= InnerShiftSize)
4319         return DAG.getConstant(0, VT);
4320       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4321                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4322                                      N0.getOperand(0)->getOperand(0),
4323                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4324     }
4325   }
4326
4327   // fold (srl (shl x, c), c) -> (and x, cst2)
4328   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4329     unsigned BitSize = N0.getScalarValueSizeInBits();
4330     if (BitSize <= 64) {
4331       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4332       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4333                          DAG.getConstant(~0ULL >> ShAmt, VT));
4334     }
4335   }
4336
4337   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4338   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4339     // Shifting in all undef bits?
4340     EVT SmallVT = N0.getOperand(0).getValueType();
4341     unsigned BitSize = SmallVT.getScalarSizeInBits();
4342     if (N1C->getZExtValue() >= BitSize)
4343       return DAG.getUNDEF(VT);
4344
4345     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4346       uint64_t ShiftAmt = N1C->getZExtValue();
4347       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4348                                        N0.getOperand(0),
4349                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4350       AddToWorkList(SmallShift.getNode());
4351       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4352       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4353                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4354                          DAG.getConstant(Mask, VT));
4355     }
4356   }
4357
4358   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4359   // bit, which is unmodified by sra.
4360   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4361     if (N0.getOpcode() == ISD::SRA)
4362       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4363   }
4364
4365   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4366   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4367       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4368     APInt KnownZero, KnownOne;
4369     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4370
4371     // If any of the input bits are KnownOne, then the input couldn't be all
4372     // zeros, thus the result of the srl will always be zero.
4373     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4374
4375     // If all of the bits input the to ctlz node are known to be zero, then
4376     // the result of the ctlz is "32" and the result of the shift is one.
4377     APInt UnknownBits = ~KnownZero;
4378     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4379
4380     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4381     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4382       // Okay, we know that only that the single bit specified by UnknownBits
4383       // could be set on input to the CTLZ node. If this bit is set, the SRL
4384       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4385       // to an SRL/XOR pair, which is likely to simplify more.
4386       unsigned ShAmt = UnknownBits.countTrailingZeros();
4387       SDValue Op = N0.getOperand(0);
4388
4389       if (ShAmt) {
4390         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4391                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4392         AddToWorkList(Op.getNode());
4393       }
4394
4395       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4396                          Op, DAG.getConstant(1, VT));
4397     }
4398   }
4399
4400   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4401   if (N1.getOpcode() == ISD::TRUNCATE &&
4402       N1.getOperand(0).getOpcode() == ISD::AND) {
4403     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4404     if (NewOp1.getNode())
4405       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4406   }
4407
4408   // fold operands of srl based on knowledge that the low bits are not
4409   // demanded.
4410   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4411     return SDValue(N, 0);
4412
4413   if (N1C) {
4414     SDValue NewSRL = visitShiftByConstant(N, N1C);
4415     if (NewSRL.getNode())
4416       return NewSRL;
4417   }
4418
4419   // Attempt to convert a srl of a load into a narrower zero-extending load.
4420   SDValue NarrowLoad = ReduceLoadWidth(N);
4421   if (NarrowLoad.getNode())
4422     return NarrowLoad;
4423
4424   // Here is a common situation. We want to optimize:
4425   //
4426   //   %a = ...
4427   //   %b = and i32 %a, 2
4428   //   %c = srl i32 %b, 1
4429   //   brcond i32 %c ...
4430   //
4431   // into
4432   //
4433   //   %a = ...
4434   //   %b = and %a, 2
4435   //   %c = setcc eq %b, 0
4436   //   brcond %c ...
4437   //
4438   // However when after the source operand of SRL is optimized into AND, the SRL
4439   // itself may not be optimized further. Look for it and add the BRCOND into
4440   // the worklist.
4441   if (N->hasOneUse()) {
4442     SDNode *Use = *N->use_begin();
4443     if (Use->getOpcode() == ISD::BRCOND)
4444       AddToWorkList(Use);
4445     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4446       // Also look pass the truncate.
4447       Use = *Use->use_begin();
4448       if (Use->getOpcode() == ISD::BRCOND)
4449         AddToWorkList(Use);
4450     }
4451   }
4452
4453   return SDValue();
4454 }
4455
4456 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4457   SDValue N0 = N->getOperand(0);
4458   EVT VT = N->getValueType(0);
4459
4460   // fold (ctlz c1) -> c2
4461   if (isa<ConstantSDNode>(N0))
4462     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4463   return SDValue();
4464 }
4465
4466 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4467   SDValue N0 = N->getOperand(0);
4468   EVT VT = N->getValueType(0);
4469
4470   // fold (ctlz_zero_undef c1) -> c2
4471   if (isa<ConstantSDNode>(N0))
4472     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4473   return SDValue();
4474 }
4475
4476 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4477   SDValue N0 = N->getOperand(0);
4478   EVT VT = N->getValueType(0);
4479
4480   // fold (cttz c1) -> c2
4481   if (isa<ConstantSDNode>(N0))
4482     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4483   return SDValue();
4484 }
4485
4486 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4487   SDValue N0 = N->getOperand(0);
4488   EVT VT = N->getValueType(0);
4489
4490   // fold (cttz_zero_undef c1) -> c2
4491   if (isa<ConstantSDNode>(N0))
4492     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4493   return SDValue();
4494 }
4495
4496 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4497   SDValue N0 = N->getOperand(0);
4498   EVT VT = N->getValueType(0);
4499
4500   // fold (ctpop c1) -> c2
4501   if (isa<ConstantSDNode>(N0))
4502     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4503   return SDValue();
4504 }
4505
4506 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4507   SDValue N0 = N->getOperand(0);
4508   SDValue N1 = N->getOperand(1);
4509   SDValue N2 = N->getOperand(2);
4510   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4511   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4512   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4513   EVT VT = N->getValueType(0);
4514   EVT VT0 = N0.getValueType();
4515
4516   // fold (select C, X, X) -> X
4517   if (N1 == N2)
4518     return N1;
4519   // fold (select true, X, Y) -> X
4520   if (N0C && !N0C->isNullValue())
4521     return N1;
4522   // fold (select false, X, Y) -> Y
4523   if (N0C && N0C->isNullValue())
4524     return N2;
4525   // fold (select C, 1, X) -> (or C, X)
4526   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4527     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4528   // fold (select C, 0, 1) -> (xor C, 1)
4529   // We can't do this reliably if integer based booleans have different contents
4530   // to floating point based booleans. This is because we can't tell whether we
4531   // have an integer-based boolean or a floating-point-based boolean unless we
4532   // can find the SETCC that produced it and inspect its operands. This is
4533   // fairly easy if C is the SETCC node, but it can potentially be
4534   // undiscoverable (or not reasonably discoverable). For example, it could be
4535   // in another basic block or it could require searching a complicated
4536   // expression.
4537   if (VT.isInteger() &&
4538       (VT0 == MVT::i1 || (VT0.isInteger() &&
4539                           TLI.getBooleanContents(false, false) ==
4540                               TLI.getBooleanContents(false, true) &&
4541                           TLI.getBooleanContents(false, false) ==
4542                               TargetLowering::ZeroOrOneBooleanContent)) &&
4543       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4544     SDValue XORNode;
4545     if (VT == VT0)
4546       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4547                          N0, DAG.getConstant(1, VT0));
4548     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4549                           N0, DAG.getConstant(1, VT0));
4550     AddToWorkList(XORNode.getNode());
4551     if (VT.bitsGT(VT0))
4552       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4553     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4554   }
4555   // fold (select C, 0, X) -> (and (not C), X)
4556   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4557     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4558     AddToWorkList(NOTNode.getNode());
4559     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4560   }
4561   // fold (select C, X, 1) -> (or (not C), X)
4562   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4563     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4564     AddToWorkList(NOTNode.getNode());
4565     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4566   }
4567   // fold (select C, X, 0) -> (and C, X)
4568   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4569     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4570   // fold (select X, X, Y) -> (or X, Y)
4571   // fold (select X, 1, Y) -> (or X, Y)
4572   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4573     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4574   // fold (select X, Y, X) -> (and X, Y)
4575   // fold (select X, Y, 0) -> (and X, Y)
4576   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4577     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4578
4579   // If we can fold this based on the true/false value, do so.
4580   if (SimplifySelectOps(N, N1, N2))
4581     return SDValue(N, 0);  // Don't revisit N.
4582
4583   // fold selects based on a setcc into other things, such as min/max/abs
4584   if (N0.getOpcode() == ISD::SETCC) {
4585     if ((!LegalOperations &&
4586          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4587         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4588       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4589                          N0.getOperand(0), N0.getOperand(1),
4590                          N1, N2, N0.getOperand(2));
4591     return SimplifySelect(SDLoc(N), N0, N1, N2);
4592   }
4593
4594   return SDValue();
4595 }
4596
4597 static
4598 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4599   SDLoc DL(N);
4600   EVT LoVT, HiVT;
4601   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4602
4603   // Split the inputs.
4604   SDValue Lo, Hi, LL, LH, RL, RH;
4605   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4606   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4607
4608   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4609   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4610
4611   return std::make_pair(Lo, Hi);
4612 }
4613
4614 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4615 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4616 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4617   SDLoc dl(N);
4618   SDValue Cond = N->getOperand(0);
4619   SDValue LHS = N->getOperand(1);
4620   SDValue RHS = N->getOperand(2);
4621   MVT VT = N->getSimpleValueType(0);
4622   int NumElems = VT.getVectorNumElements();
4623   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4624          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4625          Cond.getOpcode() == ISD::BUILD_VECTOR);
4626
4627   // We're sure we have an even number of elements due to the
4628   // concat_vectors we have as arguments to vselect.
4629   // Skip BV elements until we find one that's not an UNDEF
4630   // After we find an UNDEF element, keep looping until we get to half the
4631   // length of the BV and see if all the non-undef nodes are the same.
4632   ConstantSDNode *BottomHalf = nullptr;
4633   for (int i = 0; i < NumElems / 2; ++i) {
4634     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4635       continue;
4636
4637     if (BottomHalf == nullptr)
4638       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4639     else if (Cond->getOperand(i).getNode() != BottomHalf)
4640       return SDValue();
4641   }
4642
4643   // Do the same for the second half of the BuildVector
4644   ConstantSDNode *TopHalf = nullptr;
4645   for (int i = NumElems / 2; i < NumElems; ++i) {
4646     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4647       continue;
4648
4649     if (TopHalf == nullptr)
4650       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4651     else if (Cond->getOperand(i).getNode() != TopHalf)
4652       return SDValue();
4653   }
4654
4655   assert(TopHalf && BottomHalf &&
4656          "One half of the selector was all UNDEFs and the other was all the "
4657          "same value. This should have been addressed before this function.");
4658   return DAG.getNode(
4659       ISD::CONCAT_VECTORS, dl, VT,
4660       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4661       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4662 }
4663
4664 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4665   SDValue N0 = N->getOperand(0);
4666   SDValue N1 = N->getOperand(1);
4667   SDValue N2 = N->getOperand(2);
4668   SDLoc DL(N);
4669
4670   // Canonicalize integer abs.
4671   // vselect (setg[te] X,  0),  X, -X ->
4672   // vselect (setgt    X, -1),  X, -X ->
4673   // vselect (setl[te] X,  0), -X,  X ->
4674   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4675   if (N0.getOpcode() == ISD::SETCC) {
4676     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4677     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4678     bool isAbs = false;
4679     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4680
4681     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4682          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4683         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4684       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4685     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4686              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4687       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4688
4689     if (isAbs) {
4690       EVT VT = LHS.getValueType();
4691       SDValue Shift = DAG.getNode(
4692           ISD::SRA, DL, VT, LHS,
4693           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4694       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4695       AddToWorkList(Shift.getNode());
4696       AddToWorkList(Add.getNode());
4697       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4698     }
4699   }
4700
4701   // If the VSELECT result requires splitting and the mask is provided by a
4702   // SETCC, then split both nodes and its operands before legalization. This
4703   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4704   // and enables future optimizations (e.g. min/max pattern matching on X86).
4705   if (N0.getOpcode() == ISD::SETCC) {
4706     EVT VT = N->getValueType(0);
4707
4708     // Check if any splitting is required.
4709     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4710         TargetLowering::TypeSplitVector)
4711       return SDValue();
4712
4713     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4714     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4715     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4716     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4717
4718     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4719     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4720
4721     // Add the new VSELECT nodes to the work list in case they need to be split
4722     // again.
4723     AddToWorkList(Lo.getNode());
4724     AddToWorkList(Hi.getNode());
4725
4726     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4727   }
4728
4729   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4730   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4731     return N1;
4732   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4733   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4734     return N2;
4735
4736   // The ConvertSelectToConcatVector function is assuming both the above
4737   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4738   // and addressed.
4739   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4740       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4741       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4742     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4743     if (CV.getNode())
4744       return CV;
4745   }
4746
4747   return SDValue();
4748 }
4749
4750 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4751   SDValue N0 = N->getOperand(0);
4752   SDValue N1 = N->getOperand(1);
4753   SDValue N2 = N->getOperand(2);
4754   SDValue N3 = N->getOperand(3);
4755   SDValue N4 = N->getOperand(4);
4756   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4757
4758   // fold select_cc lhs, rhs, x, x, cc -> x
4759   if (N2 == N3)
4760     return N2;
4761
4762   // Determine if the condition we're dealing with is constant
4763   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4764                               N0, N1, CC, SDLoc(N), false);
4765   if (SCC.getNode()) {
4766     AddToWorkList(SCC.getNode());
4767
4768     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4769       if (!SCCC->isNullValue())
4770         return N2;    // cond always true -> true val
4771       else
4772         return N3;    // cond always false -> false val
4773     }
4774
4775     // Fold to a simpler select_cc
4776     if (SCC.getOpcode() == ISD::SETCC)
4777       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4778                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4779                          SCC.getOperand(2));
4780   }
4781
4782   // If we can fold this based on the true/false value, do so.
4783   if (SimplifySelectOps(N, N2, N3))
4784     return SDValue(N, 0);  // Don't revisit N.
4785
4786   // fold select_cc into other things, such as min/max/abs
4787   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4788 }
4789
4790 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4791   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4792                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4793                        SDLoc(N));
4794 }
4795
4796 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4797 // dag node into a ConstantSDNode or a build_vector of constants.
4798 // This function is called by the DAGCombiner when visiting sext/zext/aext
4799 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4800 // Vector extends are not folded if operations are legal; this is to
4801 // avoid introducing illegal build_vector dag nodes.
4802 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4803                                          SelectionDAG &DAG, bool LegalTypes,
4804                                          bool LegalOperations) {
4805   unsigned Opcode = N->getOpcode();
4806   SDValue N0 = N->getOperand(0);
4807   EVT VT = N->getValueType(0);
4808
4809   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4810          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4811
4812   // fold (sext c1) -> c1
4813   // fold (zext c1) -> c1
4814   // fold (aext c1) -> c1
4815   if (isa<ConstantSDNode>(N0))
4816     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4817
4818   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4819   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4820   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4821   EVT SVT = VT.getScalarType();
4822   if (!(VT.isVector() &&
4823       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4824       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4825     return nullptr;
4826
4827   // We can fold this node into a build_vector.
4828   unsigned VTBits = SVT.getSizeInBits();
4829   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4830   unsigned ShAmt = VTBits - EVTBits;
4831   SmallVector<SDValue, 8> Elts;
4832   unsigned NumElts = N0->getNumOperands();
4833   SDLoc DL(N);
4834
4835   for (unsigned i=0; i != NumElts; ++i) {
4836     SDValue Op = N0->getOperand(i);
4837     if (Op->getOpcode() == ISD::UNDEF) {
4838       Elts.push_back(DAG.getUNDEF(SVT));
4839       continue;
4840     }
4841
4842     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4843     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4844     if (Opcode == ISD::SIGN_EXTEND)
4845       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4846                                      SVT));
4847     else
4848       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4849                                      SVT));
4850   }
4851
4852   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4853 }
4854
4855 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4856 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4857 // transformation. Returns true if extension are possible and the above
4858 // mentioned transformation is profitable.
4859 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4860                                     unsigned ExtOpc,
4861                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4862                                     const TargetLowering &TLI) {
4863   bool HasCopyToRegUses = false;
4864   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4865   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4866                             UE = N0.getNode()->use_end();
4867        UI != UE; ++UI) {
4868     SDNode *User = *UI;
4869     if (User == N)
4870       continue;
4871     if (UI.getUse().getResNo() != N0.getResNo())
4872       continue;
4873     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4874     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4875       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4876       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4877         // Sign bits will be lost after a zext.
4878         return false;
4879       bool Add = false;
4880       for (unsigned i = 0; i != 2; ++i) {
4881         SDValue UseOp = User->getOperand(i);
4882         if (UseOp == N0)
4883           continue;
4884         if (!isa<ConstantSDNode>(UseOp))
4885           return false;
4886         Add = true;
4887       }
4888       if (Add)
4889         ExtendNodes.push_back(User);
4890       continue;
4891     }
4892     // If truncates aren't free and there are users we can't
4893     // extend, it isn't worthwhile.
4894     if (!isTruncFree)
4895       return false;
4896     // Remember if this value is live-out.
4897     if (User->getOpcode() == ISD::CopyToReg)
4898       HasCopyToRegUses = true;
4899   }
4900
4901   if (HasCopyToRegUses) {
4902     bool BothLiveOut = false;
4903     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4904          UI != UE; ++UI) {
4905       SDUse &Use = UI.getUse();
4906       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4907         BothLiveOut = true;
4908         break;
4909       }
4910     }
4911     if (BothLiveOut)
4912       // Both unextended and extended values are live out. There had better be
4913       // a good reason for the transformation.
4914       return ExtendNodes.size();
4915   }
4916   return true;
4917 }
4918
4919 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4920                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4921                                   ISD::NodeType ExtType) {
4922   // Extend SetCC uses if necessary.
4923   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4924     SDNode *SetCC = SetCCs[i];
4925     SmallVector<SDValue, 4> Ops;
4926
4927     for (unsigned j = 0; j != 2; ++j) {
4928       SDValue SOp = SetCC->getOperand(j);
4929       if (SOp == Trunc)
4930         Ops.push_back(ExtLoad);
4931       else
4932         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4933     }
4934
4935     Ops.push_back(SetCC->getOperand(2));
4936     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4937   }
4938 }
4939
4940 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4941   SDValue N0 = N->getOperand(0);
4942   EVT VT = N->getValueType(0);
4943
4944   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4945                                               LegalOperations))
4946     return SDValue(Res, 0);
4947
4948   // fold (sext (sext x)) -> (sext x)
4949   // fold (sext (aext x)) -> (sext x)
4950   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4951     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4952                        N0.getOperand(0));
4953
4954   if (N0.getOpcode() == ISD::TRUNCATE) {
4955     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4956     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4957     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4958     if (NarrowLoad.getNode()) {
4959       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4960       if (NarrowLoad.getNode() != N0.getNode()) {
4961         CombineTo(N0.getNode(), NarrowLoad);
4962         // CombineTo deleted the truncate, if needed, but not what's under it.
4963         AddToWorkList(oye);
4964       }
4965       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4966     }
4967
4968     // See if the value being truncated is already sign extended.  If so, just
4969     // eliminate the trunc/sext pair.
4970     SDValue Op = N0.getOperand(0);
4971     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4972     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4973     unsigned DestBits = VT.getScalarType().getSizeInBits();
4974     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4975
4976     if (OpBits == DestBits) {
4977       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4978       // bits, it is already ready.
4979       if (NumSignBits > DestBits-MidBits)
4980         return Op;
4981     } else if (OpBits < DestBits) {
4982       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4983       // bits, just sext from i32.
4984       if (NumSignBits > OpBits-MidBits)
4985         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4986     } else {
4987       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4988       // bits, just truncate to i32.
4989       if (NumSignBits > OpBits-MidBits)
4990         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4991     }
4992
4993     // fold (sext (truncate x)) -> (sextinreg x).
4994     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4995                                                  N0.getValueType())) {
4996       if (OpBits < DestBits)
4997         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4998       else if (OpBits > DestBits)
4999         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5000       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5001                          DAG.getValueType(N0.getValueType()));
5002     }
5003   }
5004
5005   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5006   // None of the supported targets knows how to perform load and sign extend
5007   // on vectors in one instruction.  We only perform this transformation on
5008   // scalars.
5009   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5010       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5011       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5012        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5013     bool DoXform = true;
5014     SmallVector<SDNode*, 4> SetCCs;
5015     if (!N0.hasOneUse())
5016       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5017     if (DoXform) {
5018       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5019       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5020                                        LN0->getChain(),
5021                                        LN0->getBasePtr(), N0.getValueType(),
5022                                        LN0->getMemOperand());
5023       CombineTo(N, ExtLoad);
5024       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5025                                   N0.getValueType(), ExtLoad);
5026       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5027       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5028                       ISD::SIGN_EXTEND);
5029       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5030     }
5031   }
5032
5033   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5034   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5035   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5036       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5037     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5038     EVT MemVT = LN0->getMemoryVT();
5039     if ((!LegalOperations && !LN0->isVolatile()) ||
5040         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5041       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5042                                        LN0->getChain(),
5043                                        LN0->getBasePtr(), MemVT,
5044                                        LN0->getMemOperand());
5045       CombineTo(N, ExtLoad);
5046       CombineTo(N0.getNode(),
5047                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5048                             N0.getValueType(), ExtLoad),
5049                 ExtLoad.getValue(1));
5050       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5051     }
5052   }
5053
5054   // fold (sext (and/or/xor (load x), cst)) ->
5055   //      (and/or/xor (sextload x), (sext cst))
5056   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5057        N0.getOpcode() == ISD::XOR) &&
5058       isa<LoadSDNode>(N0.getOperand(0)) &&
5059       N0.getOperand(1).getOpcode() == ISD::Constant &&
5060       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5061       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5062     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5063     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5064       bool DoXform = true;
5065       SmallVector<SDNode*, 4> SetCCs;
5066       if (!N0.hasOneUse())
5067         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5068                                           SetCCs, TLI);
5069       if (DoXform) {
5070         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5071                                          LN0->getChain(), LN0->getBasePtr(),
5072                                          LN0->getMemoryVT(),
5073                                          LN0->getMemOperand());
5074         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5075         Mask = Mask.sext(VT.getSizeInBits());
5076         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5077                                   ExtLoad, DAG.getConstant(Mask, VT));
5078         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5079                                     SDLoc(N0.getOperand(0)),
5080                                     N0.getOperand(0).getValueType(), ExtLoad);
5081         CombineTo(N, And);
5082         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5083         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5084                         ISD::SIGN_EXTEND);
5085         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5086       }
5087     }
5088   }
5089
5090   if (N0.getOpcode() == ISD::SETCC) {
5091     EVT N0VT = N0.getOperand(0).getValueType();
5092     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5093     // Only do this before legalize for now.
5094     if (VT.isVector() && !LegalOperations &&
5095         TLI.getBooleanContents(N0VT) ==
5096             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5097       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5098       // of the same size as the compared operands. Only optimize sext(setcc())
5099       // if this is the case.
5100       EVT SVT = getSetCCResultType(N0VT);
5101
5102       // We know that the # elements of the results is the same as the
5103       // # elements of the compare (and the # elements of the compare result
5104       // for that matter).  Check to see that they are the same size.  If so,
5105       // we know that the element size of the sext'd result matches the
5106       // element size of the compare operands.
5107       if (VT.getSizeInBits() == SVT.getSizeInBits())
5108         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5109                              N0.getOperand(1),
5110                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5111
5112       // If the desired elements are smaller or larger than the source
5113       // elements we can use a matching integer vector type and then
5114       // truncate/sign extend
5115       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5116       if (SVT == MatchingVectorType) {
5117         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5118                                N0.getOperand(0), N0.getOperand(1),
5119                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5120         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5121       }
5122     }
5123
5124     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5125     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5126     SDValue NegOne =
5127       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5128     SDValue SCC =
5129       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5130                        NegOne, DAG.getConstant(0, VT),
5131                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5132     if (SCC.getNode()) return SCC;
5133
5134     if (!VT.isVector()) {
5135       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5136       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5137         SDLoc DL(N);
5138         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5139         SDValue SetCC = DAG.getSetCC(DL,
5140                                      SetCCVT,
5141                                      N0.getOperand(0), N0.getOperand(1), CC);
5142         EVT SelectVT = getSetCCResultType(VT);
5143         return DAG.getSelect(DL, VT,
5144                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5145                              NegOne, DAG.getConstant(0, VT));
5146
5147       }
5148     }
5149   }
5150
5151   // fold (sext x) -> (zext x) if the sign bit is known zero.
5152   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5153       DAG.SignBitIsZero(N0))
5154     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5155
5156   return SDValue();
5157 }
5158
5159 // isTruncateOf - If N is a truncate of some other value, return true, record
5160 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5161 // This function computes KnownZero to avoid a duplicated call to
5162 // computeKnownBits in the caller.
5163 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5164                          APInt &KnownZero) {
5165   APInt KnownOne;
5166   if (N->getOpcode() == ISD::TRUNCATE) {
5167     Op = N->getOperand(0);
5168     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5169     return true;
5170   }
5171
5172   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5173       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5174     return false;
5175
5176   SDValue Op0 = N->getOperand(0);
5177   SDValue Op1 = N->getOperand(1);
5178   assert(Op0.getValueType() == Op1.getValueType());
5179
5180   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5181   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5182   if (COp0 && COp0->isNullValue())
5183     Op = Op1;
5184   else if (COp1 && COp1->isNullValue())
5185     Op = Op0;
5186   else
5187     return false;
5188
5189   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5190
5191   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5192     return false;
5193
5194   return true;
5195 }
5196
5197 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5198   SDValue N0 = N->getOperand(0);
5199   EVT VT = N->getValueType(0);
5200
5201   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5202                                               LegalOperations))
5203     return SDValue(Res, 0);
5204
5205   // fold (zext (zext x)) -> (zext x)
5206   // fold (zext (aext x)) -> (zext x)
5207   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5208     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5209                        N0.getOperand(0));
5210
5211   // fold (zext (truncate x)) -> (zext x) or
5212   //      (zext (truncate x)) -> (truncate x)
5213   // This is valid when the truncated bits of x are already zero.
5214   // FIXME: We should extend this to work for vectors too.
5215   SDValue Op;
5216   APInt KnownZero;
5217   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5218     APInt TruncatedBits =
5219       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5220       APInt(Op.getValueSizeInBits(), 0) :
5221       APInt::getBitsSet(Op.getValueSizeInBits(),
5222                         N0.getValueSizeInBits(),
5223                         std::min(Op.getValueSizeInBits(),
5224                                  VT.getSizeInBits()));
5225     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5226       if (VT.bitsGT(Op.getValueType()))
5227         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5228       if (VT.bitsLT(Op.getValueType()))
5229         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5230
5231       return Op;
5232     }
5233   }
5234
5235   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5236   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5237   if (N0.getOpcode() == ISD::TRUNCATE) {
5238     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5239     if (NarrowLoad.getNode()) {
5240       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5241       if (NarrowLoad.getNode() != N0.getNode()) {
5242         CombineTo(N0.getNode(), NarrowLoad);
5243         // CombineTo deleted the truncate, if needed, but not what's under it.
5244         AddToWorkList(oye);
5245       }
5246       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5247     }
5248   }
5249
5250   // fold (zext (truncate x)) -> (and x, mask)
5251   if (N0.getOpcode() == ISD::TRUNCATE &&
5252       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5253
5254     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5255     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5256     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5257     if (NarrowLoad.getNode()) {
5258       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5259       if (NarrowLoad.getNode() != N0.getNode()) {
5260         CombineTo(N0.getNode(), NarrowLoad);
5261         // CombineTo deleted the truncate, if needed, but not what's under it.
5262         AddToWorkList(oye);
5263       }
5264       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5265     }
5266
5267     SDValue Op = N0.getOperand(0);
5268     if (Op.getValueType().bitsLT(VT)) {
5269       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5270       AddToWorkList(Op.getNode());
5271     } else if (Op.getValueType().bitsGT(VT)) {
5272       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5273       AddToWorkList(Op.getNode());
5274     }
5275     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5276                                   N0.getValueType().getScalarType());
5277   }
5278
5279   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5280   // if either of the casts is not free.
5281   if (N0.getOpcode() == ISD::AND &&
5282       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5283       N0.getOperand(1).getOpcode() == ISD::Constant &&
5284       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5285                            N0.getValueType()) ||
5286        !TLI.isZExtFree(N0.getValueType(), VT))) {
5287     SDValue X = N0.getOperand(0).getOperand(0);
5288     if (X.getValueType().bitsLT(VT)) {
5289       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5290     } else if (X.getValueType().bitsGT(VT)) {
5291       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5292     }
5293     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5294     Mask = Mask.zext(VT.getSizeInBits());
5295     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5296                        X, DAG.getConstant(Mask, VT));
5297   }
5298
5299   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5300   // None of the supported targets knows how to perform load and vector_zext
5301   // on vectors in one instruction.  We only perform this transformation on
5302   // scalars.
5303   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5304       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5305       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5306        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5307     bool DoXform = true;
5308     SmallVector<SDNode*, 4> SetCCs;
5309     if (!N0.hasOneUse())
5310       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5311     if (DoXform) {
5312       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5313       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5314                                        LN0->getChain(),
5315                                        LN0->getBasePtr(), N0.getValueType(),
5316                                        LN0->getMemOperand());
5317       CombineTo(N, ExtLoad);
5318       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5319                                   N0.getValueType(), ExtLoad);
5320       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5321
5322       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5323                       ISD::ZERO_EXTEND);
5324       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5325     }
5326   }
5327
5328   // fold (zext (and/or/xor (load x), cst)) ->
5329   //      (and/or/xor (zextload x), (zext cst))
5330   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5331        N0.getOpcode() == ISD::XOR) &&
5332       isa<LoadSDNode>(N0.getOperand(0)) &&
5333       N0.getOperand(1).getOpcode() == ISD::Constant &&
5334       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5335       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5336     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5337     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5338       bool DoXform = true;
5339       SmallVector<SDNode*, 4> SetCCs;
5340       if (!N0.hasOneUse())
5341         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5342                                           SetCCs, TLI);
5343       if (DoXform) {
5344         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5345                                          LN0->getChain(), LN0->getBasePtr(),
5346                                          LN0->getMemoryVT(),
5347                                          LN0->getMemOperand());
5348         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5349         Mask = Mask.zext(VT.getSizeInBits());
5350         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5351                                   ExtLoad, DAG.getConstant(Mask, VT));
5352         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5353                                     SDLoc(N0.getOperand(0)),
5354                                     N0.getOperand(0).getValueType(), ExtLoad);
5355         CombineTo(N, And);
5356         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5357         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5358                         ISD::ZERO_EXTEND);
5359         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5360       }
5361     }
5362   }
5363
5364   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5365   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5366   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5367       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5368     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5369     EVT MemVT = LN0->getMemoryVT();
5370     if ((!LegalOperations && !LN0->isVolatile()) ||
5371         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5372       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5373                                        LN0->getChain(),
5374                                        LN0->getBasePtr(), MemVT,
5375                                        LN0->getMemOperand());
5376       CombineTo(N, ExtLoad);
5377       CombineTo(N0.getNode(),
5378                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5379                             ExtLoad),
5380                 ExtLoad.getValue(1));
5381       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5382     }
5383   }
5384
5385   if (N0.getOpcode() == ISD::SETCC) {
5386     if (!LegalOperations && VT.isVector() &&
5387         N0.getValueType().getVectorElementType() == MVT::i1) {
5388       EVT N0VT = N0.getOperand(0).getValueType();
5389       if (getSetCCResultType(N0VT) == N0.getValueType())
5390         return SDValue();
5391
5392       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5393       // Only do this before legalize for now.
5394       EVT EltVT = VT.getVectorElementType();
5395       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5396                                     DAG.getConstant(1, EltVT));
5397       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5398         // We know that the # elements of the results is the same as the
5399         // # elements of the compare (and the # elements of the compare result
5400         // for that matter).  Check to see that they are the same size.  If so,
5401         // we know that the element size of the sext'd result matches the
5402         // element size of the compare operands.
5403         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5404                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5405                                          N0.getOperand(1),
5406                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5407                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5408                                        OneOps));
5409
5410       // If the desired elements are smaller or larger than the source
5411       // elements we can use a matching integer vector type and then
5412       // truncate/sign extend
5413       EVT MatchingElementType =
5414         EVT::getIntegerVT(*DAG.getContext(),
5415                           N0VT.getScalarType().getSizeInBits());
5416       EVT MatchingVectorType =
5417         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5418                          N0VT.getVectorNumElements());
5419       SDValue VsetCC =
5420         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5421                       N0.getOperand(1),
5422                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5423       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5424                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5425                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5426     }
5427
5428     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5429     SDValue SCC =
5430       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5431                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5432                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5433     if (SCC.getNode()) return SCC;
5434   }
5435
5436   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5437   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5438       isa<ConstantSDNode>(N0.getOperand(1)) &&
5439       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5440       N0.hasOneUse()) {
5441     SDValue ShAmt = N0.getOperand(1);
5442     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5443     if (N0.getOpcode() == ISD::SHL) {
5444       SDValue InnerZExt = N0.getOperand(0);
5445       // If the original shl may be shifting out bits, do not perform this
5446       // transformation.
5447       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5448         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5449       if (ShAmtVal > KnownZeroBits)
5450         return SDValue();
5451     }
5452
5453     SDLoc DL(N);
5454
5455     // Ensure that the shift amount is wide enough for the shifted value.
5456     if (VT.getSizeInBits() >= 256)
5457       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5458
5459     return DAG.getNode(N0.getOpcode(), DL, VT,
5460                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5461                        ShAmt);
5462   }
5463
5464   return SDValue();
5465 }
5466
5467 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5468   SDValue N0 = N->getOperand(0);
5469   EVT VT = N->getValueType(0);
5470
5471   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5472                                               LegalOperations))
5473     return SDValue(Res, 0);
5474
5475   // fold (aext (aext x)) -> (aext x)
5476   // fold (aext (zext x)) -> (zext x)
5477   // fold (aext (sext x)) -> (sext x)
5478   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5479       N0.getOpcode() == ISD::ZERO_EXTEND ||
5480       N0.getOpcode() == ISD::SIGN_EXTEND)
5481     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5482
5483   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5484   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5485   if (N0.getOpcode() == ISD::TRUNCATE) {
5486     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5487     if (NarrowLoad.getNode()) {
5488       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5489       if (NarrowLoad.getNode() != N0.getNode()) {
5490         CombineTo(N0.getNode(), NarrowLoad);
5491         // CombineTo deleted the truncate, if needed, but not what's under it.
5492         AddToWorkList(oye);
5493       }
5494       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5495     }
5496   }
5497
5498   // fold (aext (truncate x))
5499   if (N0.getOpcode() == ISD::TRUNCATE) {
5500     SDValue TruncOp = N0.getOperand(0);
5501     if (TruncOp.getValueType() == VT)
5502       return TruncOp; // x iff x size == zext size.
5503     if (TruncOp.getValueType().bitsGT(VT))
5504       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5505     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5506   }
5507
5508   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5509   // if the trunc is not free.
5510   if (N0.getOpcode() == ISD::AND &&
5511       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5512       N0.getOperand(1).getOpcode() == ISD::Constant &&
5513       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5514                           N0.getValueType())) {
5515     SDValue X = N0.getOperand(0).getOperand(0);
5516     if (X.getValueType().bitsLT(VT)) {
5517       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5518     } else if (X.getValueType().bitsGT(VT)) {
5519       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5520     }
5521     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5522     Mask = Mask.zext(VT.getSizeInBits());
5523     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5524                        X, DAG.getConstant(Mask, VT));
5525   }
5526
5527   // fold (aext (load x)) -> (aext (truncate (extload x)))
5528   // None of the supported targets knows how to perform load and any_ext
5529   // on vectors in one instruction.  We only perform this transformation on
5530   // scalars.
5531   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5532       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5533       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5534        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5535     bool DoXform = true;
5536     SmallVector<SDNode*, 4> SetCCs;
5537     if (!N0.hasOneUse())
5538       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5539     if (DoXform) {
5540       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5541       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5542                                        LN0->getChain(),
5543                                        LN0->getBasePtr(), N0.getValueType(),
5544                                        LN0->getMemOperand());
5545       CombineTo(N, ExtLoad);
5546       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5547                                   N0.getValueType(), ExtLoad);
5548       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5549       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5550                       ISD::ANY_EXTEND);
5551       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5552     }
5553   }
5554
5555   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5556   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5557   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5558   if (N0.getOpcode() == ISD::LOAD &&
5559       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5560       N0.hasOneUse()) {
5561     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5562     ISD::LoadExtType ExtType = LN0->getExtensionType();
5563     EVT MemVT = LN0->getMemoryVT();
5564     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5565       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5566                                        VT, LN0->getChain(), LN0->getBasePtr(),
5567                                        MemVT, LN0->getMemOperand());
5568       CombineTo(N, ExtLoad);
5569       CombineTo(N0.getNode(),
5570                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5571                             N0.getValueType(), ExtLoad),
5572                 ExtLoad.getValue(1));
5573       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5574     }
5575   }
5576
5577   if (N0.getOpcode() == ISD::SETCC) {
5578     // For vectors:
5579     // aext(setcc) -> vsetcc
5580     // aext(setcc) -> truncate(vsetcc)
5581     // aext(setcc) -> aext(vsetcc)
5582     // Only do this before legalize for now.
5583     if (VT.isVector() && !LegalOperations) {
5584       EVT N0VT = N0.getOperand(0).getValueType();
5585         // We know that the # elements of the results is the same as the
5586         // # elements of the compare (and the # elements of the compare result
5587         // for that matter).  Check to see that they are the same size.  If so,
5588         // we know that the element size of the sext'd result matches the
5589         // element size of the compare operands.
5590       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5591         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5592                              N0.getOperand(1),
5593                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5594       // If the desired elements are smaller or larger than the source
5595       // elements we can use a matching integer vector type and then
5596       // truncate/any extend
5597       else {
5598         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5599         SDValue VsetCC =
5600           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5601                         N0.getOperand(1),
5602                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5603         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5604       }
5605     }
5606
5607     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5608     SDValue SCC =
5609       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5610                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5611                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5612     if (SCC.getNode())
5613       return SCC;
5614   }
5615
5616   return SDValue();
5617 }
5618
5619 /// GetDemandedBits - See if the specified operand can be simplified with the
5620 /// knowledge that only the bits specified by Mask are used.  If so, return the
5621 /// simpler operand, otherwise return a null SDValue.
5622 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5623   switch (V.getOpcode()) {
5624   default: break;
5625   case ISD::Constant: {
5626     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5627     assert(CV && "Const value should be ConstSDNode.");
5628     const APInt &CVal = CV->getAPIntValue();
5629     APInt NewVal = CVal & Mask;
5630     if (NewVal != CVal)
5631       return DAG.getConstant(NewVal, V.getValueType());
5632     break;
5633   }
5634   case ISD::OR:
5635   case ISD::XOR:
5636     // If the LHS or RHS don't contribute bits to the or, drop them.
5637     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5638       return V.getOperand(1);
5639     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5640       return V.getOperand(0);
5641     break;
5642   case ISD::SRL:
5643     // Only look at single-use SRLs.
5644     if (!V.getNode()->hasOneUse())
5645       break;
5646     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5647       // See if we can recursively simplify the LHS.
5648       unsigned Amt = RHSC->getZExtValue();
5649
5650       // Watch out for shift count overflow though.
5651       if (Amt >= Mask.getBitWidth()) break;
5652       APInt NewMask = Mask << Amt;
5653       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5654       if (SimplifyLHS.getNode())
5655         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5656                            SimplifyLHS, V.getOperand(1));
5657     }
5658   }
5659   return SDValue();
5660 }
5661
5662 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5663 /// bits and then truncated to a narrower type and where N is a multiple
5664 /// of number of bits of the narrower type, transform it to a narrower load
5665 /// from address + N / num of bits of new type. If the result is to be
5666 /// extended, also fold the extension to form a extending load.
5667 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5668   unsigned Opc = N->getOpcode();
5669
5670   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5671   SDValue N0 = N->getOperand(0);
5672   EVT VT = N->getValueType(0);
5673   EVT ExtVT = VT;
5674
5675   // This transformation isn't valid for vector loads.
5676   if (VT.isVector())
5677     return SDValue();
5678
5679   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5680   // extended to VT.
5681   if (Opc == ISD::SIGN_EXTEND_INREG) {
5682     ExtType = ISD::SEXTLOAD;
5683     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5684   } else if (Opc == ISD::SRL) {
5685     // Another special-case: SRL is basically zero-extending a narrower value.
5686     ExtType = ISD::ZEXTLOAD;
5687     N0 = SDValue(N, 0);
5688     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5689     if (!N01) return SDValue();
5690     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5691                               VT.getSizeInBits() - N01->getZExtValue());
5692   }
5693   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5694     return SDValue();
5695
5696   unsigned EVTBits = ExtVT.getSizeInBits();
5697
5698   // Do not generate loads of non-round integer types since these can
5699   // be expensive (and would be wrong if the type is not byte sized).
5700   if (!ExtVT.isRound())
5701     return SDValue();
5702
5703   unsigned ShAmt = 0;
5704   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5705     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5706       ShAmt = N01->getZExtValue();
5707       // Is the shift amount a multiple of size of VT?
5708       if ((ShAmt & (EVTBits-1)) == 0) {
5709         N0 = N0.getOperand(0);
5710         // Is the load width a multiple of size of VT?
5711         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5712           return SDValue();
5713       }
5714
5715       // At this point, we must have a load or else we can't do the transform.
5716       if (!isa<LoadSDNode>(N0)) return SDValue();
5717
5718       // Because a SRL must be assumed to *need* to zero-extend the high bits
5719       // (as opposed to anyext the high bits), we can't combine the zextload
5720       // lowering of SRL and an sextload.
5721       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5722         return SDValue();
5723
5724       // If the shift amount is larger than the input type then we're not
5725       // accessing any of the loaded bytes.  If the load was a zextload/extload
5726       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5727       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5728         return SDValue();
5729     }
5730   }
5731
5732   // If the load is shifted left (and the result isn't shifted back right),
5733   // we can fold the truncate through the shift.
5734   unsigned ShLeftAmt = 0;
5735   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5736       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5737     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5738       ShLeftAmt = N01->getZExtValue();
5739       N0 = N0.getOperand(0);
5740     }
5741   }
5742
5743   // If we haven't found a load, we can't narrow it.  Don't transform one with
5744   // multiple uses, this would require adding a new load.
5745   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5746     return SDValue();
5747
5748   // Don't change the width of a volatile load.
5749   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5750   if (LN0->isVolatile())
5751     return SDValue();
5752
5753   // Verify that we are actually reducing a load width here.
5754   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5755     return SDValue();
5756
5757   // For the transform to be legal, the load must produce only two values
5758   // (the value loaded and the chain).  Don't transform a pre-increment
5759   // load, for example, which produces an extra value.  Otherwise the
5760   // transformation is not equivalent, and the downstream logic to replace
5761   // uses gets things wrong.
5762   if (LN0->getNumValues() > 2)
5763     return SDValue();
5764
5765   // If the load that we're shrinking is an extload and we're not just
5766   // discarding the extension we can't simply shrink the load. Bail.
5767   // TODO: It would be possible to merge the extensions in some cases.
5768   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5769       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5770     return SDValue();
5771
5772   EVT PtrType = N0.getOperand(1).getValueType();
5773
5774   if (PtrType == MVT::Untyped || PtrType.isExtended())
5775     // It's not possible to generate a constant of extended or untyped type.
5776     return SDValue();
5777
5778   // For big endian targets, we need to adjust the offset to the pointer to
5779   // load the correct bytes.
5780   if (TLI.isBigEndian()) {
5781     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5782     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5783     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5784   }
5785
5786   uint64_t PtrOff = ShAmt / 8;
5787   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5788   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5789                                PtrType, LN0->getBasePtr(),
5790                                DAG.getConstant(PtrOff, PtrType));
5791   AddToWorkList(NewPtr.getNode());
5792
5793   SDValue Load;
5794   if (ExtType == ISD::NON_EXTLOAD)
5795     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5796                         LN0->getPointerInfo().getWithOffset(PtrOff),
5797                         LN0->isVolatile(), LN0->isNonTemporal(),
5798                         LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5799   else
5800     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5801                           LN0->getPointerInfo().getWithOffset(PtrOff),
5802                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5803                           NewAlign, LN0->getTBAAInfo());
5804
5805   // Replace the old load's chain with the new load's chain.
5806   WorkListRemover DeadNodes(*this);
5807   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5808
5809   // Shift the result left, if we've swallowed a left shift.
5810   SDValue Result = Load;
5811   if (ShLeftAmt != 0) {
5812     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5813     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5814       ShImmTy = VT;
5815     // If the shift amount is as large as the result size (but, presumably,
5816     // no larger than the source) then the useful bits of the result are
5817     // zero; we can't simply return the shortened shift, because the result
5818     // of that operation is undefined.
5819     if (ShLeftAmt >= VT.getSizeInBits())
5820       Result = DAG.getConstant(0, VT);
5821     else
5822       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5823                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5824   }
5825
5826   // Return the new loaded value.
5827   return Result;
5828 }
5829
5830 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5831   SDValue N0 = N->getOperand(0);
5832   SDValue N1 = N->getOperand(1);
5833   EVT VT = N->getValueType(0);
5834   EVT EVT = cast<VTSDNode>(N1)->getVT();
5835   unsigned VTBits = VT.getScalarType().getSizeInBits();
5836   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5837
5838   // fold (sext_in_reg c1) -> c1
5839   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5840     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5841
5842   // If the input is already sign extended, just drop the extension.
5843   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5844     return N0;
5845
5846   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5847   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5848       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5849     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5850                        N0.getOperand(0), N1);
5851
5852   // fold (sext_in_reg (sext x)) -> (sext x)
5853   // fold (sext_in_reg (aext x)) -> (sext x)
5854   // if x is small enough.
5855   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5856     SDValue N00 = N0.getOperand(0);
5857     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5858         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5859       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5860   }
5861
5862   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5863   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5864     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5865
5866   // fold operands of sext_in_reg based on knowledge that the top bits are not
5867   // demanded.
5868   if (SimplifyDemandedBits(SDValue(N, 0)))
5869     return SDValue(N, 0);
5870
5871   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5872   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5873   SDValue NarrowLoad = ReduceLoadWidth(N);
5874   if (NarrowLoad.getNode())
5875     return NarrowLoad;
5876
5877   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5878   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5879   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5880   if (N0.getOpcode() == ISD::SRL) {
5881     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5882       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5883         // We can turn this into an SRA iff the input to the SRL is already sign
5884         // extended enough.
5885         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5886         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5887           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5888                              N0.getOperand(0), N0.getOperand(1));
5889       }
5890   }
5891
5892   // fold (sext_inreg (extload x)) -> (sextload x)
5893   if (ISD::isEXTLoad(N0.getNode()) &&
5894       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5895       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5896       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5897        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5898     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5899     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5900                                      LN0->getChain(),
5901                                      LN0->getBasePtr(), EVT,
5902                                      LN0->getMemOperand());
5903     CombineTo(N, ExtLoad);
5904     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5905     AddToWorkList(ExtLoad.getNode());
5906     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5907   }
5908   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5909   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5910       N0.hasOneUse() &&
5911       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5912       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5913        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5914     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5915     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5916                                      LN0->getChain(),
5917                                      LN0->getBasePtr(), EVT,
5918                                      LN0->getMemOperand());
5919     CombineTo(N, ExtLoad);
5920     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5921     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5922   }
5923
5924   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5925   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5926     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5927                                        N0.getOperand(1), false);
5928     if (BSwap.getNode())
5929       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5930                          BSwap, N1);
5931   }
5932
5933   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5934   // into a build_vector.
5935   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5936     SmallVector<SDValue, 8> Elts;
5937     unsigned NumElts = N0->getNumOperands();
5938     unsigned ShAmt = VTBits - EVTBits;
5939
5940     for (unsigned i = 0; i != NumElts; ++i) {
5941       SDValue Op = N0->getOperand(i);
5942       if (Op->getOpcode() == ISD::UNDEF) {
5943         Elts.push_back(Op);
5944         continue;
5945       }
5946
5947       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5948       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5949       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5950                                      Op.getValueType()));
5951     }
5952
5953     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5954   }
5955
5956   return SDValue();
5957 }
5958
5959 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5960   SDValue N0 = N->getOperand(0);
5961   EVT VT = N->getValueType(0);
5962   bool isLE = TLI.isLittleEndian();
5963
5964   // noop truncate
5965   if (N0.getValueType() == N->getValueType(0))
5966     return N0;
5967   // fold (truncate c1) -> c1
5968   if (isa<ConstantSDNode>(N0))
5969     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5970   // fold (truncate (truncate x)) -> (truncate x)
5971   if (N0.getOpcode() == ISD::TRUNCATE)
5972     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5973   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5974   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5975       N0.getOpcode() == ISD::SIGN_EXTEND ||
5976       N0.getOpcode() == ISD::ANY_EXTEND) {
5977     if (N0.getOperand(0).getValueType().bitsLT(VT))
5978       // if the source is smaller than the dest, we still need an extend
5979       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5980                          N0.getOperand(0));
5981     if (N0.getOperand(0).getValueType().bitsGT(VT))
5982       // if the source is larger than the dest, than we just need the truncate
5983       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5984     // if the source and dest are the same type, we can drop both the extend
5985     // and the truncate.
5986     return N0.getOperand(0);
5987   }
5988
5989   // Fold extract-and-trunc into a narrow extract. For example:
5990   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5991   //   i32 y = TRUNCATE(i64 x)
5992   //        -- becomes --
5993   //   v16i8 b = BITCAST (v2i64 val)
5994   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5995   //
5996   // Note: We only run this optimization after type legalization (which often
5997   // creates this pattern) and before operation legalization after which
5998   // we need to be more careful about the vector instructions that we generate.
5999   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6000       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6001
6002     EVT VecTy = N0.getOperand(0).getValueType();
6003     EVT ExTy = N0.getValueType();
6004     EVT TrTy = N->getValueType(0);
6005
6006     unsigned NumElem = VecTy.getVectorNumElements();
6007     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6008
6009     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6010     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6011
6012     SDValue EltNo = N0->getOperand(1);
6013     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6014       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6015       EVT IndexTy = TLI.getVectorIdxTy();
6016       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6017
6018       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6019                               NVT, N0.getOperand(0));
6020
6021       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6022                          SDLoc(N), TrTy, V,
6023                          DAG.getConstant(Index, IndexTy));
6024     }
6025   }
6026
6027   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6028   if (N0.getOpcode() == ISD::SELECT) {
6029     EVT SrcVT = N0.getValueType();
6030     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6031         TLI.isTruncateFree(SrcVT, VT)) {
6032       SDLoc SL(N0);
6033       SDValue Cond = N0.getOperand(0);
6034       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6035       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6036       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6037     }
6038   }
6039
6040   // Fold a series of buildvector, bitcast, and truncate if possible.
6041   // For example fold
6042   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6043   //   (2xi32 (buildvector x, y)).
6044   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6045       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6046       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6047       N0.getOperand(0).hasOneUse()) {
6048
6049     SDValue BuildVect = N0.getOperand(0);
6050     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6051     EVT TruncVecEltTy = VT.getVectorElementType();
6052
6053     // Check that the element types match.
6054     if (BuildVectEltTy == TruncVecEltTy) {
6055       // Now we only need to compute the offset of the truncated elements.
6056       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6057       unsigned TruncVecNumElts = VT.getVectorNumElements();
6058       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6059
6060       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6061              "Invalid number of elements");
6062
6063       SmallVector<SDValue, 8> Opnds;
6064       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6065         Opnds.push_back(BuildVect.getOperand(i));
6066
6067       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6068     }
6069   }
6070
6071   // See if we can simplify the input to this truncate through knowledge that
6072   // only the low bits are being used.
6073   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6074   // Currently we only perform this optimization on scalars because vectors
6075   // may have different active low bits.
6076   if (!VT.isVector()) {
6077     SDValue Shorter =
6078       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6079                                                VT.getSizeInBits()));
6080     if (Shorter.getNode())
6081       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6082   }
6083   // fold (truncate (load x)) -> (smaller load x)
6084   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6085   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6086     SDValue Reduced = ReduceLoadWidth(N);
6087     if (Reduced.getNode())
6088       return Reduced;
6089     // Handle the case where the load remains an extending load even
6090     // after truncation.
6091     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6092       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6093       if (!LN0->isVolatile() &&
6094           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6095         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6096                                          VT, LN0->getChain(), LN0->getBasePtr(),
6097                                          LN0->getMemoryVT(),
6098                                          LN0->getMemOperand());
6099         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6100         return NewLoad;
6101       }
6102     }
6103   }
6104   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6105   // where ... are all 'undef'.
6106   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6107     SmallVector<EVT, 8> VTs;
6108     SDValue V;
6109     unsigned Idx = 0;
6110     unsigned NumDefs = 0;
6111
6112     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6113       SDValue X = N0.getOperand(i);
6114       if (X.getOpcode() != ISD::UNDEF) {
6115         V = X;
6116         Idx = i;
6117         NumDefs++;
6118       }
6119       // Stop if more than one members are non-undef.
6120       if (NumDefs > 1)
6121         break;
6122       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6123                                      VT.getVectorElementType(),
6124                                      X.getValueType().getVectorNumElements()));
6125     }
6126
6127     if (NumDefs == 0)
6128       return DAG.getUNDEF(VT);
6129
6130     if (NumDefs == 1) {
6131       assert(V.getNode() && "The single defined operand is empty!");
6132       SmallVector<SDValue, 8> Opnds;
6133       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6134         if (i != Idx) {
6135           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6136           continue;
6137         }
6138         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6139         AddToWorkList(NV.getNode());
6140         Opnds.push_back(NV);
6141       }
6142       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6143     }
6144   }
6145
6146   // Simplify the operands using demanded-bits information.
6147   if (!VT.isVector() &&
6148       SimplifyDemandedBits(SDValue(N, 0)))
6149     return SDValue(N, 0);
6150
6151   return SDValue();
6152 }
6153
6154 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6155   SDValue Elt = N->getOperand(i);
6156   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6157     return Elt.getNode();
6158   return Elt.getOperand(Elt.getResNo()).getNode();
6159 }
6160
6161 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6162 /// if load locations are consecutive.
6163 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6164   assert(N->getOpcode() == ISD::BUILD_PAIR);
6165
6166   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6167   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6168   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6169       LD1->getAddressSpace() != LD2->getAddressSpace())
6170     return SDValue();
6171   EVT LD1VT = LD1->getValueType(0);
6172
6173   if (ISD::isNON_EXTLoad(LD2) &&
6174       LD2->hasOneUse() &&
6175       // If both are volatile this would reduce the number of volatile loads.
6176       // If one is volatile it might be ok, but play conservative and bail out.
6177       !LD1->isVolatile() &&
6178       !LD2->isVolatile() &&
6179       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6180     unsigned Align = LD1->getAlignment();
6181     unsigned NewAlign = TLI.getDataLayout()->
6182       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6183
6184     if (NewAlign <= Align &&
6185         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6186       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6187                          LD1->getBasePtr(), LD1->getPointerInfo(),
6188                          false, false, false, Align);
6189   }
6190
6191   return SDValue();
6192 }
6193
6194 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6195   SDValue N0 = N->getOperand(0);
6196   EVT VT = N->getValueType(0);
6197
6198   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6199   // Only do this before legalize, since afterward the target may be depending
6200   // on the bitconvert.
6201   // First check to see if this is all constant.
6202   if (!LegalTypes &&
6203       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6204       VT.isVector()) {
6205     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6206
6207     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6208     assert(!DestEltVT.isVector() &&
6209            "Element type of vector ValueType must not be vector!");
6210     if (isSimple)
6211       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6212   }
6213
6214   // If the input is a constant, let getNode fold it.
6215   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6216     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6217     if (Res.getNode() != N) {
6218       if (!LegalOperations ||
6219           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6220         return Res;
6221
6222       // Folding it resulted in an illegal node, and it's too late to
6223       // do that. Clean up the old node and forego the transformation.
6224       // Ideally this won't happen very often, because instcombine
6225       // and the earlier dagcombine runs (where illegal nodes are
6226       // permitted) should have folded most of them already.
6227       DAG.DeleteNode(Res.getNode());
6228     }
6229   }
6230
6231   // (conv (conv x, t1), t2) -> (conv x, t2)
6232   if (N0.getOpcode() == ISD::BITCAST)
6233     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6234                        N0.getOperand(0));
6235
6236   // fold (conv (load x)) -> (load (conv*)x)
6237   // If the resultant load doesn't need a higher alignment than the original!
6238   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6239       // Do not change the width of a volatile load.
6240       !cast<LoadSDNode>(N0)->isVolatile() &&
6241       // Do not remove the cast if the types differ in endian layout.
6242       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6243       TLI.hasBigEndianPartOrdering(VT) &&
6244       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6245       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6246     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6247     unsigned Align = TLI.getDataLayout()->
6248       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6249     unsigned OrigAlign = LN0->getAlignment();
6250
6251     if (Align <= OrigAlign) {
6252       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6253                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6254                                  LN0->isVolatile(), LN0->isNonTemporal(),
6255                                  LN0->isInvariant(), OrigAlign,
6256                                  LN0->getTBAAInfo());
6257       AddToWorkList(N);
6258       CombineTo(N0.getNode(),
6259                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6260                             N0.getValueType(), Load),
6261                 Load.getValue(1));
6262       return Load;
6263     }
6264   }
6265
6266   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6267   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6268   // This often reduces constant pool loads.
6269   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6270        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6271       N0.getNode()->hasOneUse() && VT.isInteger() &&
6272       !VT.isVector() && !N0.getValueType().isVector()) {
6273     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6274                                   N0.getOperand(0));
6275     AddToWorkList(NewConv.getNode());
6276
6277     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6278     if (N0.getOpcode() == ISD::FNEG)
6279       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6280                          NewConv, DAG.getConstant(SignBit, VT));
6281     assert(N0.getOpcode() == ISD::FABS);
6282     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6283                        NewConv, DAG.getConstant(~SignBit, VT));
6284   }
6285
6286   // fold (bitconvert (fcopysign cst, x)) ->
6287   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6288   // Note that we don't handle (copysign x, cst) because this can always be
6289   // folded to an fneg or fabs.
6290   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6291       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6292       VT.isInteger() && !VT.isVector()) {
6293     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6294     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6295     if (isTypeLegal(IntXVT)) {
6296       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6297                               IntXVT, N0.getOperand(1));
6298       AddToWorkList(X.getNode());
6299
6300       // If X has a different width than the result/lhs, sext it or truncate it.
6301       unsigned VTWidth = VT.getSizeInBits();
6302       if (OrigXWidth < VTWidth) {
6303         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6304         AddToWorkList(X.getNode());
6305       } else if (OrigXWidth > VTWidth) {
6306         // To get the sign bit in the right place, we have to shift it right
6307         // before truncating.
6308         X = DAG.getNode(ISD::SRL, SDLoc(X),
6309                         X.getValueType(), X,
6310                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6311         AddToWorkList(X.getNode());
6312         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6313         AddToWorkList(X.getNode());
6314       }
6315
6316       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6317       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6318                       X, DAG.getConstant(SignBit, VT));
6319       AddToWorkList(X.getNode());
6320
6321       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6322                                 VT, N0.getOperand(0));
6323       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6324                         Cst, DAG.getConstant(~SignBit, VT));
6325       AddToWorkList(Cst.getNode());
6326
6327       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6328     }
6329   }
6330
6331   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6332   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6333     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6334     if (CombineLD.getNode())
6335       return CombineLD;
6336   }
6337
6338   return SDValue();
6339 }
6340
6341 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6342   EVT VT = N->getValueType(0);
6343   return CombineConsecutiveLoads(N, VT);
6344 }
6345
6346 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6347 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6348 /// destination element value type.
6349 SDValue DAGCombiner::
6350 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6351   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6352
6353   // If this is already the right type, we're done.
6354   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6355
6356   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6357   unsigned DstBitSize = DstEltVT.getSizeInBits();
6358
6359   // If this is a conversion of N elements of one type to N elements of another
6360   // type, convert each element.  This handles FP<->INT cases.
6361   if (SrcBitSize == DstBitSize) {
6362     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6363                               BV->getValueType(0).getVectorNumElements());
6364
6365     // Due to the FP element handling below calling this routine recursively,
6366     // we can end up with a scalar-to-vector node here.
6367     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6368       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6369                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6370                                      DstEltVT, BV->getOperand(0)));
6371
6372     SmallVector<SDValue, 8> Ops;
6373     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6374       SDValue Op = BV->getOperand(i);
6375       // If the vector element type is not legal, the BUILD_VECTOR operands
6376       // are promoted and implicitly truncated.  Make that explicit here.
6377       if (Op.getValueType() != SrcEltVT)
6378         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6379       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6380                                 DstEltVT, Op));
6381       AddToWorkList(Ops.back().getNode());
6382     }
6383     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6384   }
6385
6386   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6387   // handle annoying details of growing/shrinking FP values, we convert them to
6388   // int first.
6389   if (SrcEltVT.isFloatingPoint()) {
6390     // Convert the input float vector to a int vector where the elements are the
6391     // same sizes.
6392     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6393     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6394     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6395     SrcEltVT = IntVT;
6396   }
6397
6398   // Now we know the input is an integer vector.  If the output is a FP type,
6399   // convert to integer first, then to FP of the right size.
6400   if (DstEltVT.isFloatingPoint()) {
6401     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6402     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6403     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6404
6405     // Next, convert to FP elements of the same size.
6406     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6407   }
6408
6409   // Okay, we know the src/dst types are both integers of differing types.
6410   // Handling growing first.
6411   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6412   if (SrcBitSize < DstBitSize) {
6413     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6414
6415     SmallVector<SDValue, 8> Ops;
6416     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6417          i += NumInputsPerOutput) {
6418       bool isLE = TLI.isLittleEndian();
6419       APInt NewBits = APInt(DstBitSize, 0);
6420       bool EltIsUndef = true;
6421       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6422         // Shift the previously computed bits over.
6423         NewBits <<= SrcBitSize;
6424         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6425         if (Op.getOpcode() == ISD::UNDEF) continue;
6426         EltIsUndef = false;
6427
6428         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6429                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6430       }
6431
6432       if (EltIsUndef)
6433         Ops.push_back(DAG.getUNDEF(DstEltVT));
6434       else
6435         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6436     }
6437
6438     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6439     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6440   }
6441
6442   // Finally, this must be the case where we are shrinking elements: each input
6443   // turns into multiple outputs.
6444   bool isS2V = ISD::isScalarToVector(BV);
6445   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6446   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6447                             NumOutputsPerInput*BV->getNumOperands());
6448   SmallVector<SDValue, 8> Ops;
6449
6450   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6451     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6452       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6453         Ops.push_back(DAG.getUNDEF(DstEltVT));
6454       continue;
6455     }
6456
6457     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6458                   getAPIntValue().zextOrTrunc(SrcBitSize);
6459
6460     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6461       APInt ThisVal = OpVal.trunc(DstBitSize);
6462       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6463       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6464         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6465         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6466                            Ops[0]);
6467       OpVal = OpVal.lshr(DstBitSize);
6468     }
6469
6470     // For big endian targets, swap the order of the pieces of each element.
6471     if (TLI.isBigEndian())
6472       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6473   }
6474
6475   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6476 }
6477
6478 SDValue DAGCombiner::visitFADD(SDNode *N) {
6479   SDValue N0 = N->getOperand(0);
6480   SDValue N1 = N->getOperand(1);
6481   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6482   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6483   EVT VT = N->getValueType(0);
6484
6485   // fold vector ops
6486   if (VT.isVector()) {
6487     SDValue FoldedVOp = SimplifyVBinOp(N);
6488     if (FoldedVOp.getNode()) return FoldedVOp;
6489   }
6490
6491   // fold (fadd c1, c2) -> c1 + c2
6492   if (N0CFP && N1CFP)
6493     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6494   // canonicalize constant to RHS
6495   if (N0CFP && !N1CFP)
6496     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6497   // fold (fadd A, 0) -> A
6498   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6499       N1CFP->getValueAPF().isZero())
6500     return N0;
6501   // fold (fadd A, (fneg B)) -> (fsub A, B)
6502   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6503     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6504     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6505                        GetNegatedExpression(N1, DAG, LegalOperations));
6506   // fold (fadd (fneg A), B) -> (fsub B, A)
6507   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6508     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6509     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6510                        GetNegatedExpression(N0, DAG, LegalOperations));
6511
6512   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6513   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6514       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6515       isa<ConstantFPSDNode>(N0.getOperand(1)))
6516     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6517                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6518                                    N0.getOperand(1), N1));
6519
6520   // No FP constant should be created after legalization as Instruction
6521   // Selection pass has hard time in dealing with FP constant.
6522   //
6523   // We don't need test this condition for transformation like following, as
6524   // the DAG being transformed implies it is legal to take FP constant as
6525   // operand.
6526   //
6527   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6528   //
6529   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6530
6531   // If allow, fold (fadd (fneg x), x) -> 0.0
6532   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6533       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6534     return DAG.getConstantFP(0.0, VT);
6535
6536     // If allow, fold (fadd x, (fneg x)) -> 0.0
6537   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6538       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6539     return DAG.getConstantFP(0.0, VT);
6540
6541   // In unsafe math mode, we can fold chains of FADD's of the same value
6542   // into multiplications.  This transform is not safe in general because
6543   // we are reducing the number of rounding steps.
6544   if (DAG.getTarget().Options.UnsafeFPMath &&
6545       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6546       !N0CFP && !N1CFP) {
6547     if (N0.getOpcode() == ISD::FMUL) {
6548       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6549       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6550
6551       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6552       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6553         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6554                                      SDValue(CFP00, 0),
6555                                      DAG.getConstantFP(1.0, VT));
6556         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6557                            N1, NewCFP);
6558       }
6559
6560       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6561       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6562         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6563                                      SDValue(CFP01, 0),
6564                                      DAG.getConstantFP(1.0, VT));
6565         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6566                            N1, NewCFP);
6567       }
6568
6569       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6570       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6571           N1.getOperand(0) == N1.getOperand(1) &&
6572           N0.getOperand(1) == N1.getOperand(0)) {
6573         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6574                                      SDValue(CFP00, 0),
6575                                      DAG.getConstantFP(2.0, VT));
6576         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6577                            N0.getOperand(1), NewCFP);
6578       }
6579
6580       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6581       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6582           N1.getOperand(0) == N1.getOperand(1) &&
6583           N0.getOperand(0) == N1.getOperand(0)) {
6584         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6585                                      SDValue(CFP01, 0),
6586                                      DAG.getConstantFP(2.0, VT));
6587         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6588                            N0.getOperand(0), NewCFP);
6589       }
6590     }
6591
6592     if (N1.getOpcode() == ISD::FMUL) {
6593       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6594       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6595
6596       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6597       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6598         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6599                                      SDValue(CFP10, 0),
6600                                      DAG.getConstantFP(1.0, VT));
6601         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6602                            N0, NewCFP);
6603       }
6604
6605       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6606       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6607         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6608                                      SDValue(CFP11, 0),
6609                                      DAG.getConstantFP(1.0, VT));
6610         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6611                            N0, NewCFP);
6612       }
6613
6614
6615       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6616       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6617           N0.getOperand(0) == N0.getOperand(1) &&
6618           N1.getOperand(1) == N0.getOperand(0)) {
6619         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6620                                      SDValue(CFP10, 0),
6621                                      DAG.getConstantFP(2.0, VT));
6622         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6623                            N1.getOperand(1), NewCFP);
6624       }
6625
6626       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6627       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6628           N0.getOperand(0) == N0.getOperand(1) &&
6629           N1.getOperand(0) == N0.getOperand(0)) {
6630         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6631                                      SDValue(CFP11, 0),
6632                                      DAG.getConstantFP(2.0, VT));
6633         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6634                            N1.getOperand(0), NewCFP);
6635       }
6636     }
6637
6638     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6639       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6640       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6641       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6642           (N0.getOperand(0) == N1))
6643         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6644                            N1, DAG.getConstantFP(3.0, VT));
6645     }
6646
6647     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6648       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6649       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6650       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6651           N1.getOperand(0) == N0)
6652         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6653                            N0, DAG.getConstantFP(3.0, VT));
6654     }
6655
6656     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6657     if (AllowNewFpConst &&
6658         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6659         N0.getOperand(0) == N0.getOperand(1) &&
6660         N1.getOperand(0) == N1.getOperand(1) &&
6661         N0.getOperand(0) == N1.getOperand(0))
6662       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6663                          N0.getOperand(0),
6664                          DAG.getConstantFP(4.0, VT));
6665   }
6666
6667   // FADD -> FMA combines:
6668   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6669        DAG.getTarget().Options.UnsafeFPMath) &&
6670       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6671       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6672
6673     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6674     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6675       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6676                          N0.getOperand(0), N0.getOperand(1), N1);
6677
6678     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6679     // Note: Commutes FADD operands.
6680     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6681       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6682                          N1.getOperand(0), N1.getOperand(1), N0);
6683   }
6684
6685   return SDValue();
6686 }
6687
6688 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6689   SDValue N0 = N->getOperand(0);
6690   SDValue N1 = N->getOperand(1);
6691   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6692   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6693   EVT VT = N->getValueType(0);
6694   SDLoc dl(N);
6695
6696   // fold vector ops
6697   if (VT.isVector()) {
6698     SDValue FoldedVOp = SimplifyVBinOp(N);
6699     if (FoldedVOp.getNode()) return FoldedVOp;
6700   }
6701
6702   // fold (fsub c1, c2) -> c1-c2
6703   if (N0CFP && N1CFP)
6704     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6705   // fold (fsub A, 0) -> A
6706   if (DAG.getTarget().Options.UnsafeFPMath &&
6707       N1CFP && N1CFP->getValueAPF().isZero())
6708     return N0;
6709   // fold (fsub 0, B) -> -B
6710   if (DAG.getTarget().Options.UnsafeFPMath &&
6711       N0CFP && N0CFP->getValueAPF().isZero()) {
6712     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6713       return GetNegatedExpression(N1, DAG, LegalOperations);
6714     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6715       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6716   }
6717   // fold (fsub A, (fneg B)) -> (fadd A, B)
6718   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6719     return DAG.getNode(ISD::FADD, dl, VT, N0,
6720                        GetNegatedExpression(N1, DAG, LegalOperations));
6721
6722   // If 'unsafe math' is enabled, fold
6723   //    (fsub x, x) -> 0.0 &
6724   //    (fsub x, (fadd x, y)) -> (fneg y) &
6725   //    (fsub x, (fadd y, x)) -> (fneg y)
6726   if (DAG.getTarget().Options.UnsafeFPMath) {
6727     if (N0 == N1)
6728       return DAG.getConstantFP(0.0f, VT);
6729
6730     if (N1.getOpcode() == ISD::FADD) {
6731       SDValue N10 = N1->getOperand(0);
6732       SDValue N11 = N1->getOperand(1);
6733
6734       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6735                                           &DAG.getTarget().Options))
6736         return GetNegatedExpression(N11, DAG, LegalOperations);
6737
6738       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6739                                           &DAG.getTarget().Options))
6740         return GetNegatedExpression(N10, DAG, LegalOperations);
6741     }
6742   }
6743
6744   // FSUB -> FMA combines:
6745   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6746        DAG.getTarget().Options.UnsafeFPMath) &&
6747       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6748       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6749
6750     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6751     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6752       return DAG.getNode(ISD::FMA, dl, VT,
6753                          N0.getOperand(0), N0.getOperand(1),
6754                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6755
6756     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6757     // Note: Commutes FSUB operands.
6758     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6759       return DAG.getNode(ISD::FMA, dl, VT,
6760                          DAG.getNode(ISD::FNEG, dl, VT,
6761                          N1.getOperand(0)),
6762                          N1.getOperand(1), N0);
6763
6764     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6765     if (N0.getOpcode() == ISD::FNEG &&
6766         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6767         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6768       SDValue N00 = N0.getOperand(0).getOperand(0);
6769       SDValue N01 = N0.getOperand(0).getOperand(1);
6770       return DAG.getNode(ISD::FMA, dl, VT,
6771                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6772                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6773     }
6774   }
6775
6776   return SDValue();
6777 }
6778
6779 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6780   SDValue N0 = N->getOperand(0);
6781   SDValue N1 = N->getOperand(1);
6782   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6783   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6784   EVT VT = N->getValueType(0);
6785   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6786
6787   // fold vector ops
6788   if (VT.isVector()) {
6789     SDValue FoldedVOp = SimplifyVBinOp(N);
6790     if (FoldedVOp.getNode()) return FoldedVOp;
6791   }
6792
6793   // fold (fmul c1, c2) -> c1*c2
6794   if (N0CFP && N1CFP)
6795     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6796   // canonicalize constant to RHS
6797   if (N0CFP && !N1CFP)
6798     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6799   // fold (fmul A, 0) -> 0
6800   if (DAG.getTarget().Options.UnsafeFPMath &&
6801       N1CFP && N1CFP->getValueAPF().isZero())
6802     return N1;
6803   // fold (fmul A, 0) -> 0, vector edition.
6804   if (DAG.getTarget().Options.UnsafeFPMath &&
6805       ISD::isBuildVectorAllZeros(N1.getNode()))
6806     return N1;
6807   // fold (fmul A, 1.0) -> A
6808   if (N1CFP && N1CFP->isExactlyValue(1.0))
6809     return N0;
6810   // fold (fmul X, 2.0) -> (fadd X, X)
6811   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6812     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6813   // fold (fmul X, -1.0) -> (fneg X)
6814   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6815     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6816       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6817
6818   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6819   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6820                                        &DAG.getTarget().Options)) {
6821     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6822                                          &DAG.getTarget().Options)) {
6823       // Both can be negated for free, check to see if at least one is cheaper
6824       // negated.
6825       if (LHSNeg == 2 || RHSNeg == 2)
6826         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6827                            GetNegatedExpression(N0, DAG, LegalOperations),
6828                            GetNegatedExpression(N1, DAG, LegalOperations));
6829     }
6830   }
6831
6832   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6833   if (DAG.getTarget().Options.UnsafeFPMath &&
6834       N1CFP && N0.getOpcode() == ISD::FMUL &&
6835       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6836     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6837                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6838                                    N0.getOperand(1), N1));
6839
6840   return SDValue();
6841 }
6842
6843 SDValue DAGCombiner::visitFMA(SDNode *N) {
6844   SDValue N0 = N->getOperand(0);
6845   SDValue N1 = N->getOperand(1);
6846   SDValue N2 = N->getOperand(2);
6847   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6848   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6849   EVT VT = N->getValueType(0);
6850   SDLoc dl(N);
6851
6852   if (DAG.getTarget().Options.UnsafeFPMath) {
6853     if (N0CFP && N0CFP->isZero())
6854       return N2;
6855     if (N1CFP && N1CFP->isZero())
6856       return N2;
6857   }
6858   if (N0CFP && N0CFP->isExactlyValue(1.0))
6859     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6860   if (N1CFP && N1CFP->isExactlyValue(1.0))
6861     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6862
6863   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6864   if (N0CFP && !N1CFP)
6865     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6866
6867   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6868   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6869       N2.getOpcode() == ISD::FMUL &&
6870       N0 == N2.getOperand(0) &&
6871       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6872     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6873                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6874   }
6875
6876
6877   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6878   if (DAG.getTarget().Options.UnsafeFPMath &&
6879       N0.getOpcode() == ISD::FMUL && N1CFP &&
6880       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6881     return DAG.getNode(ISD::FMA, dl, VT,
6882                        N0.getOperand(0),
6883                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6884                        N2);
6885   }
6886
6887   // (fma x, 1, y) -> (fadd x, y)
6888   // (fma x, -1, y) -> (fadd (fneg x), y)
6889   if (N1CFP) {
6890     if (N1CFP->isExactlyValue(1.0))
6891       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6892
6893     if (N1CFP->isExactlyValue(-1.0) &&
6894         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6895       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6896       AddToWorkList(RHSNeg.getNode());
6897       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6898     }
6899   }
6900
6901   // (fma x, c, x) -> (fmul x, (c+1))
6902   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6903     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6904                        DAG.getNode(ISD::FADD, dl, VT,
6905                                    N1, DAG.getConstantFP(1.0, VT)));
6906
6907   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6908   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6909       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6910     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6911                        DAG.getNode(ISD::FADD, dl, VT,
6912                                    N1, DAG.getConstantFP(-1.0, VT)));
6913
6914
6915   return SDValue();
6916 }
6917
6918 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6919   SDValue N0 = N->getOperand(0);
6920   SDValue N1 = N->getOperand(1);
6921   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6922   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6923   EVT VT = N->getValueType(0);
6924   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6925
6926   // fold vector ops
6927   if (VT.isVector()) {
6928     SDValue FoldedVOp = SimplifyVBinOp(N);
6929     if (FoldedVOp.getNode()) return FoldedVOp;
6930   }
6931
6932   // fold (fdiv c1, c2) -> c1/c2
6933   if (N0CFP && N1CFP)
6934     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6935
6936   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6937   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6938     // Compute the reciprocal 1.0 / c2.
6939     APFloat N1APF = N1CFP->getValueAPF();
6940     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6941     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6942     // Only do the transform if the reciprocal is a legal fp immediate that
6943     // isn't too nasty (eg NaN, denormal, ...).
6944     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6945         (!LegalOperations ||
6946          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6947          // backend)... we should handle this gracefully after Legalize.
6948          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6949          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6950          TLI.isFPImmLegal(Recip, VT)))
6951       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6952                          DAG.getConstantFP(Recip, VT));
6953   }
6954
6955   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6956   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6957                                        &DAG.getTarget().Options)) {
6958     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6959                                          &DAG.getTarget().Options)) {
6960       // Both can be negated for free, check to see if at least one is cheaper
6961       // negated.
6962       if (LHSNeg == 2 || RHSNeg == 2)
6963         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6964                            GetNegatedExpression(N0, DAG, LegalOperations),
6965                            GetNegatedExpression(N1, DAG, LegalOperations));
6966     }
6967   }
6968
6969   return SDValue();
6970 }
6971
6972 SDValue DAGCombiner::visitFREM(SDNode *N) {
6973   SDValue N0 = N->getOperand(0);
6974   SDValue N1 = N->getOperand(1);
6975   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6976   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6977   EVT VT = N->getValueType(0);
6978
6979   // fold (frem c1, c2) -> fmod(c1,c2)
6980   if (N0CFP && N1CFP)
6981     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6982
6983   return SDValue();
6984 }
6985
6986 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6987   SDValue N0 = N->getOperand(0);
6988   SDValue N1 = N->getOperand(1);
6989   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6990   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6991   EVT VT = N->getValueType(0);
6992
6993   if (N0CFP && N1CFP)  // Constant fold
6994     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6995
6996   if (N1CFP) {
6997     const APFloat& V = N1CFP->getValueAPF();
6998     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6999     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7000     if (!V.isNegative()) {
7001       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7002         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7003     } else {
7004       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7005         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7006                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7007     }
7008   }
7009
7010   // copysign(fabs(x), y) -> copysign(x, y)
7011   // copysign(fneg(x), y) -> copysign(x, y)
7012   // copysign(copysign(x,z), y) -> copysign(x, y)
7013   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7014       N0.getOpcode() == ISD::FCOPYSIGN)
7015     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7016                        N0.getOperand(0), N1);
7017
7018   // copysign(x, abs(y)) -> abs(x)
7019   if (N1.getOpcode() == ISD::FABS)
7020     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7021
7022   // copysign(x, copysign(y,z)) -> copysign(x, z)
7023   if (N1.getOpcode() == ISD::FCOPYSIGN)
7024     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7025                        N0, N1.getOperand(1));
7026
7027   // copysign(x, fp_extend(y)) -> copysign(x, y)
7028   // copysign(x, fp_round(y)) -> copysign(x, y)
7029   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7030     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7031                        N0, N1.getOperand(0));
7032
7033   return SDValue();
7034 }
7035
7036 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7037   SDValue N0 = N->getOperand(0);
7038   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7039   EVT VT = N->getValueType(0);
7040   EVT OpVT = N0.getValueType();
7041
7042   // fold (sint_to_fp c1) -> c1fp
7043   if (N0C &&
7044       // ...but only if the target supports immediate floating-point values
7045       (!LegalOperations ||
7046        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7047     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7048
7049   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7050   // but UINT_TO_FP is legal on this target, try to convert.
7051   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7052       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7053     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7054     if (DAG.SignBitIsZero(N0))
7055       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7056   }
7057
7058   // The next optimizations are desirable only if SELECT_CC can be lowered.
7059   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7060     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7061     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7062         !VT.isVector() &&
7063         (!LegalOperations ||
7064          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7065       SDValue Ops[] =
7066         { N0.getOperand(0), N0.getOperand(1),
7067           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7068           N0.getOperand(2) };
7069       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7070     }
7071
7072     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7073     //      (select_cc x, y, 1.0, 0.0,, cc)
7074     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7075         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7076         (!LegalOperations ||
7077          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7078       SDValue Ops[] =
7079         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7080           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7081           N0.getOperand(0).getOperand(2) };
7082       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7083     }
7084   }
7085
7086   return SDValue();
7087 }
7088
7089 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7090   SDValue N0 = N->getOperand(0);
7091   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7092   EVT VT = N->getValueType(0);
7093   EVT OpVT = N0.getValueType();
7094
7095   // fold (uint_to_fp c1) -> c1fp
7096   if (N0C &&
7097       // ...but only if the target supports immediate floating-point values
7098       (!LegalOperations ||
7099        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7100     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7101
7102   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7103   // but SINT_TO_FP is legal on this target, try to convert.
7104   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7105       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7106     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7107     if (DAG.SignBitIsZero(N0))
7108       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7109   }
7110
7111   // The next optimizations are desirable only if SELECT_CC can be lowered.
7112   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7113     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7114
7115     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7116         (!LegalOperations ||
7117          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7118       SDValue Ops[] =
7119         { N0.getOperand(0), N0.getOperand(1),
7120           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7121           N0.getOperand(2) };
7122       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7123     }
7124   }
7125
7126   return SDValue();
7127 }
7128
7129 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7130   SDValue N0 = N->getOperand(0);
7131   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7132   EVT VT = N->getValueType(0);
7133
7134   // fold (fp_to_sint c1fp) -> c1
7135   if (N0CFP)
7136     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7137
7138   return SDValue();
7139 }
7140
7141 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7142   SDValue N0 = N->getOperand(0);
7143   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7144   EVT VT = N->getValueType(0);
7145
7146   // fold (fp_to_uint c1fp) -> c1
7147   if (N0CFP)
7148     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7149
7150   return SDValue();
7151 }
7152
7153 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7154   SDValue N0 = N->getOperand(0);
7155   SDValue N1 = N->getOperand(1);
7156   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7157   EVT VT = N->getValueType(0);
7158
7159   // fold (fp_round c1fp) -> c1fp
7160   if (N0CFP)
7161     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7162
7163   // fold (fp_round (fp_extend x)) -> x
7164   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7165     return N0.getOperand(0);
7166
7167   // fold (fp_round (fp_round x)) -> (fp_round x)
7168   if (N0.getOpcode() == ISD::FP_ROUND) {
7169     // This is a value preserving truncation if both round's are.
7170     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7171                    N0.getNode()->getConstantOperandVal(1) == 1;
7172     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7173                        DAG.getIntPtrConstant(IsTrunc));
7174   }
7175
7176   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7177   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7178     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7179                               N0.getOperand(0), N1);
7180     AddToWorkList(Tmp.getNode());
7181     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7182                        Tmp, N0.getOperand(1));
7183   }
7184
7185   return SDValue();
7186 }
7187
7188 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7189   SDValue N0 = N->getOperand(0);
7190   EVT VT = N->getValueType(0);
7191   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7192   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7193
7194   // fold (fp_round_inreg c1fp) -> c1fp
7195   if (N0CFP && isTypeLegal(EVT)) {
7196     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7197     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7198   }
7199
7200   return SDValue();
7201 }
7202
7203 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7204   SDValue N0 = N->getOperand(0);
7205   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7206   EVT VT = N->getValueType(0);
7207
7208   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7209   if (N->hasOneUse() &&
7210       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7211     return SDValue();
7212
7213   // fold (fp_extend c1fp) -> c1fp
7214   if (N0CFP)
7215     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7216
7217   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7218   // value of X.
7219   if (N0.getOpcode() == ISD::FP_ROUND
7220       && N0.getNode()->getConstantOperandVal(1) == 1) {
7221     SDValue In = N0.getOperand(0);
7222     if (In.getValueType() == VT) return In;
7223     if (VT.bitsLT(In.getValueType()))
7224       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7225                          In, N0.getOperand(1));
7226     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7227   }
7228
7229   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7230   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7231       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7232        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7233     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7234     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7235                                      LN0->getChain(),
7236                                      LN0->getBasePtr(), N0.getValueType(),
7237                                      LN0->getMemOperand());
7238     CombineTo(N, ExtLoad);
7239     CombineTo(N0.getNode(),
7240               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7241                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7242               ExtLoad.getValue(1));
7243     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7244   }
7245
7246   return SDValue();
7247 }
7248
7249 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7250   SDValue N0 = N->getOperand(0);
7251   EVT VT = N->getValueType(0);
7252
7253   if (VT.isVector()) {
7254     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7255     if (FoldedVOp.getNode()) return FoldedVOp;
7256   }
7257
7258   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7259                          &DAG.getTarget().Options))
7260     return GetNegatedExpression(N0, DAG, LegalOperations);
7261
7262   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7263   // constant pool values.
7264   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7265       !VT.isVector() &&
7266       N0.getNode()->hasOneUse() &&
7267       N0.getOperand(0).getValueType().isInteger()) {
7268     SDValue Int = N0.getOperand(0);
7269     EVT IntVT = Int.getValueType();
7270     if (IntVT.isInteger() && !IntVT.isVector()) {
7271       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7272               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7273       AddToWorkList(Int.getNode());
7274       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7275                          VT, Int);
7276     }
7277   }
7278
7279   // (fneg (fmul c, x)) -> (fmul -c, x)
7280   if (N0.getOpcode() == ISD::FMUL) {
7281     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7282     if (CFP1) {
7283       APFloat CVal = CFP1->getValueAPF();
7284       CVal.changeSign();
7285       if (Level >= AfterLegalizeDAG &&
7286           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7287            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7288         return DAG.getNode(
7289             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7290             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7291     }
7292   }
7293
7294   return SDValue();
7295 }
7296
7297 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7298   SDValue N0 = N->getOperand(0);
7299   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7300   EVT VT = N->getValueType(0);
7301
7302   // fold (fceil c1) -> fceil(c1)
7303   if (N0CFP)
7304     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7305
7306   return SDValue();
7307 }
7308
7309 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7310   SDValue N0 = N->getOperand(0);
7311   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7312   EVT VT = N->getValueType(0);
7313
7314   // fold (ftrunc c1) -> ftrunc(c1)
7315   if (N0CFP)
7316     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7317
7318   return SDValue();
7319 }
7320
7321 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7322   SDValue N0 = N->getOperand(0);
7323   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7324   EVT VT = N->getValueType(0);
7325
7326   // fold (ffloor c1) -> ffloor(c1)
7327   if (N0CFP)
7328     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7329
7330   return SDValue();
7331 }
7332
7333 SDValue DAGCombiner::visitFABS(SDNode *N) {
7334   SDValue N0 = N->getOperand(0);
7335   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7336   EVT VT = N->getValueType(0);
7337
7338   if (VT.isVector()) {
7339     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7340     if (FoldedVOp.getNode()) return FoldedVOp;
7341   }
7342
7343   // fold (fabs c1) -> fabs(c1)
7344   if (N0CFP)
7345     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7346   // fold (fabs (fabs x)) -> (fabs x)
7347   if (N0.getOpcode() == ISD::FABS)
7348     return N->getOperand(0);
7349   // fold (fabs (fneg x)) -> (fabs x)
7350   // fold (fabs (fcopysign x, y)) -> (fabs x)
7351   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7352     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7353
7354   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7355   // constant pool values.
7356   if (!TLI.isFAbsFree(VT) &&
7357       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7358       N0.getOperand(0).getValueType().isInteger() &&
7359       !N0.getOperand(0).getValueType().isVector()) {
7360     SDValue Int = N0.getOperand(0);
7361     EVT IntVT = Int.getValueType();
7362     if (IntVT.isInteger() && !IntVT.isVector()) {
7363       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7364              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7365       AddToWorkList(Int.getNode());
7366       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7367                          N->getValueType(0), Int);
7368     }
7369   }
7370
7371   return SDValue();
7372 }
7373
7374 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7375   SDValue Chain = N->getOperand(0);
7376   SDValue N1 = N->getOperand(1);
7377   SDValue N2 = N->getOperand(2);
7378
7379   // If N is a constant we could fold this into a fallthrough or unconditional
7380   // branch. However that doesn't happen very often in normal code, because
7381   // Instcombine/SimplifyCFG should have handled the available opportunities.
7382   // If we did this folding here, it would be necessary to update the
7383   // MachineBasicBlock CFG, which is awkward.
7384
7385   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7386   // on the target.
7387   if (N1.getOpcode() == ISD::SETCC &&
7388       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7389                                    N1.getOperand(0).getValueType())) {
7390     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7391                        Chain, N1.getOperand(2),
7392                        N1.getOperand(0), N1.getOperand(1), N2);
7393   }
7394
7395   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7396       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7397        (N1.getOperand(0).hasOneUse() &&
7398         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7399     SDNode *Trunc = nullptr;
7400     if (N1.getOpcode() == ISD::TRUNCATE) {
7401       // Look pass the truncate.
7402       Trunc = N1.getNode();
7403       N1 = N1.getOperand(0);
7404     }
7405
7406     // Match this pattern so that we can generate simpler code:
7407     //
7408     //   %a = ...
7409     //   %b = and i32 %a, 2
7410     //   %c = srl i32 %b, 1
7411     //   brcond i32 %c ...
7412     //
7413     // into
7414     //
7415     //   %a = ...
7416     //   %b = and i32 %a, 2
7417     //   %c = setcc eq %b, 0
7418     //   brcond %c ...
7419     //
7420     // This applies only when the AND constant value has one bit set and the
7421     // SRL constant is equal to the log2 of the AND constant. The back-end is
7422     // smart enough to convert the result into a TEST/JMP sequence.
7423     SDValue Op0 = N1.getOperand(0);
7424     SDValue Op1 = N1.getOperand(1);
7425
7426     if (Op0.getOpcode() == ISD::AND &&
7427         Op1.getOpcode() == ISD::Constant) {
7428       SDValue AndOp1 = Op0.getOperand(1);
7429
7430       if (AndOp1.getOpcode() == ISD::Constant) {
7431         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7432
7433         if (AndConst.isPowerOf2() &&
7434             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7435           SDValue SetCC =
7436             DAG.getSetCC(SDLoc(N),
7437                          getSetCCResultType(Op0.getValueType()),
7438                          Op0, DAG.getConstant(0, Op0.getValueType()),
7439                          ISD::SETNE);
7440
7441           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7442                                           MVT::Other, Chain, SetCC, N2);
7443           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7444           // will convert it back to (X & C1) >> C2.
7445           CombineTo(N, NewBRCond, false);
7446           // Truncate is dead.
7447           if (Trunc) {
7448             removeFromWorkList(Trunc);
7449             DAG.DeleteNode(Trunc);
7450           }
7451           // Replace the uses of SRL with SETCC
7452           WorkListRemover DeadNodes(*this);
7453           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7454           removeFromWorkList(N1.getNode());
7455           DAG.DeleteNode(N1.getNode());
7456           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7457         }
7458       }
7459     }
7460
7461     if (Trunc)
7462       // Restore N1 if the above transformation doesn't match.
7463       N1 = N->getOperand(1);
7464   }
7465
7466   // Transform br(xor(x, y)) -> br(x != y)
7467   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7468   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7469     SDNode *TheXor = N1.getNode();
7470     SDValue Op0 = TheXor->getOperand(0);
7471     SDValue Op1 = TheXor->getOperand(1);
7472     if (Op0.getOpcode() == Op1.getOpcode()) {
7473       // Avoid missing important xor optimizations.
7474       SDValue Tmp = visitXOR(TheXor);
7475       if (Tmp.getNode()) {
7476         if (Tmp.getNode() != TheXor) {
7477           DEBUG(dbgs() << "\nReplacing.8 ";
7478                 TheXor->dump(&DAG);
7479                 dbgs() << "\nWith: ";
7480                 Tmp.getNode()->dump(&DAG);
7481                 dbgs() << '\n');
7482           WorkListRemover DeadNodes(*this);
7483           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7484           removeFromWorkList(TheXor);
7485           DAG.DeleteNode(TheXor);
7486           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7487                              MVT::Other, Chain, Tmp, N2);
7488         }
7489
7490         // visitXOR has changed XOR's operands or replaced the XOR completely,
7491         // bail out.
7492         return SDValue(N, 0);
7493       }
7494     }
7495
7496     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7497       bool Equal = false;
7498       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7499         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7500             Op0.getOpcode() == ISD::XOR) {
7501           TheXor = Op0.getNode();
7502           Equal = true;
7503         }
7504
7505       EVT SetCCVT = N1.getValueType();
7506       if (LegalTypes)
7507         SetCCVT = getSetCCResultType(SetCCVT);
7508       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7509                                    SetCCVT,
7510                                    Op0, Op1,
7511                                    Equal ? ISD::SETEQ : ISD::SETNE);
7512       // Replace the uses of XOR with SETCC
7513       WorkListRemover DeadNodes(*this);
7514       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7515       removeFromWorkList(N1.getNode());
7516       DAG.DeleteNode(N1.getNode());
7517       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7518                          MVT::Other, Chain, SetCC, N2);
7519     }
7520   }
7521
7522   return SDValue();
7523 }
7524
7525 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7526 //
7527 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7528   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7529   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7530
7531   // If N is a constant we could fold this into a fallthrough or unconditional
7532   // branch. However that doesn't happen very often in normal code, because
7533   // Instcombine/SimplifyCFG should have handled the available opportunities.
7534   // If we did this folding here, it would be necessary to update the
7535   // MachineBasicBlock CFG, which is awkward.
7536
7537   // Use SimplifySetCC to simplify SETCC's.
7538   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7539                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7540                                false);
7541   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7542
7543   // fold to a simpler setcc
7544   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7545     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7546                        N->getOperand(0), Simp.getOperand(2),
7547                        Simp.getOperand(0), Simp.getOperand(1),
7548                        N->getOperand(4));
7549
7550   return SDValue();
7551 }
7552
7553 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7554 /// uses N as its base pointer and that N may be folded in the load / store
7555 /// addressing mode.
7556 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7557                                     SelectionDAG &DAG,
7558                                     const TargetLowering &TLI) {
7559   EVT VT;
7560   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7561     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7562       return false;
7563     VT = Use->getValueType(0);
7564   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7565     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7566       return false;
7567     VT = ST->getValue().getValueType();
7568   } else
7569     return false;
7570
7571   TargetLowering::AddrMode AM;
7572   if (N->getOpcode() == ISD::ADD) {
7573     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7574     if (Offset)
7575       // [reg +/- imm]
7576       AM.BaseOffs = Offset->getSExtValue();
7577     else
7578       // [reg +/- reg]
7579       AM.Scale = 1;
7580   } else if (N->getOpcode() == ISD::SUB) {
7581     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7582     if (Offset)
7583       // [reg +/- imm]
7584       AM.BaseOffs = -Offset->getSExtValue();
7585     else
7586       // [reg +/- reg]
7587       AM.Scale = 1;
7588   } else
7589     return false;
7590
7591   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7592 }
7593
7594 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7595 /// pre-indexed load / store when the base pointer is an add or subtract
7596 /// and it has other uses besides the load / store. After the
7597 /// transformation, the new indexed load / store has effectively folded
7598 /// the add / subtract in and all of its other uses are redirected to the
7599 /// new load / store.
7600 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7601   if (Level < AfterLegalizeDAG)
7602     return false;
7603
7604   bool isLoad = true;
7605   SDValue Ptr;
7606   EVT VT;
7607   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7608     if (LD->isIndexed())
7609       return false;
7610     VT = LD->getMemoryVT();
7611     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7612         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7613       return false;
7614     Ptr = LD->getBasePtr();
7615   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7616     if (ST->isIndexed())
7617       return false;
7618     VT = ST->getMemoryVT();
7619     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7620         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7621       return false;
7622     Ptr = ST->getBasePtr();
7623     isLoad = false;
7624   } else {
7625     return false;
7626   }
7627
7628   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7629   // out.  There is no reason to make this a preinc/predec.
7630   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7631       Ptr.getNode()->hasOneUse())
7632     return false;
7633
7634   // Ask the target to do addressing mode selection.
7635   SDValue BasePtr;
7636   SDValue Offset;
7637   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7638   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7639     return false;
7640
7641   // Backends without true r+i pre-indexed forms may need to pass a
7642   // constant base with a variable offset so that constant coercion
7643   // will work with the patterns in canonical form.
7644   bool Swapped = false;
7645   if (isa<ConstantSDNode>(BasePtr)) {
7646     std::swap(BasePtr, Offset);
7647     Swapped = true;
7648   }
7649
7650   // Don't create a indexed load / store with zero offset.
7651   if (isa<ConstantSDNode>(Offset) &&
7652       cast<ConstantSDNode>(Offset)->isNullValue())
7653     return false;
7654
7655   // Try turning it into a pre-indexed load / store except when:
7656   // 1) The new base ptr is a frame index.
7657   // 2) If N is a store and the new base ptr is either the same as or is a
7658   //    predecessor of the value being stored.
7659   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7660   //    that would create a cycle.
7661   // 4) All uses are load / store ops that use it as old base ptr.
7662
7663   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7664   // (plus the implicit offset) to a register to preinc anyway.
7665   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7666     return false;
7667
7668   // Check #2.
7669   if (!isLoad) {
7670     SDValue Val = cast<StoreSDNode>(N)->getValue();
7671     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7672       return false;
7673   }
7674
7675   // If the offset is a constant, there may be other adds of constants that
7676   // can be folded with this one. We should do this to avoid having to keep
7677   // a copy of the original base pointer.
7678   SmallVector<SDNode *, 16> OtherUses;
7679   if (isa<ConstantSDNode>(Offset))
7680     for (SDNode *Use : BasePtr.getNode()->uses()) {
7681       if (Use == Ptr.getNode())
7682         continue;
7683
7684       if (Use->isPredecessorOf(N))
7685         continue;
7686
7687       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7688         OtherUses.clear();
7689         break;
7690       }
7691
7692       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7693       if (Op1.getNode() == BasePtr.getNode())
7694         std::swap(Op0, Op1);
7695       assert(Op0.getNode() == BasePtr.getNode() &&
7696              "Use of ADD/SUB but not an operand");
7697
7698       if (!isa<ConstantSDNode>(Op1)) {
7699         OtherUses.clear();
7700         break;
7701       }
7702
7703       // FIXME: In some cases, we can be smarter about this.
7704       if (Op1.getValueType() != Offset.getValueType()) {
7705         OtherUses.clear();
7706         break;
7707       }
7708
7709       OtherUses.push_back(Use);
7710     }
7711
7712   if (Swapped)
7713     std::swap(BasePtr, Offset);
7714
7715   // Now check for #3 and #4.
7716   bool RealUse = false;
7717
7718   // Caches for hasPredecessorHelper
7719   SmallPtrSet<const SDNode *, 32> Visited;
7720   SmallVector<const SDNode *, 16> Worklist;
7721
7722   for (SDNode *Use : Ptr.getNode()->uses()) {
7723     if (Use == N)
7724       continue;
7725     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7726       return false;
7727
7728     // If Ptr may be folded in addressing mode of other use, then it's
7729     // not profitable to do this transformation.
7730     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7731       RealUse = true;
7732   }
7733
7734   if (!RealUse)
7735     return false;
7736
7737   SDValue Result;
7738   if (isLoad)
7739     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7740                                 BasePtr, Offset, AM);
7741   else
7742     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7743                                  BasePtr, Offset, AM);
7744   ++PreIndexedNodes;
7745   ++NodesCombined;
7746   DEBUG(dbgs() << "\nReplacing.4 ";
7747         N->dump(&DAG);
7748         dbgs() << "\nWith: ";
7749         Result.getNode()->dump(&DAG);
7750         dbgs() << '\n');
7751   WorkListRemover DeadNodes(*this);
7752   if (isLoad) {
7753     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7754     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7755   } else {
7756     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7757   }
7758
7759   // Finally, since the node is now dead, remove it from the graph.
7760   DAG.DeleteNode(N);
7761
7762   if (Swapped)
7763     std::swap(BasePtr, Offset);
7764
7765   // Replace other uses of BasePtr that can be updated to use Ptr
7766   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7767     unsigned OffsetIdx = 1;
7768     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7769       OffsetIdx = 0;
7770     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7771            BasePtr.getNode() && "Expected BasePtr operand");
7772
7773     // We need to replace ptr0 in the following expression:
7774     //   x0 * offset0 + y0 * ptr0 = t0
7775     // knowing that
7776     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7777     //
7778     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7779     // indexed load/store and the expresion that needs to be re-written.
7780     //
7781     // Therefore, we have:
7782     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7783
7784     ConstantSDNode *CN =
7785       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7786     int X0, X1, Y0, Y1;
7787     APInt Offset0 = CN->getAPIntValue();
7788     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7789
7790     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7791     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7792     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7793     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7794
7795     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7796
7797     APInt CNV = Offset0;
7798     if (X0 < 0) CNV = -CNV;
7799     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7800     else CNV = CNV - Offset1;
7801
7802     // We can now generate the new expression.
7803     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7804     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7805
7806     SDValue NewUse = DAG.getNode(Opcode,
7807                                  SDLoc(OtherUses[i]),
7808                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7809     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7810     removeFromWorkList(OtherUses[i]);
7811     DAG.DeleteNode(OtherUses[i]);
7812   }
7813
7814   // Replace the uses of Ptr with uses of the updated base value.
7815   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7816   removeFromWorkList(Ptr.getNode());
7817   DAG.DeleteNode(Ptr.getNode());
7818
7819   return true;
7820 }
7821
7822 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7823 /// add / sub of the base pointer node into a post-indexed load / store.
7824 /// The transformation folded the add / subtract into the new indexed
7825 /// load / store effectively and all of its uses are redirected to the
7826 /// new load / store.
7827 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7828   if (Level < AfterLegalizeDAG)
7829     return false;
7830
7831   bool isLoad = true;
7832   SDValue Ptr;
7833   EVT VT;
7834   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7835     if (LD->isIndexed())
7836       return false;
7837     VT = LD->getMemoryVT();
7838     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7839         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7840       return false;
7841     Ptr = LD->getBasePtr();
7842   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7843     if (ST->isIndexed())
7844       return false;
7845     VT = ST->getMemoryVT();
7846     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7847         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7848       return false;
7849     Ptr = ST->getBasePtr();
7850     isLoad = false;
7851   } else {
7852     return false;
7853   }
7854
7855   if (Ptr.getNode()->hasOneUse())
7856     return false;
7857
7858   for (SDNode *Op : Ptr.getNode()->uses()) {
7859     if (Op == N ||
7860         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7861       continue;
7862
7863     SDValue BasePtr;
7864     SDValue Offset;
7865     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7866     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7867       // Don't create a indexed load / store with zero offset.
7868       if (isa<ConstantSDNode>(Offset) &&
7869           cast<ConstantSDNode>(Offset)->isNullValue())
7870         continue;
7871
7872       // Try turning it into a post-indexed load / store except when
7873       // 1) All uses are load / store ops that use it as base ptr (and
7874       //    it may be folded as addressing mmode).
7875       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7876       //    nor a successor of N. Otherwise, if Op is folded that would
7877       //    create a cycle.
7878
7879       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7880         continue;
7881
7882       // Check for #1.
7883       bool TryNext = false;
7884       for (SDNode *Use : BasePtr.getNode()->uses()) {
7885         if (Use == Ptr.getNode())
7886           continue;
7887
7888         // If all the uses are load / store addresses, then don't do the
7889         // transformation.
7890         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7891           bool RealUse = false;
7892           for (SDNode *UseUse : Use->uses()) {
7893             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7894               RealUse = true;
7895           }
7896
7897           if (!RealUse) {
7898             TryNext = true;
7899             break;
7900           }
7901         }
7902       }
7903
7904       if (TryNext)
7905         continue;
7906
7907       // Check for #2
7908       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7909         SDValue Result = isLoad
7910           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7911                                BasePtr, Offset, AM)
7912           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7913                                 BasePtr, Offset, AM);
7914         ++PostIndexedNodes;
7915         ++NodesCombined;
7916         DEBUG(dbgs() << "\nReplacing.5 ";
7917               N->dump(&DAG);
7918               dbgs() << "\nWith: ";
7919               Result.getNode()->dump(&DAG);
7920               dbgs() << '\n');
7921         WorkListRemover DeadNodes(*this);
7922         if (isLoad) {
7923           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7924           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7925         } else {
7926           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7927         }
7928
7929         // Finally, since the node is now dead, remove it from the graph.
7930         DAG.DeleteNode(N);
7931
7932         // Replace the uses of Use with uses of the updated base value.
7933         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7934                                       Result.getValue(isLoad ? 1 : 0));
7935         removeFromWorkList(Op);
7936         DAG.DeleteNode(Op);
7937         return true;
7938       }
7939     }
7940   }
7941
7942   return false;
7943 }
7944
7945 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7946   LoadSDNode *LD  = cast<LoadSDNode>(N);
7947   SDValue Chain = LD->getChain();
7948   SDValue Ptr   = LD->getBasePtr();
7949
7950   // If load is not volatile and there are no uses of the loaded value (and
7951   // the updated indexed value in case of indexed loads), change uses of the
7952   // chain value into uses of the chain input (i.e. delete the dead load).
7953   if (!LD->isVolatile()) {
7954     if (N->getValueType(1) == MVT::Other) {
7955       // Unindexed loads.
7956       if (!N->hasAnyUseOfValue(0)) {
7957         // It's not safe to use the two value CombineTo variant here. e.g.
7958         // v1, chain2 = load chain1, loc
7959         // v2, chain3 = load chain2, loc
7960         // v3         = add v2, c
7961         // Now we replace use of chain2 with chain1.  This makes the second load
7962         // isomorphic to the one we are deleting, and thus makes this load live.
7963         DEBUG(dbgs() << "\nReplacing.6 ";
7964               N->dump(&DAG);
7965               dbgs() << "\nWith chain: ";
7966               Chain.getNode()->dump(&DAG);
7967               dbgs() << "\n");
7968         WorkListRemover DeadNodes(*this);
7969         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7970
7971         if (N->use_empty()) {
7972           removeFromWorkList(N);
7973           DAG.DeleteNode(N);
7974         }
7975
7976         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7977       }
7978     } else {
7979       // Indexed loads.
7980       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7981       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7982         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7983         DEBUG(dbgs() << "\nReplacing.7 ";
7984               N->dump(&DAG);
7985               dbgs() << "\nWith: ";
7986               Undef.getNode()->dump(&DAG);
7987               dbgs() << " and 2 other values\n");
7988         WorkListRemover DeadNodes(*this);
7989         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7990         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7991                                       DAG.getUNDEF(N->getValueType(1)));
7992         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7993         removeFromWorkList(N);
7994         DAG.DeleteNode(N);
7995         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7996       }
7997     }
7998   }
7999
8000   // If this load is directly stored, replace the load value with the stored
8001   // value.
8002   // TODO: Handle store large -> read small portion.
8003   // TODO: Handle TRUNCSTORE/LOADEXT
8004   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8005     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8006       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8007       if (PrevST->getBasePtr() == Ptr &&
8008           PrevST->getValue().getValueType() == N->getValueType(0))
8009       return CombineTo(N, Chain.getOperand(1), Chain);
8010     }
8011   }
8012
8013   // Try to infer better alignment information than the load already has.
8014   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8015     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8016       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8017         SDValue NewLoad =
8018                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8019                               LD->getValueType(0),
8020                               Chain, Ptr, LD->getPointerInfo(),
8021                               LD->getMemoryVT(),
8022                               LD->isVolatile(), LD->isNonTemporal(), Align,
8023                               LD->getTBAAInfo());
8024         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8025       }
8026     }
8027   }
8028
8029   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8030     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8031 #ifndef NDEBUG
8032   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8033       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8034     UseAA = false;
8035 #endif
8036   if (UseAA && LD->isUnindexed()) {
8037     // Walk up chain skipping non-aliasing memory nodes.
8038     SDValue BetterChain = FindBetterChain(N, Chain);
8039
8040     // If there is a better chain.
8041     if (Chain != BetterChain) {
8042       SDValue ReplLoad;
8043
8044       // Replace the chain to void dependency.
8045       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8046         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8047                                BetterChain, Ptr, LD->getMemOperand());
8048       } else {
8049         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8050                                   LD->getValueType(0),
8051                                   BetterChain, Ptr, LD->getMemoryVT(),
8052                                   LD->getMemOperand());
8053       }
8054
8055       // Create token factor to keep old chain connected.
8056       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8057                                   MVT::Other, Chain, ReplLoad.getValue(1));
8058
8059       // Make sure the new and old chains are cleaned up.
8060       AddToWorkList(Token.getNode());
8061
8062       // Replace uses with load result and token factor. Don't add users
8063       // to work list.
8064       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8065     }
8066   }
8067
8068   // Try transforming N to an indexed load.
8069   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8070     return SDValue(N, 0);
8071
8072   // Try to slice up N to more direct loads if the slices are mapped to
8073   // different register banks or pairing can take place.
8074   if (SliceUpLoad(N))
8075     return SDValue(N, 0);
8076
8077   return SDValue();
8078 }
8079
8080 namespace {
8081 /// \brief Helper structure used to slice a load in smaller loads.
8082 /// Basically a slice is obtained from the following sequence:
8083 /// Origin = load Ty1, Base
8084 /// Shift = srl Ty1 Origin, CstTy Amount
8085 /// Inst = trunc Shift to Ty2
8086 ///
8087 /// Then, it will be rewriten into:
8088 /// Slice = load SliceTy, Base + SliceOffset
8089 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8090 ///
8091 /// SliceTy is deduced from the number of bits that are actually used to
8092 /// build Inst.
8093 struct LoadedSlice {
8094   /// \brief Helper structure used to compute the cost of a slice.
8095   struct Cost {
8096     /// Are we optimizing for code size.
8097     bool ForCodeSize;
8098     /// Various cost.
8099     unsigned Loads;
8100     unsigned Truncates;
8101     unsigned CrossRegisterBanksCopies;
8102     unsigned ZExts;
8103     unsigned Shift;
8104
8105     Cost(bool ForCodeSize = false)
8106         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8107           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8108
8109     /// \brief Get the cost of one isolated slice.
8110     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8111         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8112           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8113       EVT TruncType = LS.Inst->getValueType(0);
8114       EVT LoadedType = LS.getLoadedType();
8115       if (TruncType != LoadedType &&
8116           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8117         ZExts = 1;
8118     }
8119
8120     /// \brief Account for slicing gain in the current cost.
8121     /// Slicing provide a few gains like removing a shift or a
8122     /// truncate. This method allows to grow the cost of the original
8123     /// load with the gain from this slice.
8124     void addSliceGain(const LoadedSlice &LS) {
8125       // Each slice saves a truncate.
8126       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8127       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8128                               LS.Inst->getOperand(0).getValueType()))
8129         ++Truncates;
8130       // If there is a shift amount, this slice gets rid of it.
8131       if (LS.Shift)
8132         ++Shift;
8133       // If this slice can merge a cross register bank copy, account for it.
8134       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8135         ++CrossRegisterBanksCopies;
8136     }
8137
8138     Cost &operator+=(const Cost &RHS) {
8139       Loads += RHS.Loads;
8140       Truncates += RHS.Truncates;
8141       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8142       ZExts += RHS.ZExts;
8143       Shift += RHS.Shift;
8144       return *this;
8145     }
8146
8147     bool operator==(const Cost &RHS) const {
8148       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8149              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8150              ZExts == RHS.ZExts && Shift == RHS.Shift;
8151     }
8152
8153     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8154
8155     bool operator<(const Cost &RHS) const {
8156       // Assume cross register banks copies are as expensive as loads.
8157       // FIXME: Do we want some more target hooks?
8158       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8159       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8160       // Unless we are optimizing for code size, consider the
8161       // expensive operation first.
8162       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8163         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8164       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8165              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8166     }
8167
8168     bool operator>(const Cost &RHS) const { return RHS < *this; }
8169
8170     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8171
8172     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8173   };
8174   // The last instruction that represent the slice. This should be a
8175   // truncate instruction.
8176   SDNode *Inst;
8177   // The original load instruction.
8178   LoadSDNode *Origin;
8179   // The right shift amount in bits from the original load.
8180   unsigned Shift;
8181   // The DAG from which Origin came from.
8182   // This is used to get some contextual information about legal types, etc.
8183   SelectionDAG *DAG;
8184
8185   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8186               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8187       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8188
8189   LoadedSlice(const LoadedSlice &LS)
8190       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8191
8192   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8193   /// \return Result is \p BitWidth and has used bits set to 1 and
8194   ///         not used bits set to 0.
8195   APInt getUsedBits() const {
8196     // Reproduce the trunc(lshr) sequence:
8197     // - Start from the truncated value.
8198     // - Zero extend to the desired bit width.
8199     // - Shift left.
8200     assert(Origin && "No original load to compare against.");
8201     unsigned BitWidth = Origin->getValueSizeInBits(0);
8202     assert(Inst && "This slice is not bound to an instruction");
8203     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8204            "Extracted slice is bigger than the whole type!");
8205     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8206     UsedBits.setAllBits();
8207     UsedBits = UsedBits.zext(BitWidth);
8208     UsedBits <<= Shift;
8209     return UsedBits;
8210   }
8211
8212   /// \brief Get the size of the slice to be loaded in bytes.
8213   unsigned getLoadedSize() const {
8214     unsigned SliceSize = getUsedBits().countPopulation();
8215     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8216     return SliceSize / 8;
8217   }
8218
8219   /// \brief Get the type that will be loaded for this slice.
8220   /// Note: This may not be the final type for the slice.
8221   EVT getLoadedType() const {
8222     assert(DAG && "Missing context");
8223     LLVMContext &Ctxt = *DAG->getContext();
8224     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8225   }
8226
8227   /// \brief Get the alignment of the load used for this slice.
8228   unsigned getAlignment() const {
8229     unsigned Alignment = Origin->getAlignment();
8230     unsigned Offset = getOffsetFromBase();
8231     if (Offset != 0)
8232       Alignment = MinAlign(Alignment, Alignment + Offset);
8233     return Alignment;
8234   }
8235
8236   /// \brief Check if this slice can be rewritten with legal operations.
8237   bool isLegal() const {
8238     // An invalid slice is not legal.
8239     if (!Origin || !Inst || !DAG)
8240       return false;
8241
8242     // Offsets are for indexed load only, we do not handle that.
8243     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8244       return false;
8245
8246     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8247
8248     // Check that the type is legal.
8249     EVT SliceType = getLoadedType();
8250     if (!TLI.isTypeLegal(SliceType))
8251       return false;
8252
8253     // Check that the load is legal for this type.
8254     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8255       return false;
8256
8257     // Check that the offset can be computed.
8258     // 1. Check its type.
8259     EVT PtrType = Origin->getBasePtr().getValueType();
8260     if (PtrType == MVT::Untyped || PtrType.isExtended())
8261       return false;
8262
8263     // 2. Check that it fits in the immediate.
8264     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8265       return false;
8266
8267     // 3. Check that the computation is legal.
8268     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8269       return false;
8270
8271     // Check that the zext is legal if it needs one.
8272     EVT TruncateType = Inst->getValueType(0);
8273     if (TruncateType != SliceType &&
8274         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8275       return false;
8276
8277     return true;
8278   }
8279
8280   /// \brief Get the offset in bytes of this slice in the original chunk of
8281   /// bits.
8282   /// \pre DAG != nullptr.
8283   uint64_t getOffsetFromBase() const {
8284     assert(DAG && "Missing context.");
8285     bool IsBigEndian =
8286         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8287     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8288     uint64_t Offset = Shift / 8;
8289     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8290     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8291            "The size of the original loaded type is not a multiple of a"
8292            " byte.");
8293     // If Offset is bigger than TySizeInBytes, it means we are loading all
8294     // zeros. This should have been optimized before in the process.
8295     assert(TySizeInBytes > Offset &&
8296            "Invalid shift amount for given loaded size");
8297     if (IsBigEndian)
8298       Offset = TySizeInBytes - Offset - getLoadedSize();
8299     return Offset;
8300   }
8301
8302   /// \brief Generate the sequence of instructions to load the slice
8303   /// represented by this object and redirect the uses of this slice to
8304   /// this new sequence of instructions.
8305   /// \pre this->Inst && this->Origin are valid Instructions and this
8306   /// object passed the legal check: LoadedSlice::isLegal returned true.
8307   /// \return The last instruction of the sequence used to load the slice.
8308   SDValue loadSlice() const {
8309     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8310     const SDValue &OldBaseAddr = Origin->getBasePtr();
8311     SDValue BaseAddr = OldBaseAddr;
8312     // Get the offset in that chunk of bytes w.r.t. the endianess.
8313     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8314     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8315     if (Offset) {
8316       // BaseAddr = BaseAddr + Offset.
8317       EVT ArithType = BaseAddr.getValueType();
8318       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8319                               DAG->getConstant(Offset, ArithType));
8320     }
8321
8322     // Create the type of the loaded slice according to its size.
8323     EVT SliceType = getLoadedType();
8324
8325     // Create the load for the slice.
8326     SDValue LastInst = DAG->getLoad(
8327         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8328         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8329         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8330     // If the final type is not the same as the loaded type, this means that
8331     // we have to pad with zero. Create a zero extend for that.
8332     EVT FinalType = Inst->getValueType(0);
8333     if (SliceType != FinalType)
8334       LastInst =
8335           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8336     return LastInst;
8337   }
8338
8339   /// \brief Check if this slice can be merged with an expensive cross register
8340   /// bank copy. E.g.,
8341   /// i = load i32
8342   /// f = bitcast i32 i to float
8343   bool canMergeExpensiveCrossRegisterBankCopy() const {
8344     if (!Inst || !Inst->hasOneUse())
8345       return false;
8346     SDNode *Use = *Inst->use_begin();
8347     if (Use->getOpcode() != ISD::BITCAST)
8348       return false;
8349     assert(DAG && "Missing context");
8350     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8351     EVT ResVT = Use->getValueType(0);
8352     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8353     const TargetRegisterClass *ArgRC =
8354         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8355     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8356       return false;
8357
8358     // At this point, we know that we perform a cross-register-bank copy.
8359     // Check if it is expensive.
8360     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8361     // Assume bitcasts are cheap, unless both register classes do not
8362     // explicitly share a common sub class.
8363     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8364       return false;
8365
8366     // Check if it will be merged with the load.
8367     // 1. Check the alignment constraint.
8368     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8369         ResVT.getTypeForEVT(*DAG->getContext()));
8370
8371     if (RequiredAlignment > getAlignment())
8372       return false;
8373
8374     // 2. Check that the load is a legal operation for that type.
8375     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8376       return false;
8377
8378     // 3. Check that we do not have a zext in the way.
8379     if (Inst->getValueType(0) != getLoadedType())
8380       return false;
8381
8382     return true;
8383   }
8384 };
8385 }
8386
8387 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8388 /// \p UsedBits looks like 0..0 1..1 0..0.
8389 static bool areUsedBitsDense(const APInt &UsedBits) {
8390   // If all the bits are one, this is dense!
8391   if (UsedBits.isAllOnesValue())
8392     return true;
8393
8394   // Get rid of the unused bits on the right.
8395   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8396   // Get rid of the unused bits on the left.
8397   if (NarrowedUsedBits.countLeadingZeros())
8398     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8399   // Check that the chunk of bits is completely used.
8400   return NarrowedUsedBits.isAllOnesValue();
8401 }
8402
8403 /// \brief Check whether or not \p First and \p Second are next to each other
8404 /// in memory. This means that there is no hole between the bits loaded
8405 /// by \p First and the bits loaded by \p Second.
8406 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8407                                      const LoadedSlice &Second) {
8408   assert(First.Origin == Second.Origin && First.Origin &&
8409          "Unable to match different memory origins.");
8410   APInt UsedBits = First.getUsedBits();
8411   assert((UsedBits & Second.getUsedBits()) == 0 &&
8412          "Slices are not supposed to overlap.");
8413   UsedBits |= Second.getUsedBits();
8414   return areUsedBitsDense(UsedBits);
8415 }
8416
8417 /// \brief Adjust the \p GlobalLSCost according to the target
8418 /// paring capabilities and the layout of the slices.
8419 /// \pre \p GlobalLSCost should account for at least as many loads as
8420 /// there is in the slices in \p LoadedSlices.
8421 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8422                                  LoadedSlice::Cost &GlobalLSCost) {
8423   unsigned NumberOfSlices = LoadedSlices.size();
8424   // If there is less than 2 elements, no pairing is possible.
8425   if (NumberOfSlices < 2)
8426     return;
8427
8428   // Sort the slices so that elements that are likely to be next to each
8429   // other in memory are next to each other in the list.
8430   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8431             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8432     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8433     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8434   });
8435   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8436   // First (resp. Second) is the first (resp. Second) potentially candidate
8437   // to be placed in a paired load.
8438   const LoadedSlice *First = nullptr;
8439   const LoadedSlice *Second = nullptr;
8440   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8441                 // Set the beginning of the pair.
8442                                                            First = Second) {
8443
8444     Second = &LoadedSlices[CurrSlice];
8445
8446     // If First is NULL, it means we start a new pair.
8447     // Get to the next slice.
8448     if (!First)
8449       continue;
8450
8451     EVT LoadedType = First->getLoadedType();
8452
8453     // If the types of the slices are different, we cannot pair them.
8454     if (LoadedType != Second->getLoadedType())
8455       continue;
8456
8457     // Check if the target supplies paired loads for this type.
8458     unsigned RequiredAlignment = 0;
8459     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8460       // move to the next pair, this type is hopeless.
8461       Second = nullptr;
8462       continue;
8463     }
8464     // Check if we meet the alignment requirement.
8465     if (RequiredAlignment > First->getAlignment())
8466       continue;
8467
8468     // Check that both loads are next to each other in memory.
8469     if (!areSlicesNextToEachOther(*First, *Second))
8470       continue;
8471
8472     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8473     --GlobalLSCost.Loads;
8474     // Move to the next pair.
8475     Second = nullptr;
8476   }
8477 }
8478
8479 /// \brief Check the profitability of all involved LoadedSlice.
8480 /// Currently, it is considered profitable if there is exactly two
8481 /// involved slices (1) which are (2) next to each other in memory, and
8482 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8483 ///
8484 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8485 /// the elements themselves.
8486 ///
8487 /// FIXME: When the cost model will be mature enough, we can relax
8488 /// constraints (1) and (2).
8489 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8490                                 const APInt &UsedBits, bool ForCodeSize) {
8491   unsigned NumberOfSlices = LoadedSlices.size();
8492   if (StressLoadSlicing)
8493     return NumberOfSlices > 1;
8494
8495   // Check (1).
8496   if (NumberOfSlices != 2)
8497     return false;
8498
8499   // Check (2).
8500   if (!areUsedBitsDense(UsedBits))
8501     return false;
8502
8503   // Check (3).
8504   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8505   // The original code has one big load.
8506   OrigCost.Loads = 1;
8507   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8508     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8509     // Accumulate the cost of all the slices.
8510     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8511     GlobalSlicingCost += SliceCost;
8512
8513     // Account as cost in the original configuration the gain obtained
8514     // with the current slices.
8515     OrigCost.addSliceGain(LS);
8516   }
8517
8518   // If the target supports paired load, adjust the cost accordingly.
8519   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8520   return OrigCost > GlobalSlicingCost;
8521 }
8522
8523 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8524 /// operations, split it in the various pieces being extracted.
8525 ///
8526 /// This sort of thing is introduced by SROA.
8527 /// This slicing takes care not to insert overlapping loads.
8528 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8529 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8530   if (Level < AfterLegalizeDAG)
8531     return false;
8532
8533   LoadSDNode *LD = cast<LoadSDNode>(N);
8534   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8535       !LD->getValueType(0).isInteger())
8536     return false;
8537
8538   // Keep track of already used bits to detect overlapping values.
8539   // In that case, we will just abort the transformation.
8540   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8541
8542   SmallVector<LoadedSlice, 4> LoadedSlices;
8543
8544   // Check if this load is used as several smaller chunks of bits.
8545   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8546   // of computation for each trunc.
8547   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8548        UI != UIEnd; ++UI) {
8549     // Skip the uses of the chain.
8550     if (UI.getUse().getResNo() != 0)
8551       continue;
8552
8553     SDNode *User = *UI;
8554     unsigned Shift = 0;
8555
8556     // Check if this is a trunc(lshr).
8557     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8558         isa<ConstantSDNode>(User->getOperand(1))) {
8559       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8560       User = *User->use_begin();
8561     }
8562
8563     // At this point, User is a Truncate, iff we encountered, trunc or
8564     // trunc(lshr).
8565     if (User->getOpcode() != ISD::TRUNCATE)
8566       return false;
8567
8568     // The width of the type must be a power of 2 and greater than 8-bits.
8569     // Otherwise the load cannot be represented in LLVM IR.
8570     // Moreover, if we shifted with a non-8-bits multiple, the slice
8571     // will be across several bytes. We do not support that.
8572     unsigned Width = User->getValueSizeInBits(0);
8573     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8574       return 0;
8575
8576     // Build the slice for this chain of computations.
8577     LoadedSlice LS(User, LD, Shift, &DAG);
8578     APInt CurrentUsedBits = LS.getUsedBits();
8579
8580     // Check if this slice overlaps with another.
8581     if ((CurrentUsedBits & UsedBits) != 0)
8582       return false;
8583     // Update the bits used globally.
8584     UsedBits |= CurrentUsedBits;
8585
8586     // Check if the new slice would be legal.
8587     if (!LS.isLegal())
8588       return false;
8589
8590     // Record the slice.
8591     LoadedSlices.push_back(LS);
8592   }
8593
8594   // Abort slicing if it does not seem to be profitable.
8595   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8596     return false;
8597
8598   ++SlicedLoads;
8599
8600   // Rewrite each chain to use an independent load.
8601   // By construction, each chain can be represented by a unique load.
8602
8603   // Prepare the argument for the new token factor for all the slices.
8604   SmallVector<SDValue, 8> ArgChains;
8605   for (SmallVectorImpl<LoadedSlice>::const_iterator
8606            LSIt = LoadedSlices.begin(),
8607            LSItEnd = LoadedSlices.end();
8608        LSIt != LSItEnd; ++LSIt) {
8609     SDValue SliceInst = LSIt->loadSlice();
8610     CombineTo(LSIt->Inst, SliceInst, true);
8611     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8612       SliceInst = SliceInst.getOperand(0);
8613     assert(SliceInst->getOpcode() == ISD::LOAD &&
8614            "It takes more than a zext to get to the loaded slice!!");
8615     ArgChains.push_back(SliceInst.getValue(1));
8616   }
8617
8618   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8619                               ArgChains);
8620   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8621   return true;
8622 }
8623
8624 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8625 /// load is having specific bytes cleared out.  If so, return the byte size
8626 /// being masked out and the shift amount.
8627 static std::pair<unsigned, unsigned>
8628 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8629   std::pair<unsigned, unsigned> Result(0, 0);
8630
8631   // Check for the structure we're looking for.
8632   if (V->getOpcode() != ISD::AND ||
8633       !isa<ConstantSDNode>(V->getOperand(1)) ||
8634       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8635     return Result;
8636
8637   // Check the chain and pointer.
8638   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8639   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8640
8641   // The store should be chained directly to the load or be an operand of a
8642   // tokenfactor.
8643   if (LD == Chain.getNode())
8644     ; // ok.
8645   else if (Chain->getOpcode() != ISD::TokenFactor)
8646     return Result; // Fail.
8647   else {
8648     bool isOk = false;
8649     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8650       if (Chain->getOperand(i).getNode() == LD) {
8651         isOk = true;
8652         break;
8653       }
8654     if (!isOk) return Result;
8655   }
8656
8657   // This only handles simple types.
8658   if (V.getValueType() != MVT::i16 &&
8659       V.getValueType() != MVT::i32 &&
8660       V.getValueType() != MVT::i64)
8661     return Result;
8662
8663   // Check the constant mask.  Invert it so that the bits being masked out are
8664   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8665   // follow the sign bit for uniformity.
8666   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8667   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8668   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8669   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8670   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8671   if (NotMaskLZ == 64) return Result;  // All zero mask.
8672
8673   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8674   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8675     return Result;
8676
8677   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8678   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8679     NotMaskLZ -= 64-V.getValueSizeInBits();
8680
8681   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8682   switch (MaskedBytes) {
8683   case 1:
8684   case 2:
8685   case 4: break;
8686   default: return Result; // All one mask, or 5-byte mask.
8687   }
8688
8689   // Verify that the first bit starts at a multiple of mask so that the access
8690   // is aligned the same as the access width.
8691   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8692
8693   Result.first = MaskedBytes;
8694   Result.second = NotMaskTZ/8;
8695   return Result;
8696 }
8697
8698
8699 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8700 /// provides a value as specified by MaskInfo.  If so, replace the specified
8701 /// store with a narrower store of truncated IVal.
8702 static SDNode *
8703 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8704                                 SDValue IVal, StoreSDNode *St,
8705                                 DAGCombiner *DC) {
8706   unsigned NumBytes = MaskInfo.first;
8707   unsigned ByteShift = MaskInfo.second;
8708   SelectionDAG &DAG = DC->getDAG();
8709
8710   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8711   // that uses this.  If not, this is not a replacement.
8712   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8713                                   ByteShift*8, (ByteShift+NumBytes)*8);
8714   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8715
8716   // Check that it is legal on the target to do this.  It is legal if the new
8717   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8718   // legalization.
8719   MVT VT = MVT::getIntegerVT(NumBytes*8);
8720   if (!DC->isTypeLegal(VT))
8721     return nullptr;
8722
8723   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8724   // shifted by ByteShift and truncated down to NumBytes.
8725   if (ByteShift)
8726     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8727                        DAG.getConstant(ByteShift*8,
8728                                     DC->getShiftAmountTy(IVal.getValueType())));
8729
8730   // Figure out the offset for the store and the alignment of the access.
8731   unsigned StOffset;
8732   unsigned NewAlign = St->getAlignment();
8733
8734   if (DAG.getTargetLoweringInfo().isLittleEndian())
8735     StOffset = ByteShift;
8736   else
8737     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8738
8739   SDValue Ptr = St->getBasePtr();
8740   if (StOffset) {
8741     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8742                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8743     NewAlign = MinAlign(NewAlign, StOffset);
8744   }
8745
8746   // Truncate down to the new size.
8747   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8748
8749   ++OpsNarrowed;
8750   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8751                       St->getPointerInfo().getWithOffset(StOffset),
8752                       false, false, NewAlign).getNode();
8753 }
8754
8755
8756 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8757 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8758 /// of the loaded bits, try narrowing the load and store if it would end up
8759 /// being a win for performance or code size.
8760 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8761   StoreSDNode *ST  = cast<StoreSDNode>(N);
8762   if (ST->isVolatile())
8763     return SDValue();
8764
8765   SDValue Chain = ST->getChain();
8766   SDValue Value = ST->getValue();
8767   SDValue Ptr   = ST->getBasePtr();
8768   EVT VT = Value.getValueType();
8769
8770   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8771     return SDValue();
8772
8773   unsigned Opc = Value.getOpcode();
8774
8775   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8776   // is a byte mask indicating a consecutive number of bytes, check to see if
8777   // Y is known to provide just those bytes.  If so, we try to replace the
8778   // load + replace + store sequence with a single (narrower) store, which makes
8779   // the load dead.
8780   if (Opc == ISD::OR) {
8781     std::pair<unsigned, unsigned> MaskedLoad;
8782     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8783     if (MaskedLoad.first)
8784       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8785                                                   Value.getOperand(1), ST,this))
8786         return SDValue(NewST, 0);
8787
8788     // Or is commutative, so try swapping X and Y.
8789     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8790     if (MaskedLoad.first)
8791       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8792                                                   Value.getOperand(0), ST,this))
8793         return SDValue(NewST, 0);
8794   }
8795
8796   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8797       Value.getOperand(1).getOpcode() != ISD::Constant)
8798     return SDValue();
8799
8800   SDValue N0 = Value.getOperand(0);
8801   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8802       Chain == SDValue(N0.getNode(), 1)) {
8803     LoadSDNode *LD = cast<LoadSDNode>(N0);
8804     if (LD->getBasePtr() != Ptr ||
8805         LD->getPointerInfo().getAddrSpace() !=
8806         ST->getPointerInfo().getAddrSpace())
8807       return SDValue();
8808
8809     // Find the type to narrow it the load / op / store to.
8810     SDValue N1 = Value.getOperand(1);
8811     unsigned BitWidth = N1.getValueSizeInBits();
8812     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8813     if (Opc == ISD::AND)
8814       Imm ^= APInt::getAllOnesValue(BitWidth);
8815     if (Imm == 0 || Imm.isAllOnesValue())
8816       return SDValue();
8817     unsigned ShAmt = Imm.countTrailingZeros();
8818     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8819     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8820     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8821     while (NewBW < BitWidth &&
8822            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8823              TLI.isNarrowingProfitable(VT, NewVT))) {
8824       NewBW = NextPowerOf2(NewBW);
8825       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8826     }
8827     if (NewBW >= BitWidth)
8828       return SDValue();
8829
8830     // If the lsb changed does not start at the type bitwidth boundary,
8831     // start at the previous one.
8832     if (ShAmt % NewBW)
8833       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8834     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8835                                    std::min(BitWidth, ShAmt + NewBW));
8836     if ((Imm & Mask) == Imm) {
8837       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8838       if (Opc == ISD::AND)
8839         NewImm ^= APInt::getAllOnesValue(NewBW);
8840       uint64_t PtrOff = ShAmt / 8;
8841       // For big endian targets, we need to adjust the offset to the pointer to
8842       // load the correct bytes.
8843       if (TLI.isBigEndian())
8844         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8845
8846       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8847       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8848       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8849         return SDValue();
8850
8851       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8852                                    Ptr.getValueType(), Ptr,
8853                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8854       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8855                                   LD->getChain(), NewPtr,
8856                                   LD->getPointerInfo().getWithOffset(PtrOff),
8857                                   LD->isVolatile(), LD->isNonTemporal(),
8858                                   LD->isInvariant(), NewAlign,
8859                                   LD->getTBAAInfo());
8860       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8861                                    DAG.getConstant(NewImm, NewVT));
8862       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8863                                    NewVal, NewPtr,
8864                                    ST->getPointerInfo().getWithOffset(PtrOff),
8865                                    false, false, NewAlign);
8866
8867       AddToWorkList(NewPtr.getNode());
8868       AddToWorkList(NewLD.getNode());
8869       AddToWorkList(NewVal.getNode());
8870       WorkListRemover DeadNodes(*this);
8871       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8872       ++OpsNarrowed;
8873       return NewST;
8874     }
8875   }
8876
8877   return SDValue();
8878 }
8879
8880 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8881 /// if the load value isn't used by any other operations, then consider
8882 /// transforming the pair to integer load / store operations if the target
8883 /// deems the transformation profitable.
8884 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8885   StoreSDNode *ST  = cast<StoreSDNode>(N);
8886   SDValue Chain = ST->getChain();
8887   SDValue Value = ST->getValue();
8888   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8889       Value.hasOneUse() &&
8890       Chain == SDValue(Value.getNode(), 1)) {
8891     LoadSDNode *LD = cast<LoadSDNode>(Value);
8892     EVT VT = LD->getMemoryVT();
8893     if (!VT.isFloatingPoint() ||
8894         VT != ST->getMemoryVT() ||
8895         LD->isNonTemporal() ||
8896         ST->isNonTemporal() ||
8897         LD->getPointerInfo().getAddrSpace() != 0 ||
8898         ST->getPointerInfo().getAddrSpace() != 0)
8899       return SDValue();
8900
8901     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8902     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8903         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8904         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8905         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8906       return SDValue();
8907
8908     unsigned LDAlign = LD->getAlignment();
8909     unsigned STAlign = ST->getAlignment();
8910     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8911     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8912     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8913       return SDValue();
8914
8915     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8916                                 LD->getChain(), LD->getBasePtr(),
8917                                 LD->getPointerInfo(),
8918                                 false, false, false, LDAlign);
8919
8920     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8921                                  NewLD, ST->getBasePtr(),
8922                                  ST->getPointerInfo(),
8923                                  false, false, STAlign);
8924
8925     AddToWorkList(NewLD.getNode());
8926     AddToWorkList(NewST.getNode());
8927     WorkListRemover DeadNodes(*this);
8928     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8929     ++LdStFP2Int;
8930     return NewST;
8931   }
8932
8933   return SDValue();
8934 }
8935
8936 /// Helper struct to parse and store a memory address as base + index + offset.
8937 /// We ignore sign extensions when it is safe to do so.
8938 /// The following two expressions are not equivalent. To differentiate we need
8939 /// to store whether there was a sign extension involved in the index
8940 /// computation.
8941 ///  (load (i64 add (i64 copyfromreg %c)
8942 ///                 (i64 signextend (add (i8 load %index)
8943 ///                                      (i8 1))))
8944 /// vs
8945 ///
8946 /// (load (i64 add (i64 copyfromreg %c)
8947 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8948 ///                                         (i32 1)))))
8949 struct BaseIndexOffset {
8950   SDValue Base;
8951   SDValue Index;
8952   int64_t Offset;
8953   bool IsIndexSignExt;
8954
8955   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8956
8957   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8958                   bool IsIndexSignExt) :
8959     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8960
8961   bool equalBaseIndex(const BaseIndexOffset &Other) {
8962     return Other.Base == Base && Other.Index == Index &&
8963       Other.IsIndexSignExt == IsIndexSignExt;
8964   }
8965
8966   /// Parses tree in Ptr for base, index, offset addresses.
8967   static BaseIndexOffset match(SDValue Ptr) {
8968     bool IsIndexSignExt = false;
8969
8970     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8971     // instruction, then it could be just the BASE or everything else we don't
8972     // know how to handle. Just use Ptr as BASE and give up.
8973     if (Ptr->getOpcode() != ISD::ADD)
8974       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8975
8976     // We know that we have at least an ADD instruction. Try to pattern match
8977     // the simple case of BASE + OFFSET.
8978     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8979       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8980       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8981                               IsIndexSignExt);
8982     }
8983
8984     // Inside a loop the current BASE pointer is calculated using an ADD and a
8985     // MUL instruction. In this case Ptr is the actual BASE pointer.
8986     // (i64 add (i64 %array_ptr)
8987     //          (i64 mul (i64 %induction_var)
8988     //                   (i64 %element_size)))
8989     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8990       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8991
8992     // Look at Base + Index + Offset cases.
8993     SDValue Base = Ptr->getOperand(0);
8994     SDValue IndexOffset = Ptr->getOperand(1);
8995
8996     // Skip signextends.
8997     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8998       IndexOffset = IndexOffset->getOperand(0);
8999       IsIndexSignExt = true;
9000     }
9001
9002     // Either the case of Base + Index (no offset) or something else.
9003     if (IndexOffset->getOpcode() != ISD::ADD)
9004       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9005
9006     // Now we have the case of Base + Index + offset.
9007     SDValue Index = IndexOffset->getOperand(0);
9008     SDValue Offset = IndexOffset->getOperand(1);
9009
9010     if (!isa<ConstantSDNode>(Offset))
9011       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9012
9013     // Ignore signextends.
9014     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9015       Index = Index->getOperand(0);
9016       IsIndexSignExt = true;
9017     } else IsIndexSignExt = false;
9018
9019     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9020     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9021   }
9022 };
9023
9024 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9025 /// is located in a sequence of memory operations connected by a chain.
9026 struct MemOpLink {
9027   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9028     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9029   // Ptr to the mem node.
9030   LSBaseSDNode *MemNode;
9031   // Offset from the base ptr.
9032   int64_t OffsetFromBase;
9033   // What is the sequence number of this mem node.
9034   // Lowest mem operand in the DAG starts at zero.
9035   unsigned SequenceNum;
9036 };
9037
9038 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9039   EVT MemVT = St->getMemoryVT();
9040   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9041   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9042     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9043
9044   // Don't merge vectors into wider inputs.
9045   if (MemVT.isVector() || !MemVT.isSimple())
9046     return false;
9047
9048   // Perform an early exit check. Do not bother looking at stored values that
9049   // are not constants or loads.
9050   SDValue StoredVal = St->getValue();
9051   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9052   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9053       !IsLoadSrc)
9054     return false;
9055
9056   // Only look at ends of store sequences.
9057   SDValue Chain = SDValue(St, 1);
9058   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9059     return false;
9060
9061   // This holds the base pointer, index, and the offset in bytes from the base
9062   // pointer.
9063   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9064
9065   // We must have a base and an offset.
9066   if (!BasePtr.Base.getNode())
9067     return false;
9068
9069   // Do not handle stores to undef base pointers.
9070   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9071     return false;
9072
9073   // Save the LoadSDNodes that we find in the chain.
9074   // We need to make sure that these nodes do not interfere with
9075   // any of the store nodes.
9076   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9077
9078   // Save the StoreSDNodes that we find in the chain.
9079   SmallVector<MemOpLink, 8> StoreNodes;
9080
9081   // Walk up the chain and look for nodes with offsets from the same
9082   // base pointer. Stop when reaching an instruction with a different kind
9083   // or instruction which has a different base pointer.
9084   unsigned Seq = 0;
9085   StoreSDNode *Index = St;
9086   while (Index) {
9087     // If the chain has more than one use, then we can't reorder the mem ops.
9088     if (Index != St && !SDValue(Index, 1)->hasOneUse())
9089       break;
9090
9091     // Find the base pointer and offset for this memory node.
9092     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9093
9094     // Check that the base pointer is the same as the original one.
9095     if (!Ptr.equalBaseIndex(BasePtr))
9096       break;
9097
9098     // Check that the alignment is the same.
9099     if (Index->getAlignment() != St->getAlignment())
9100       break;
9101
9102     // The memory operands must not be volatile.
9103     if (Index->isVolatile() || Index->isIndexed())
9104       break;
9105
9106     // No truncation.
9107     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9108       if (St->isTruncatingStore())
9109         break;
9110
9111     // The stored memory type must be the same.
9112     if (Index->getMemoryVT() != MemVT)
9113       break;
9114
9115     // We do not allow unaligned stores because we want to prevent overriding
9116     // stores.
9117     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9118       break;
9119
9120     // We found a potential memory operand to merge.
9121     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9122
9123     // Find the next memory operand in the chain. If the next operand in the
9124     // chain is a store then move up and continue the scan with the next
9125     // memory operand. If the next operand is a load save it and use alias
9126     // information to check if it interferes with anything.
9127     SDNode *NextInChain = Index->getChain().getNode();
9128     while (1) {
9129       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9130         // We found a store node. Use it for the next iteration.
9131         Index = STn;
9132         break;
9133       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9134         if (Ldn->isVolatile()) {
9135           Index = nullptr;
9136           break;
9137         }
9138
9139         // Save the load node for later. Continue the scan.
9140         AliasLoadNodes.push_back(Ldn);
9141         NextInChain = Ldn->getChain().getNode();
9142         continue;
9143       } else {
9144         Index = nullptr;
9145         break;
9146       }
9147     }
9148   }
9149
9150   // Check if there is anything to merge.
9151   if (StoreNodes.size() < 2)
9152     return false;
9153
9154   // Sort the memory operands according to their distance from the base pointer.
9155   std::sort(StoreNodes.begin(), StoreNodes.end(),
9156             [](MemOpLink LHS, MemOpLink RHS) {
9157     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9158            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9159             LHS.SequenceNum > RHS.SequenceNum);
9160   });
9161
9162   // Scan the memory operations on the chain and find the first non-consecutive
9163   // store memory address.
9164   unsigned LastConsecutiveStore = 0;
9165   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9166   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9167
9168     // Check that the addresses are consecutive starting from the second
9169     // element in the list of stores.
9170     if (i > 0) {
9171       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9172       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9173         break;
9174     }
9175
9176     bool Alias = false;
9177     // Check if this store interferes with any of the loads that we found.
9178     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9179       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9180         Alias = true;
9181         break;
9182       }
9183     // We found a load that alias with this store. Stop the sequence.
9184     if (Alias)
9185       break;
9186
9187     // Mark this node as useful.
9188     LastConsecutiveStore = i;
9189   }
9190
9191   // The node with the lowest store address.
9192   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9193
9194   // Store the constants into memory as one consecutive store.
9195   if (!IsLoadSrc) {
9196     unsigned LastLegalType = 0;
9197     unsigned LastLegalVectorType = 0;
9198     bool NonZero = false;
9199     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9200       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9201       SDValue StoredVal = St->getValue();
9202
9203       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9204         NonZero |= !C->isNullValue();
9205       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9206         NonZero |= !C->getConstantFPValue()->isNullValue();
9207       } else {
9208         // Non-constant.
9209         break;
9210       }
9211
9212       // Find a legal type for the constant store.
9213       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9214       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9215       if (TLI.isTypeLegal(StoreTy))
9216         LastLegalType = i+1;
9217       // Or check whether a truncstore is legal.
9218       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9219                TargetLowering::TypePromoteInteger) {
9220         EVT LegalizedStoredValueTy =
9221           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9222         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9223           LastLegalType = i+1;
9224       }
9225
9226       // Find a legal type for the vector store.
9227       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9228       if (TLI.isTypeLegal(Ty))
9229         LastLegalVectorType = i + 1;
9230     }
9231
9232     // We only use vectors if the constant is known to be zero and the
9233     // function is not marked with the noimplicitfloat attribute.
9234     if (NonZero || NoVectors)
9235       LastLegalVectorType = 0;
9236
9237     // Check if we found a legal integer type to store.
9238     if (LastLegalType == 0 && LastLegalVectorType == 0)
9239       return false;
9240
9241     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9242     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9243
9244     // Make sure we have something to merge.
9245     if (NumElem < 2)
9246       return false;
9247
9248     unsigned EarliestNodeUsed = 0;
9249     for (unsigned i=0; i < NumElem; ++i) {
9250       // Find a chain for the new wide-store operand. Notice that some
9251       // of the store nodes that we found may not be selected for inclusion
9252       // in the wide store. The chain we use needs to be the chain of the
9253       // earliest store node which is *used* and replaced by the wide store.
9254       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9255         EarliestNodeUsed = i;
9256     }
9257
9258     // The earliest Node in the DAG.
9259     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9260     SDLoc DL(StoreNodes[0].MemNode);
9261
9262     SDValue StoredVal;
9263     if (UseVector) {
9264       // Find a legal type for the vector store.
9265       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9266       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9267       StoredVal = DAG.getConstant(0, Ty);
9268     } else {
9269       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9270       APInt StoreInt(StoreBW, 0);
9271
9272       // Construct a single integer constant which is made of the smaller
9273       // constant inputs.
9274       bool IsLE = TLI.isLittleEndian();
9275       for (unsigned i = 0; i < NumElem ; ++i) {
9276         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9277         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9278         SDValue Val = St->getValue();
9279         StoreInt<<=ElementSizeBytes*8;
9280         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9281           StoreInt|=C->getAPIntValue().zext(StoreBW);
9282         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9283           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9284         } else {
9285           assert(false && "Invalid constant element type");
9286         }
9287       }
9288
9289       // Create the new Load and Store operations.
9290       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9291       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9292     }
9293
9294     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9295                                     FirstInChain->getBasePtr(),
9296                                     FirstInChain->getPointerInfo(),
9297                                     false, false,
9298                                     FirstInChain->getAlignment());
9299
9300     // Replace the first store with the new store
9301     CombineTo(EarliestOp, NewStore);
9302     // Erase all other stores.
9303     for (unsigned i = 0; i < NumElem ; ++i) {
9304       if (StoreNodes[i].MemNode == EarliestOp)
9305         continue;
9306       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9307       // ReplaceAllUsesWith will replace all uses that existed when it was
9308       // called, but graph optimizations may cause new ones to appear. For
9309       // example, the case in pr14333 looks like
9310       //
9311       //  St's chain -> St -> another store -> X
9312       //
9313       // And the only difference from St to the other store is the chain.
9314       // When we change it's chain to be St's chain they become identical,
9315       // get CSEed and the net result is that X is now a use of St.
9316       // Since we know that St is redundant, just iterate.
9317       while (!St->use_empty())
9318         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9319       removeFromWorkList(St);
9320       DAG.DeleteNode(St);
9321     }
9322
9323     return true;
9324   }
9325
9326   // Below we handle the case of multiple consecutive stores that
9327   // come from multiple consecutive loads. We merge them into a single
9328   // wide load and a single wide store.
9329
9330   // Look for load nodes which are used by the stored values.
9331   SmallVector<MemOpLink, 8> LoadNodes;
9332
9333   // Find acceptable loads. Loads need to have the same chain (token factor),
9334   // must not be zext, volatile, indexed, and they must be consecutive.
9335   BaseIndexOffset LdBasePtr;
9336   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9337     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9338     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9339     if (!Ld) break;
9340
9341     // Loads must only have one use.
9342     if (!Ld->hasNUsesOfValue(1, 0))
9343       break;
9344
9345     // Check that the alignment is the same as the stores.
9346     if (Ld->getAlignment() != St->getAlignment())
9347       break;
9348
9349     // The memory operands must not be volatile.
9350     if (Ld->isVolatile() || Ld->isIndexed())
9351       break;
9352
9353     // We do not accept ext loads.
9354     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9355       break;
9356
9357     // The stored memory type must be the same.
9358     if (Ld->getMemoryVT() != MemVT)
9359       break;
9360
9361     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9362     // If this is not the first ptr that we check.
9363     if (LdBasePtr.Base.getNode()) {
9364       // The base ptr must be the same.
9365       if (!LdPtr.equalBaseIndex(LdBasePtr))
9366         break;
9367     } else {
9368       // Check that all other base pointers are the same as this one.
9369       LdBasePtr = LdPtr;
9370     }
9371
9372     // We found a potential memory operand to merge.
9373     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9374   }
9375
9376   if (LoadNodes.size() < 2)
9377     return false;
9378
9379   // Scan the memory operations on the chain and find the first non-consecutive
9380   // load memory address. These variables hold the index in the store node
9381   // array.
9382   unsigned LastConsecutiveLoad = 0;
9383   // This variable refers to the size and not index in the array.
9384   unsigned LastLegalVectorType = 0;
9385   unsigned LastLegalIntegerType = 0;
9386   StartAddress = LoadNodes[0].OffsetFromBase;
9387   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9388   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9389     // All loads much share the same chain.
9390     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9391       break;
9392
9393     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9394     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9395       break;
9396     LastConsecutiveLoad = i;
9397
9398     // Find a legal type for the vector store.
9399     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9400     if (TLI.isTypeLegal(StoreTy))
9401       LastLegalVectorType = i + 1;
9402
9403     // Find a legal type for the integer store.
9404     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9405     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9406     if (TLI.isTypeLegal(StoreTy))
9407       LastLegalIntegerType = i + 1;
9408     // Or check whether a truncstore and extload is legal.
9409     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9410              TargetLowering::TypePromoteInteger) {
9411       EVT LegalizedStoredValueTy =
9412         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9413       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9414           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9415           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9416           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9417         LastLegalIntegerType = i+1;
9418     }
9419   }
9420
9421   // Only use vector types if the vector type is larger than the integer type.
9422   // If they are the same, use integers.
9423   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9424   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9425
9426   // We add +1 here because the LastXXX variables refer to location while
9427   // the NumElem refers to array/index size.
9428   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9429   NumElem = std::min(LastLegalType, NumElem);
9430
9431   if (NumElem < 2)
9432     return false;
9433
9434   // The earliest Node in the DAG.
9435   unsigned EarliestNodeUsed = 0;
9436   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9437   for (unsigned i=1; i<NumElem; ++i) {
9438     // Find a chain for the new wide-store operand. Notice that some
9439     // of the store nodes that we found may not be selected for inclusion
9440     // in the wide store. The chain we use needs to be the chain of the
9441     // earliest store node which is *used* and replaced by the wide store.
9442     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9443       EarliestNodeUsed = i;
9444   }
9445
9446   // Find if it is better to use vectors or integers to load and store
9447   // to memory.
9448   EVT JointMemOpVT;
9449   if (UseVectorTy) {
9450     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9451   } else {
9452     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9453     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9454   }
9455
9456   SDLoc LoadDL(LoadNodes[0].MemNode);
9457   SDLoc StoreDL(StoreNodes[0].MemNode);
9458
9459   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9460   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9461                                 FirstLoad->getChain(),
9462                                 FirstLoad->getBasePtr(),
9463                                 FirstLoad->getPointerInfo(),
9464                                 false, false, false,
9465                                 FirstLoad->getAlignment());
9466
9467   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9468                                   FirstInChain->getBasePtr(),
9469                                   FirstInChain->getPointerInfo(), false, false,
9470                                   FirstInChain->getAlignment());
9471
9472   // Replace one of the loads with the new load.
9473   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9474   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9475                                 SDValue(NewLoad.getNode(), 1));
9476
9477   // Remove the rest of the load chains.
9478   for (unsigned i = 1; i < NumElem ; ++i) {
9479     // Replace all chain users of the old load nodes with the chain of the new
9480     // load node.
9481     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9482     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9483   }
9484
9485   // Replace the first store with the new store.
9486   CombineTo(EarliestOp, NewStore);
9487   // Erase all other stores.
9488   for (unsigned i = 0; i < NumElem ; ++i) {
9489     // Remove all Store nodes.
9490     if (StoreNodes[i].MemNode == EarliestOp)
9491       continue;
9492     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9493     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9494     removeFromWorkList(St);
9495     DAG.DeleteNode(St);
9496   }
9497
9498   return true;
9499 }
9500
9501 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9502   StoreSDNode *ST  = cast<StoreSDNode>(N);
9503   SDValue Chain = ST->getChain();
9504   SDValue Value = ST->getValue();
9505   SDValue Ptr   = ST->getBasePtr();
9506
9507   // If this is a store of a bit convert, store the input value if the
9508   // resultant store does not need a higher alignment than the original.
9509   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9510       ST->isUnindexed()) {
9511     unsigned OrigAlign = ST->getAlignment();
9512     EVT SVT = Value.getOperand(0).getValueType();
9513     unsigned Align = TLI.getDataLayout()->
9514       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9515     if (Align <= OrigAlign &&
9516         ((!LegalOperations && !ST->isVolatile()) ||
9517          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9518       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9519                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9520                           ST->isNonTemporal(), OrigAlign,
9521                           ST->getTBAAInfo());
9522   }
9523
9524   // Turn 'store undef, Ptr' -> nothing.
9525   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9526     return Chain;
9527
9528   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9529   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9530     // NOTE: If the original store is volatile, this transform must not increase
9531     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9532     // processor operation but an i64 (which is not legal) requires two.  So the
9533     // transform should not be done in this case.
9534     if (Value.getOpcode() != ISD::TargetConstantFP) {
9535       SDValue Tmp;
9536       switch (CFP->getSimpleValueType(0).SimpleTy) {
9537       default: llvm_unreachable("Unknown FP type");
9538       case MVT::f16:    // We don't do this for these yet.
9539       case MVT::f80:
9540       case MVT::f128:
9541       case MVT::ppcf128:
9542         break;
9543       case MVT::f32:
9544         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9545             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9546           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9547                               bitcastToAPInt().getZExtValue(), MVT::i32);
9548           return DAG.getStore(Chain, SDLoc(N), Tmp,
9549                               Ptr, ST->getMemOperand());
9550         }
9551         break;
9552       case MVT::f64:
9553         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9554              !ST->isVolatile()) ||
9555             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9556           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9557                                 getZExtValue(), MVT::i64);
9558           return DAG.getStore(Chain, SDLoc(N), Tmp,
9559                               Ptr, ST->getMemOperand());
9560         }
9561
9562         if (!ST->isVolatile() &&
9563             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9564           // Many FP stores are not made apparent until after legalize, e.g. for
9565           // argument passing.  Since this is so common, custom legalize the
9566           // 64-bit integer store into two 32-bit stores.
9567           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9568           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9569           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9570           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9571
9572           unsigned Alignment = ST->getAlignment();
9573           bool isVolatile = ST->isVolatile();
9574           bool isNonTemporal = ST->isNonTemporal();
9575           const MDNode *TBAAInfo = ST->getTBAAInfo();
9576
9577           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9578                                      Ptr, ST->getPointerInfo(),
9579                                      isVolatile, isNonTemporal,
9580                                      ST->getAlignment(), TBAAInfo);
9581           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9582                             DAG.getConstant(4, Ptr.getValueType()));
9583           Alignment = MinAlign(Alignment, 4U);
9584           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9585                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9586                                      isVolatile, isNonTemporal,
9587                                      Alignment, TBAAInfo);
9588           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9589                              St0, St1);
9590         }
9591
9592         break;
9593       }
9594     }
9595   }
9596
9597   // Try to infer better alignment information than the store already has.
9598   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9599     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9600       if (Align > ST->getAlignment())
9601         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9602                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9603                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9604                                  ST->getTBAAInfo());
9605     }
9606   }
9607
9608   // Try transforming a pair floating point load / store ops to integer
9609   // load / store ops.
9610   SDValue NewST = TransformFPLoadStorePair(N);
9611   if (NewST.getNode())
9612     return NewST;
9613
9614   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9615     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9616 #ifndef NDEBUG
9617   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9618       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9619     UseAA = false;
9620 #endif
9621   if (UseAA && ST->isUnindexed()) {
9622     // Walk up chain skipping non-aliasing memory nodes.
9623     SDValue BetterChain = FindBetterChain(N, Chain);
9624
9625     // If there is a better chain.
9626     if (Chain != BetterChain) {
9627       SDValue ReplStore;
9628
9629       // Replace the chain to avoid dependency.
9630       if (ST->isTruncatingStore()) {
9631         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9632                                       ST->getMemoryVT(), ST->getMemOperand());
9633       } else {
9634         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9635                                  ST->getMemOperand());
9636       }
9637
9638       // Create token to keep both nodes around.
9639       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9640                                   MVT::Other, Chain, ReplStore);
9641
9642       // Make sure the new and old chains are cleaned up.
9643       AddToWorkList(Token.getNode());
9644
9645       // Don't add users to work list.
9646       return CombineTo(N, Token, false);
9647     }
9648   }
9649
9650   // Try transforming N to an indexed store.
9651   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9652     return SDValue(N, 0);
9653
9654   // FIXME: is there such a thing as a truncating indexed store?
9655   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9656       Value.getValueType().isInteger()) {
9657     // See if we can simplify the input to this truncstore with knowledge that
9658     // only the low bits are being used.  For example:
9659     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9660     SDValue Shorter =
9661       GetDemandedBits(Value,
9662                       APInt::getLowBitsSet(
9663                         Value.getValueType().getScalarType().getSizeInBits(),
9664                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9665     AddToWorkList(Value.getNode());
9666     if (Shorter.getNode())
9667       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9668                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9669
9670     // Otherwise, see if we can simplify the operation with
9671     // SimplifyDemandedBits, which only works if the value has a single use.
9672     if (SimplifyDemandedBits(Value,
9673                         APInt::getLowBitsSet(
9674                           Value.getValueType().getScalarType().getSizeInBits(),
9675                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9676       return SDValue(N, 0);
9677   }
9678
9679   // If this is a load followed by a store to the same location, then the store
9680   // is dead/noop.
9681   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9682     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9683         ST->isUnindexed() && !ST->isVolatile() &&
9684         // There can't be any side effects between the load and store, such as
9685         // a call or store.
9686         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9687       // The store is dead, remove it.
9688       return Chain;
9689     }
9690   }
9691
9692   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9693   // truncating store.  We can do this even if this is already a truncstore.
9694   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9695       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9696       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9697                             ST->getMemoryVT())) {
9698     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9699                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9700   }
9701
9702   // Only perform this optimization before the types are legal, because we
9703   // don't want to perform this optimization on every DAGCombine invocation.
9704   if (!LegalTypes) {
9705     bool EverChanged = false;
9706
9707     do {
9708       // There can be multiple store sequences on the same chain.
9709       // Keep trying to merge store sequences until we are unable to do so
9710       // or until we merge the last store on the chain.
9711       bool Changed = MergeConsecutiveStores(ST);
9712       EverChanged |= Changed;
9713       if (!Changed) break;
9714     } while (ST->getOpcode() != ISD::DELETED_NODE);
9715
9716     if (EverChanged)
9717       return SDValue(N, 0);
9718   }
9719
9720   return ReduceLoadOpStoreWidth(N);
9721 }
9722
9723 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9724   SDValue InVec = N->getOperand(0);
9725   SDValue InVal = N->getOperand(1);
9726   SDValue EltNo = N->getOperand(2);
9727   SDLoc dl(N);
9728
9729   // If the inserted element is an UNDEF, just use the input vector.
9730   if (InVal.getOpcode() == ISD::UNDEF)
9731     return InVec;
9732
9733   EVT VT = InVec.getValueType();
9734
9735   // If we can't generate a legal BUILD_VECTOR, exit
9736   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9737     return SDValue();
9738
9739   // Check that we know which element is being inserted
9740   if (!isa<ConstantSDNode>(EltNo))
9741     return SDValue();
9742   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9743
9744   // Canonicalize insert_vector_elt dag nodes.
9745   // Example:
9746   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9747   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9748   //
9749   // Do this only if the child insert_vector node has one use; also
9750   // do this only if indices are both constants and Idx1 < Idx0.
9751   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9752       && isa<ConstantSDNode>(InVec.getOperand(2))) {
9753     unsigned OtherElt =
9754       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9755     if (Elt < OtherElt) {
9756       // Swap nodes.
9757       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9758                                   InVec.getOperand(0), InVal, EltNo);
9759       AddToWorkList(NewOp.getNode());
9760       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9761                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9762     }
9763   }
9764
9765   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9766   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9767   // vector elements.
9768   SmallVector<SDValue, 8> Ops;
9769   // Do not combine these two vectors if the output vector will not replace
9770   // the input vector.
9771   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9772     Ops.append(InVec.getNode()->op_begin(),
9773                InVec.getNode()->op_end());
9774   } else if (InVec.getOpcode() == ISD::UNDEF) {
9775     unsigned NElts = VT.getVectorNumElements();
9776     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9777   } else {
9778     return SDValue();
9779   }
9780
9781   // Insert the element
9782   if (Elt < Ops.size()) {
9783     // All the operands of BUILD_VECTOR must have the same type;
9784     // we enforce that here.
9785     EVT OpVT = Ops[0].getValueType();
9786     if (InVal.getValueType() != OpVT)
9787       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9788                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9789                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9790     Ops[Elt] = InVal;
9791   }
9792
9793   // Return the new vector
9794   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9795 }
9796
9797 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9798     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9799   EVT ResultVT = EVE->getValueType(0);
9800   EVT VecEltVT = InVecVT.getVectorElementType();
9801   unsigned Align = OriginalLoad->getAlignment();
9802   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9803       VecEltVT.getTypeForEVT(*DAG.getContext()));
9804
9805   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9806     return SDValue();
9807
9808   Align = NewAlign;
9809
9810   SDValue NewPtr = OriginalLoad->getBasePtr();
9811   SDValue Offset;
9812   EVT PtrType = NewPtr.getValueType();
9813   MachinePointerInfo MPI;
9814   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9815     int Elt = ConstEltNo->getZExtValue();
9816     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9817     if (TLI.isBigEndian())
9818       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9819     Offset = DAG.getConstant(PtrOff, PtrType);
9820     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9821   } else {
9822     Offset = DAG.getNode(
9823         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9824         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9825     if (TLI.isBigEndian())
9826       Offset = DAG.getNode(
9827           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9828           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9829     MPI = OriginalLoad->getPointerInfo();
9830   }
9831   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9832
9833   // The replacement we need to do here is a little tricky: we need to
9834   // replace an extractelement of a load with a load.
9835   // Use ReplaceAllUsesOfValuesWith to do the replacement.
9836   // Note that this replacement assumes that the extractvalue is the only
9837   // use of the load; that's okay because we don't want to perform this
9838   // transformation in other cases anyway.
9839   SDValue Load;
9840   SDValue Chain;
9841   if (ResultVT.bitsGT(VecEltVT)) {
9842     // If the result type of vextract is wider than the load, then issue an
9843     // extending load instead.
9844     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9845                                    ? ISD::ZEXTLOAD
9846                                    : ISD::EXTLOAD;
9847     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(),
9848                           NewPtr, MPI, VecEltVT, OriginalLoad->isVolatile(),
9849                           OriginalLoad->isNonTemporal(), Align,
9850                           OriginalLoad->getTBAAInfo());
9851     Chain = Load.getValue(1);
9852   } else {
9853     Load = DAG.getLoad(
9854         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9855         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9856         OriginalLoad->isInvariant(), Align, OriginalLoad->getTBAAInfo());
9857     Chain = Load.getValue(1);
9858     if (ResultVT.bitsLT(VecEltVT))
9859       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9860     else
9861       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9862   }
9863   WorkListRemover DeadNodes(*this);
9864   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9865   SDValue To[] = { Load, Chain };
9866   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9867   // Since we're explicitly calling ReplaceAllUses, add the new node to the
9868   // worklist explicitly as well.
9869   AddToWorkList(Load.getNode());
9870   AddUsersToWorkList(Load.getNode()); // Add users too
9871   // Make sure to revisit this node to clean it up; it will usually be dead.
9872   AddToWorkList(EVE);
9873   ++OpsNarrowed;
9874   return SDValue(EVE, 0);
9875 }
9876
9877 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9878   // (vextract (scalar_to_vector val, 0) -> val
9879   SDValue InVec = N->getOperand(0);
9880   EVT VT = InVec.getValueType();
9881   EVT NVT = N->getValueType(0);
9882
9883   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9884     // Check if the result type doesn't match the inserted element type. A
9885     // SCALAR_TO_VECTOR may truncate the inserted element and the
9886     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9887     SDValue InOp = InVec.getOperand(0);
9888     if (InOp.getValueType() != NVT) {
9889       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9890       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9891     }
9892     return InOp;
9893   }
9894
9895   SDValue EltNo = N->getOperand(1);
9896   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9897
9898   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9899   // We only perform this optimization before the op legalization phase because
9900   // we may introduce new vector instructions which are not backed by TD
9901   // patterns. For example on AVX, extracting elements from a wide vector
9902   // without using extract_subvector. However, if we can find an underlying
9903   // scalar value, then we can always use that.
9904   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9905       && ConstEltNo) {
9906     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9907     int NumElem = VT.getVectorNumElements();
9908     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9909     // Find the new index to extract from.
9910     int OrigElt = SVOp->getMaskElt(Elt);
9911
9912     // Extracting an undef index is undef.
9913     if (OrigElt == -1)
9914       return DAG.getUNDEF(NVT);
9915
9916     // Select the right vector half to extract from.
9917     SDValue SVInVec;
9918     if (OrigElt < NumElem) {
9919       SVInVec = InVec->getOperand(0);
9920     } else {
9921       SVInVec = InVec->getOperand(1);
9922       OrigElt -= NumElem;
9923     }
9924
9925     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9926       SDValue InOp = SVInVec.getOperand(OrigElt);
9927       if (InOp.getValueType() != NVT) {
9928         assert(InOp.getValueType().isInteger() && NVT.isInteger());
9929         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9930       }
9931
9932       return InOp;
9933     }
9934
9935     // FIXME: We should handle recursing on other vector shuffles and
9936     // scalar_to_vector here as well.
9937
9938     if (!LegalOperations) {
9939       EVT IndexTy = TLI.getVectorIdxTy();
9940       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9941                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
9942     }
9943   }
9944
9945   bool BCNumEltsChanged = false;
9946   EVT ExtVT = VT.getVectorElementType();
9947   EVT LVT = ExtVT;
9948
9949   // If the result of load has to be truncated, then it's not necessarily
9950   // profitable.
9951   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9952     return SDValue();
9953
9954   if (InVec.getOpcode() == ISD::BITCAST) {
9955     // Don't duplicate a load with other uses.
9956     if (!InVec.hasOneUse())
9957       return SDValue();
9958
9959     EVT BCVT = InVec.getOperand(0).getValueType();
9960     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9961       return SDValue();
9962     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9963       BCNumEltsChanged = true;
9964     InVec = InVec.getOperand(0);
9965     ExtVT = BCVT.getVectorElementType();
9966   }
9967
9968   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
9969   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
9970       ISD::isNormalLoad(InVec.getNode())) {
9971     SDValue Index = N->getOperand(1);
9972     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
9973       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
9974                                                            OrigLoad);
9975   }
9976
9977   // Perform only after legalization to ensure build_vector / vector_shuffle
9978   // optimizations have already been done.
9979   if (!LegalOperations) return SDValue();
9980
9981   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9982   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9983   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9984
9985   if (ConstEltNo) {
9986     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9987
9988     LoadSDNode *LN0 = nullptr;
9989     const ShuffleVectorSDNode *SVN = nullptr;
9990     if (ISD::isNormalLoad(InVec.getNode())) {
9991       LN0 = cast<LoadSDNode>(InVec);
9992     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9993                InVec.getOperand(0).getValueType() == ExtVT &&
9994                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9995       // Don't duplicate a load with other uses.
9996       if (!InVec.hasOneUse())
9997         return SDValue();
9998
9999       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10000     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10001       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10002       // =>
10003       // (load $addr+1*size)
10004
10005       // Don't duplicate a load with other uses.
10006       if (!InVec.hasOneUse())
10007         return SDValue();
10008
10009       // If the bit convert changed the number of elements, it is unsafe
10010       // to examine the mask.
10011       if (BCNumEltsChanged)
10012         return SDValue();
10013
10014       // Select the input vector, guarding against out of range extract vector.
10015       unsigned NumElems = VT.getVectorNumElements();
10016       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10017       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10018
10019       if (InVec.getOpcode() == ISD::BITCAST) {
10020         // Don't duplicate a load with other uses.
10021         if (!InVec.hasOneUse())
10022           return SDValue();
10023
10024         InVec = InVec.getOperand(0);
10025       }
10026       if (ISD::isNormalLoad(InVec.getNode())) {
10027         LN0 = cast<LoadSDNode>(InVec);
10028         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10029         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10030       }
10031     }
10032
10033     // Make sure we found a non-volatile load and the extractelement is
10034     // the only use.
10035     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10036       return SDValue();
10037
10038     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10039     if (Elt == -1)
10040       return DAG.getUNDEF(LVT);
10041
10042     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10043   }
10044
10045   return SDValue();
10046 }
10047
10048 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10049 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10050   // We perform this optimization post type-legalization because
10051   // the type-legalizer often scalarizes integer-promoted vectors.
10052   // Performing this optimization before may create bit-casts which
10053   // will be type-legalized to complex code sequences.
10054   // We perform this optimization only before the operation legalizer because we
10055   // may introduce illegal operations.
10056   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10057     return SDValue();
10058
10059   unsigned NumInScalars = N->getNumOperands();
10060   SDLoc dl(N);
10061   EVT VT = N->getValueType(0);
10062
10063   // Check to see if this is a BUILD_VECTOR of a bunch of values
10064   // which come from any_extend or zero_extend nodes. If so, we can create
10065   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10066   // optimizations. We do not handle sign-extend because we can't fill the sign
10067   // using shuffles.
10068   EVT SourceType = MVT::Other;
10069   bool AllAnyExt = true;
10070
10071   for (unsigned i = 0; i != NumInScalars; ++i) {
10072     SDValue In = N->getOperand(i);
10073     // Ignore undef inputs.
10074     if (In.getOpcode() == ISD::UNDEF) continue;
10075
10076     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10077     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10078
10079     // Abort if the element is not an extension.
10080     if (!ZeroExt && !AnyExt) {
10081       SourceType = MVT::Other;
10082       break;
10083     }
10084
10085     // The input is a ZeroExt or AnyExt. Check the original type.
10086     EVT InTy = In.getOperand(0).getValueType();
10087
10088     // Check that all of the widened source types are the same.
10089     if (SourceType == MVT::Other)
10090       // First time.
10091       SourceType = InTy;
10092     else if (InTy != SourceType) {
10093       // Multiple income types. Abort.
10094       SourceType = MVT::Other;
10095       break;
10096     }
10097
10098     // Check if all of the extends are ANY_EXTENDs.
10099     AllAnyExt &= AnyExt;
10100   }
10101
10102   // In order to have valid types, all of the inputs must be extended from the
10103   // same source type and all of the inputs must be any or zero extend.
10104   // Scalar sizes must be a power of two.
10105   EVT OutScalarTy = VT.getScalarType();
10106   bool ValidTypes = SourceType != MVT::Other &&
10107                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10108                  isPowerOf2_32(SourceType.getSizeInBits());
10109
10110   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10111   // turn into a single shuffle instruction.
10112   if (!ValidTypes)
10113     return SDValue();
10114
10115   bool isLE = TLI.isLittleEndian();
10116   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10117   assert(ElemRatio > 1 && "Invalid element size ratio");
10118   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10119                                DAG.getConstant(0, SourceType);
10120
10121   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10122   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10123
10124   // Populate the new build_vector
10125   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10126     SDValue Cast = N->getOperand(i);
10127     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10128             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10129             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10130     SDValue In;
10131     if (Cast.getOpcode() == ISD::UNDEF)
10132       In = DAG.getUNDEF(SourceType);
10133     else
10134       In = Cast->getOperand(0);
10135     unsigned Index = isLE ? (i * ElemRatio) :
10136                             (i * ElemRatio + (ElemRatio - 1));
10137
10138     assert(Index < Ops.size() && "Invalid index");
10139     Ops[Index] = In;
10140   }
10141
10142   // The type of the new BUILD_VECTOR node.
10143   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10144   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10145          "Invalid vector size");
10146   // Check if the new vector type is legal.
10147   if (!isTypeLegal(VecVT)) return SDValue();
10148
10149   // Make the new BUILD_VECTOR.
10150   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10151
10152   // The new BUILD_VECTOR node has the potential to be further optimized.
10153   AddToWorkList(BV.getNode());
10154   // Bitcast to the desired type.
10155   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10156 }
10157
10158 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10159   EVT VT = N->getValueType(0);
10160
10161   unsigned NumInScalars = N->getNumOperands();
10162   SDLoc dl(N);
10163
10164   EVT SrcVT = MVT::Other;
10165   unsigned Opcode = ISD::DELETED_NODE;
10166   unsigned NumDefs = 0;
10167
10168   for (unsigned i = 0; i != NumInScalars; ++i) {
10169     SDValue In = N->getOperand(i);
10170     unsigned Opc = In.getOpcode();
10171
10172     if (Opc == ISD::UNDEF)
10173       continue;
10174
10175     // If all scalar values are floats and converted from integers.
10176     if (Opcode == ISD::DELETED_NODE &&
10177         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10178       Opcode = Opc;
10179     }
10180
10181     if (Opc != Opcode)
10182       return SDValue();
10183
10184     EVT InVT = In.getOperand(0).getValueType();
10185
10186     // If all scalar values are typed differently, bail out. It's chosen to
10187     // simplify BUILD_VECTOR of integer types.
10188     if (SrcVT == MVT::Other)
10189       SrcVT = InVT;
10190     if (SrcVT != InVT)
10191       return SDValue();
10192     NumDefs++;
10193   }
10194
10195   // If the vector has just one element defined, it's not worth to fold it into
10196   // a vectorized one.
10197   if (NumDefs < 2)
10198     return SDValue();
10199
10200   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10201          && "Should only handle conversion from integer to float.");
10202   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10203
10204   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10205
10206   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10207     return SDValue();
10208
10209   SmallVector<SDValue, 8> Opnds;
10210   for (unsigned i = 0; i != NumInScalars; ++i) {
10211     SDValue In = N->getOperand(i);
10212
10213     if (In.getOpcode() == ISD::UNDEF)
10214       Opnds.push_back(DAG.getUNDEF(SrcVT));
10215     else
10216       Opnds.push_back(In.getOperand(0));
10217   }
10218   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10219   AddToWorkList(BV.getNode());
10220
10221   return DAG.getNode(Opcode, dl, VT, BV);
10222 }
10223
10224 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10225   unsigned NumInScalars = N->getNumOperands();
10226   SDLoc dl(N);
10227   EVT VT = N->getValueType(0);
10228
10229   // A vector built entirely of undefs is undef.
10230   if (ISD::allOperandsUndef(N))
10231     return DAG.getUNDEF(VT);
10232
10233   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10234   if (V.getNode())
10235     return V;
10236
10237   V = reduceBuildVecConvertToConvertBuildVec(N);
10238   if (V.getNode())
10239     return V;
10240
10241   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10242   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10243   // at most two distinct vectors, turn this into a shuffle node.
10244
10245   // May only combine to shuffle after legalize if shuffle is legal.
10246   if (LegalOperations &&
10247       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10248     return SDValue();
10249
10250   SDValue VecIn1, VecIn2;
10251   for (unsigned i = 0; i != NumInScalars; ++i) {
10252     // Ignore undef inputs.
10253     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10254
10255     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10256     // constant index, bail out.
10257     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10258         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10259       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10260       break;
10261     }
10262
10263     // We allow up to two distinct input vectors.
10264     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10265     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10266       continue;
10267
10268     if (!VecIn1.getNode()) {
10269       VecIn1 = ExtractedFromVec;
10270     } else if (!VecIn2.getNode()) {
10271       VecIn2 = ExtractedFromVec;
10272     } else {
10273       // Too many inputs.
10274       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10275       break;
10276     }
10277   }
10278
10279   // If everything is good, we can make a shuffle operation.
10280   if (VecIn1.getNode()) {
10281     SmallVector<int, 8> Mask;
10282     for (unsigned i = 0; i != NumInScalars; ++i) {
10283       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10284         Mask.push_back(-1);
10285         continue;
10286       }
10287
10288       // If extracting from the first vector, just use the index directly.
10289       SDValue Extract = N->getOperand(i);
10290       SDValue ExtVal = Extract.getOperand(1);
10291       if (Extract.getOperand(0) == VecIn1) {
10292         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10293         if (ExtIndex > VT.getVectorNumElements())
10294           return SDValue();
10295
10296         Mask.push_back(ExtIndex);
10297         continue;
10298       }
10299
10300       // Otherwise, use InIdx + VecSize
10301       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10302       Mask.push_back(Idx+NumInScalars);
10303     }
10304
10305     // We can't generate a shuffle node with mismatched input and output types.
10306     // Attempt to transform a single input vector to the correct type.
10307     if ((VT != VecIn1.getValueType())) {
10308       // We don't support shuffeling between TWO values of different types.
10309       if (VecIn2.getNode())
10310         return SDValue();
10311
10312       // We only support widening of vectors which are half the size of the
10313       // output registers. For example XMM->YMM widening on X86 with AVX.
10314       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10315         return SDValue();
10316
10317       // If the input vector type has a different base type to the output
10318       // vector type, bail out.
10319       if (VecIn1.getValueType().getVectorElementType() !=
10320           VT.getVectorElementType())
10321         return SDValue();
10322
10323       // Widen the input vector by adding undef values.
10324       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10325                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10326     }
10327
10328     // If VecIn2 is unused then change it to undef.
10329     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10330
10331     // Check that we were able to transform all incoming values to the same
10332     // type.
10333     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10334         VecIn1.getValueType() != VT)
10335           return SDValue();
10336
10337     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10338     if (!isTypeLegal(VT))
10339       return SDValue();
10340
10341     // Return the new VECTOR_SHUFFLE node.
10342     SDValue Ops[2];
10343     Ops[0] = VecIn1;
10344     Ops[1] = VecIn2;
10345     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10346   }
10347
10348   return SDValue();
10349 }
10350
10351 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10352   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10353   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10354   // inputs come from at most two distinct vectors, turn this into a shuffle
10355   // node.
10356
10357   // If we only have one input vector, we don't need to do any concatenation.
10358   if (N->getNumOperands() == 1)
10359     return N->getOperand(0);
10360
10361   // Check if all of the operands are undefs.
10362   EVT VT = N->getValueType(0);
10363   if (ISD::allOperandsUndef(N))
10364     return DAG.getUNDEF(VT);
10365
10366   // Optimize concat_vectors where one of the vectors is undef.
10367   if (N->getNumOperands() == 2 &&
10368       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10369     SDValue In = N->getOperand(0);
10370     assert(In.getValueType().isVector() && "Must concat vectors");
10371
10372     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10373     if (In->getOpcode() == ISD::BITCAST &&
10374         !In->getOperand(0)->getValueType(0).isVector()) {
10375       SDValue Scalar = In->getOperand(0);
10376       EVT SclTy = Scalar->getValueType(0);
10377
10378       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10379         return SDValue();
10380
10381       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10382                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10383       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10384         return SDValue();
10385
10386       SDLoc dl = SDLoc(N);
10387       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10388       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10389     }
10390   }
10391
10392   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10393   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10394   if (N->getNumOperands() == 2 &&
10395       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10396       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10397     EVT VT = N->getValueType(0);
10398     SDValue N0 = N->getOperand(0);
10399     SDValue N1 = N->getOperand(1);
10400     SmallVector<SDValue, 8> Opnds;
10401     unsigned BuildVecNumElts =  N0.getNumOperands();
10402
10403     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10404     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10405     if (SclTy0.isFloatingPoint()) {
10406       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10407         Opnds.push_back(N0.getOperand(i));
10408       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10409         Opnds.push_back(N1.getOperand(i));
10410     } else {
10411       // If BUILD_VECTOR are from built from integer, they may have different
10412       // operand types. Get the smaller type and truncate all operands to it.
10413       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10414       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10415         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10416                         N0.getOperand(i)));
10417       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10418         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10419                         N1.getOperand(i)));
10420     }
10421
10422     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10423   }
10424
10425   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10426   // nodes often generate nop CONCAT_VECTOR nodes.
10427   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10428   // place the incoming vectors at the exact same location.
10429   SDValue SingleSource = SDValue();
10430   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10431
10432   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10433     SDValue Op = N->getOperand(i);
10434
10435     if (Op.getOpcode() == ISD::UNDEF)
10436       continue;
10437
10438     // Check if this is the identity extract:
10439     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10440       return SDValue();
10441
10442     // Find the single incoming vector for the extract_subvector.
10443     if (SingleSource.getNode()) {
10444       if (Op.getOperand(0) != SingleSource)
10445         return SDValue();
10446     } else {
10447       SingleSource = Op.getOperand(0);
10448
10449       // Check the source type is the same as the type of the result.
10450       // If not, this concat may extend the vector, so we can not
10451       // optimize it away.
10452       if (SingleSource.getValueType() != N->getValueType(0))
10453         return SDValue();
10454     }
10455
10456     unsigned IdentityIndex = i * PartNumElem;
10457     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10458     // The extract index must be constant.
10459     if (!CS)
10460       return SDValue();
10461
10462     // Check that we are reading from the identity index.
10463     if (CS->getZExtValue() != IdentityIndex)
10464       return SDValue();
10465   }
10466
10467   if (SingleSource.getNode())
10468     return SingleSource;
10469
10470   return SDValue();
10471 }
10472
10473 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10474   EVT NVT = N->getValueType(0);
10475   SDValue V = N->getOperand(0);
10476
10477   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10478     // Combine:
10479     //    (extract_subvec (concat V1, V2, ...), i)
10480     // Into:
10481     //    Vi if possible
10482     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10483     // type.
10484     if (V->getOperand(0).getValueType() != NVT)
10485       return SDValue();
10486     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10487     unsigned NumElems = NVT.getVectorNumElements();
10488     assert((Idx % NumElems) == 0 &&
10489            "IDX in concat is not a multiple of the result vector length.");
10490     return V->getOperand(Idx / NumElems);
10491   }
10492
10493   // Skip bitcasting
10494   if (V->getOpcode() == ISD::BITCAST)
10495     V = V.getOperand(0);
10496
10497   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10498     SDLoc dl(N);
10499     // Handle only simple case where vector being inserted and vector
10500     // being extracted are of same type, and are half size of larger vectors.
10501     EVT BigVT = V->getOperand(0).getValueType();
10502     EVT SmallVT = V->getOperand(1).getValueType();
10503     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10504       return SDValue();
10505
10506     // Only handle cases where both indexes are constants with the same type.
10507     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10508     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10509
10510     if (InsIdx && ExtIdx &&
10511         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10512         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10513       // Combine:
10514       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10515       // Into:
10516       //    indices are equal or bit offsets are equal => V1
10517       //    otherwise => (extract_subvec V1, ExtIdx)
10518       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10519           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10520         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10521       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10522                          DAG.getNode(ISD::BITCAST, dl,
10523                                      N->getOperand(0).getValueType(),
10524                                      V->getOperand(0)), N->getOperand(1));
10525     }
10526   }
10527
10528   return SDValue();
10529 }
10530
10531 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10532 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10533   EVT VT = N->getValueType(0);
10534   unsigned NumElts = VT.getVectorNumElements();
10535
10536   SDValue N0 = N->getOperand(0);
10537   SDValue N1 = N->getOperand(1);
10538   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10539
10540   SmallVector<SDValue, 4> Ops;
10541   EVT ConcatVT = N0.getOperand(0).getValueType();
10542   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10543   unsigned NumConcats = NumElts / NumElemsPerConcat;
10544
10545   // Look at every vector that's inserted. We're looking for exact
10546   // subvector-sized copies from a concatenated vector
10547   for (unsigned I = 0; I != NumConcats; ++I) {
10548     // Make sure we're dealing with a copy.
10549     unsigned Begin = I * NumElemsPerConcat;
10550     bool AllUndef = true, NoUndef = true;
10551     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10552       if (SVN->getMaskElt(J) >= 0)
10553         AllUndef = false;
10554       else
10555         NoUndef = false;
10556     }
10557
10558     if (NoUndef) {
10559       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10560         return SDValue();
10561
10562       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10563         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10564           return SDValue();
10565
10566       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10567       if (FirstElt < N0.getNumOperands())
10568         Ops.push_back(N0.getOperand(FirstElt));
10569       else
10570         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10571
10572     } else if (AllUndef) {
10573       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10574     } else { // Mixed with general masks and undefs, can't do optimization.
10575       return SDValue();
10576     }
10577   }
10578
10579   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10580 }
10581
10582 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10583   EVT VT = N->getValueType(0);
10584   unsigned NumElts = VT.getVectorNumElements();
10585
10586   SDValue N0 = N->getOperand(0);
10587   SDValue N1 = N->getOperand(1);
10588
10589   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10590
10591   // Canonicalize shuffle undef, undef -> undef
10592   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10593     return DAG.getUNDEF(VT);
10594
10595   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10596
10597   // Canonicalize shuffle v, v -> v, undef
10598   if (N0 == N1) {
10599     SmallVector<int, 8> NewMask;
10600     for (unsigned i = 0; i != NumElts; ++i) {
10601       int Idx = SVN->getMaskElt(i);
10602       if (Idx >= (int)NumElts) Idx -= NumElts;
10603       NewMask.push_back(Idx);
10604     }
10605     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10606                                 &NewMask[0]);
10607   }
10608
10609   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10610   if (N0.getOpcode() == ISD::UNDEF) {
10611     SmallVector<int, 8> NewMask;
10612     for (unsigned i = 0; i != NumElts; ++i) {
10613       int Idx = SVN->getMaskElt(i);
10614       if (Idx >= 0) {
10615         if (Idx >= (int)NumElts)
10616           Idx -= NumElts;
10617         else
10618           Idx = -1; // remove reference to lhs
10619       }
10620       NewMask.push_back(Idx);
10621     }
10622     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10623                                 &NewMask[0]);
10624   }
10625
10626   // Remove references to rhs if it is undef
10627   if (N1.getOpcode() == ISD::UNDEF) {
10628     bool Changed = false;
10629     SmallVector<int, 8> NewMask;
10630     for (unsigned i = 0; i != NumElts; ++i) {
10631       int Idx = SVN->getMaskElt(i);
10632       if (Idx >= (int)NumElts) {
10633         Idx = -1;
10634         Changed = true;
10635       }
10636       NewMask.push_back(Idx);
10637     }
10638     if (Changed)
10639       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10640   }
10641
10642   // If it is a splat, check if the argument vector is another splat or a
10643   // build_vector with all scalar elements the same.
10644   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10645     SDNode *V = N0.getNode();
10646
10647     // If this is a bit convert that changes the element type of the vector but
10648     // not the number of vector elements, look through it.  Be careful not to
10649     // look though conversions that change things like v4f32 to v2f64.
10650     if (V->getOpcode() == ISD::BITCAST) {
10651       SDValue ConvInput = V->getOperand(0);
10652       if (ConvInput.getValueType().isVector() &&
10653           ConvInput.getValueType().getVectorNumElements() == NumElts)
10654         V = ConvInput.getNode();
10655     }
10656
10657     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10658       assert(V->getNumOperands() == NumElts &&
10659              "BUILD_VECTOR has wrong number of operands");
10660       SDValue Base;
10661       bool AllSame = true;
10662       for (unsigned i = 0; i != NumElts; ++i) {
10663         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10664           Base = V->getOperand(i);
10665           break;
10666         }
10667       }
10668       // Splat of <u, u, u, u>, return <u, u, u, u>
10669       if (!Base.getNode())
10670         return N0;
10671       for (unsigned i = 0; i != NumElts; ++i) {
10672         if (V->getOperand(i) != Base) {
10673           AllSame = false;
10674           break;
10675         }
10676       }
10677       // Splat of <x, x, x, x>, return <x, x, x, x>
10678       if (AllSame)
10679         return N0;
10680     }
10681   }
10682
10683   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10684       Level < AfterLegalizeVectorOps &&
10685       (N1.getOpcode() == ISD::UNDEF ||
10686       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10687        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10688     SDValue V = partitionShuffleOfConcats(N, DAG);
10689
10690     if (V.getNode())
10691       return V;
10692   }
10693
10694   // If this shuffle node is simply a swizzle of another shuffle node,
10695   // then try to simplify it.
10696   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10697       N1.getOpcode() == ISD::UNDEF) {
10698
10699     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10700
10701     // The incoming shuffle must be of the same type as the result of the
10702     // current shuffle.
10703     assert(OtherSV->getOperand(0).getValueType() == VT &&
10704            "Shuffle types don't match");
10705
10706     SmallVector<int, 4> Mask;
10707     // Compute the combined shuffle mask.
10708     for (unsigned i = 0; i != NumElts; ++i) {
10709       int Idx = SVN->getMaskElt(i);
10710       assert(Idx < (int)NumElts && "Index references undef operand");
10711       // Next, this index comes from the first value, which is the incoming
10712       // shuffle. Adopt the incoming index.
10713       if (Idx >= 0)
10714         Idx = OtherSV->getMaskElt(Idx);
10715       Mask.push_back(Idx);
10716     }
10717     
10718     bool CommuteOperands = false;
10719     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10720       // To be valid, the combine shuffle mask should only reference elements
10721       // from one of the two vectors in input to the inner shufflevector.
10722       bool IsValidMask = true;
10723       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10724         // See if the combined mask only reference undefs or elements coming
10725         // from the first shufflevector operand.
10726         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10727
10728       if (!IsValidMask) {
10729         IsValidMask = true;
10730         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10731           // Check that all the elements come from the second shuffle operand.
10732           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10733         CommuteOperands = IsValidMask;
10734       }
10735
10736       // Early exit if the combined shuffle mask is not valid.
10737       if (!IsValidMask)
10738         return SDValue();
10739     }
10740
10741     // See if this pair of shuffles can be safely folded according to either
10742     // of the following rules:
10743     //   shuffle(shuffle(x, y), undef) -> x
10744     //   shuffle(shuffle(x, undef), undef) -> x
10745     //   shuffle(shuffle(x, y), undef) -> y
10746     bool IsIdentityMask = true;
10747     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10748     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10749       // Skip Undefs.
10750       if (Mask[i] < 0)
10751         continue;
10752
10753       // The combined shuffle must map each index to itself.
10754       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10755     }
10756     
10757     if (IsIdentityMask) {
10758       if (CommuteOperands)
10759         // optimize shuffle(shuffle(x, y), undef) -> y.
10760         return OtherSV->getOperand(1);
10761       
10762       // optimize shuffle(shuffle(x, undef), undef) -> x
10763       // optimize shuffle(shuffle(x, y), undef) -> x
10764       return OtherSV->getOperand(0);
10765     }
10766
10767     // It may still be beneficial to combine the two shuffles if the
10768     // resulting shuffle is legal.
10769     if (TLI.isTypeLegal(VT) && TLI.isShuffleMaskLegal(Mask, VT)) {
10770       if (!CommuteOperands)
10771         // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10772         // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10773         return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10774                                     &Mask[0]);
10775       
10776       //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(undef, y, M3)
10777       return DAG.getVectorShuffle(VT, SDLoc(N), N1, N0->getOperand(1),
10778                                   &Mask[0]);
10779     }
10780   }
10781
10782   // Try to fold according to rules:
10783   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10784   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10785   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10786   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10787   // Don't try to fold shuffles with illegal type.
10788   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10789       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10790     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10791
10792     // The incoming shuffle must be of the same type as the result of the
10793     // current shuffle.
10794     assert(OtherSV->getOperand(0).getValueType() == VT &&
10795            "Shuffle types don't match");
10796
10797     SDValue SV0 = OtherSV->getOperand(0);
10798     SDValue SV1 = OtherSV->getOperand(1);
10799     bool HasSameOp0 = N1 == SV0;
10800     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10801     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10802       // Early exit.
10803       return SDValue();
10804
10805     SmallVector<int, 4> Mask;
10806     // Compute the combined shuffle mask for a shuffle with SV0 as the first
10807     // operand, and SV1 as the second operand.
10808     for (unsigned i = 0; i != NumElts; ++i) {
10809       int Idx = SVN->getMaskElt(i);
10810       if (Idx < 0) {
10811         // Propagate Undef.
10812         Mask.push_back(Idx);
10813         continue;
10814       }
10815
10816       if (Idx < (int)NumElts) {
10817         Idx = OtherSV->getMaskElt(Idx);
10818         if (IsSV1Undef && Idx >= (int) NumElts)
10819           Idx = -1;  // Propagate Undef.
10820       } else
10821         Idx = HasSameOp0 ? Idx - NumElts : Idx;
10822
10823       Mask.push_back(Idx);
10824     }
10825
10826     // Avoid introducing shuffles with illegal mask.
10827     if (TLI.isShuffleMaskLegal(Mask, VT)) {
10828       if (IsSV1Undef)
10829         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10830         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10831         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10832       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10833     }
10834   }
10835
10836   return SDValue();
10837 }
10838
10839 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10840   SDValue N0 = N->getOperand(0);
10841   SDValue N2 = N->getOperand(2);
10842
10843   // If the input vector is a concatenation, and the insert replaces
10844   // one of the halves, we can optimize into a single concat_vectors.
10845   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10846       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10847     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10848     EVT VT = N->getValueType(0);
10849
10850     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10851     // (concat_vectors Z, Y)
10852     if (InsIdx == 0)
10853       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10854                          N->getOperand(1), N0.getOperand(1));
10855
10856     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10857     // (concat_vectors X, Z)
10858     if (InsIdx == VT.getVectorNumElements()/2)
10859       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10860                          N0.getOperand(0), N->getOperand(1));
10861   }
10862
10863   return SDValue();
10864 }
10865
10866 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10867 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10868 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10869 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10870 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10871   EVT VT = N->getValueType(0);
10872   SDLoc dl(N);
10873   SDValue LHS = N->getOperand(0);
10874   SDValue RHS = N->getOperand(1);
10875   if (N->getOpcode() == ISD::AND) {
10876     if (RHS.getOpcode() == ISD::BITCAST)
10877       RHS = RHS.getOperand(0);
10878     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10879       SmallVector<int, 8> Indices;
10880       unsigned NumElts = RHS.getNumOperands();
10881       for (unsigned i = 0; i != NumElts; ++i) {
10882         SDValue Elt = RHS.getOperand(i);
10883         if (!isa<ConstantSDNode>(Elt))
10884           return SDValue();
10885
10886         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10887           Indices.push_back(i);
10888         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10889           Indices.push_back(NumElts);
10890         else
10891           return SDValue();
10892       }
10893
10894       // Let's see if the target supports this vector_shuffle.
10895       EVT RVT = RHS.getValueType();
10896       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10897         return SDValue();
10898
10899       // Return the new VECTOR_SHUFFLE node.
10900       EVT EltVT = RVT.getVectorElementType();
10901       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10902                                      DAG.getConstant(0, EltVT));
10903       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10904       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10905       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10906       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10907     }
10908   }
10909
10910   return SDValue();
10911 }
10912
10913 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10914 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10915   assert(N->getValueType(0).isVector() &&
10916          "SimplifyVBinOp only works on vectors!");
10917
10918   SDValue LHS = N->getOperand(0);
10919   SDValue RHS = N->getOperand(1);
10920   SDValue Shuffle = XformToShuffleWithZero(N);
10921   if (Shuffle.getNode()) return Shuffle;
10922
10923   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10924   // this operation.
10925   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10926       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10927     // Check if both vectors are constants. If not bail out.
10928     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10929           cast<BuildVectorSDNode>(RHS)->isConstant()))
10930       return SDValue();
10931
10932     SmallVector<SDValue, 8> Ops;
10933     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10934       SDValue LHSOp = LHS.getOperand(i);
10935       SDValue RHSOp = RHS.getOperand(i);
10936
10937       // Can't fold divide by zero.
10938       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10939           N->getOpcode() == ISD::FDIV) {
10940         if ((RHSOp.getOpcode() == ISD::Constant &&
10941              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10942             (RHSOp.getOpcode() == ISD::ConstantFP &&
10943              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10944           break;
10945       }
10946
10947       EVT VT = LHSOp.getValueType();
10948       EVT RVT = RHSOp.getValueType();
10949       if (RVT != VT) {
10950         // Integer BUILD_VECTOR operands may have types larger than the element
10951         // size (e.g., when the element type is not legal).  Prior to type
10952         // legalization, the types may not match between the two BUILD_VECTORS.
10953         // Truncate one of the operands to make them match.
10954         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10955           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10956         } else {
10957           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10958           VT = RVT;
10959         }
10960       }
10961       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10962                                    LHSOp, RHSOp);
10963       if (FoldOp.getOpcode() != ISD::UNDEF &&
10964           FoldOp.getOpcode() != ISD::Constant &&
10965           FoldOp.getOpcode() != ISD::ConstantFP)
10966         break;
10967       Ops.push_back(FoldOp);
10968       AddToWorkList(FoldOp.getNode());
10969     }
10970
10971     if (Ops.size() == LHS.getNumOperands())
10972       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
10973   }
10974
10975   // Type legalization might introduce new shuffles in the DAG.
10976   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
10977   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
10978   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
10979       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
10980       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
10981       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
10982     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
10983     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
10984
10985     if (SVN0->getMask().equals(SVN1->getMask())) {
10986       EVT VT = N->getValueType(0);
10987       SDValue UndefVector = LHS.getOperand(1);
10988       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10989                                      LHS.getOperand(0), RHS.getOperand(0));
10990       AddUsersToWorkList(N);
10991       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
10992                                   &SVN0->getMask()[0]);
10993     }
10994   }
10995
10996   return SDValue();
10997 }
10998
10999 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
11000 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11001   assert(N->getValueType(0).isVector() &&
11002          "SimplifyVUnaryOp only works on vectors!");
11003
11004   SDValue N0 = N->getOperand(0);
11005
11006   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11007     return SDValue();
11008
11009   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11010   SmallVector<SDValue, 8> Ops;
11011   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11012     SDValue Op = N0.getOperand(i);
11013     if (Op.getOpcode() != ISD::UNDEF &&
11014         Op.getOpcode() != ISD::ConstantFP)
11015       break;
11016     EVT EltVT = Op.getValueType();
11017     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11018     if (FoldOp.getOpcode() != ISD::UNDEF &&
11019         FoldOp.getOpcode() != ISD::ConstantFP)
11020       break;
11021     Ops.push_back(FoldOp);
11022     AddToWorkList(FoldOp.getNode());
11023   }
11024
11025   if (Ops.size() != N0.getNumOperands())
11026     return SDValue();
11027
11028   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11029 }
11030
11031 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11032                                     SDValue N1, SDValue N2){
11033   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11034
11035   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11036                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11037
11038   // If we got a simplified select_cc node back from SimplifySelectCC, then
11039   // break it down into a new SETCC node, and a new SELECT node, and then return
11040   // the SELECT node, since we were called with a SELECT node.
11041   if (SCC.getNode()) {
11042     // Check to see if we got a select_cc back (to turn into setcc/select).
11043     // Otherwise, just return whatever node we got back, like fabs.
11044     if (SCC.getOpcode() == ISD::SELECT_CC) {
11045       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11046                                   N0.getValueType(),
11047                                   SCC.getOperand(0), SCC.getOperand(1),
11048                                   SCC.getOperand(4));
11049       AddToWorkList(SETCC.getNode());
11050       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
11051                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
11052     }
11053
11054     return SCC;
11055   }
11056   return SDValue();
11057 }
11058
11059 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11060 /// are the two values being selected between, see if we can simplify the
11061 /// select.  Callers of this should assume that TheSelect is deleted if this
11062 /// returns true.  As such, they should return the appropriate thing (e.g. the
11063 /// node) back to the top-level of the DAG combiner loop to avoid it being
11064 /// looked at.
11065 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11066                                     SDValue RHS) {
11067
11068   // Cannot simplify select with vector condition
11069   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11070
11071   // If this is a select from two identical things, try to pull the operation
11072   // through the select.
11073   if (LHS.getOpcode() != RHS.getOpcode() ||
11074       !LHS.hasOneUse() || !RHS.hasOneUse())
11075     return false;
11076
11077   // If this is a load and the token chain is identical, replace the select
11078   // of two loads with a load through a select of the address to load from.
11079   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11080   // constants have been dropped into the constant pool.
11081   if (LHS.getOpcode() == ISD::LOAD) {
11082     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11083     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11084
11085     // Token chains must be identical.
11086     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11087         // Do not let this transformation reduce the number of volatile loads.
11088         LLD->isVolatile() || RLD->isVolatile() ||
11089         // If this is an EXTLOAD, the VT's must match.
11090         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11091         // If this is an EXTLOAD, the kind of extension must match.
11092         (LLD->getExtensionType() != RLD->getExtensionType() &&
11093          // The only exception is if one of the extensions is anyext.
11094          LLD->getExtensionType() != ISD::EXTLOAD &&
11095          RLD->getExtensionType() != ISD::EXTLOAD) ||
11096         // FIXME: this discards src value information.  This is
11097         // over-conservative. It would be beneficial to be able to remember
11098         // both potential memory locations.  Since we are discarding
11099         // src value info, don't do the transformation if the memory
11100         // locations are not in the default address space.
11101         LLD->getPointerInfo().getAddrSpace() != 0 ||
11102         RLD->getPointerInfo().getAddrSpace() != 0 ||
11103         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11104                                       LLD->getBasePtr().getValueType()))
11105       return false;
11106
11107     // Check that the select condition doesn't reach either load.  If so,
11108     // folding this will induce a cycle into the DAG.  If not, this is safe to
11109     // xform, so create a select of the addresses.
11110     SDValue Addr;
11111     if (TheSelect->getOpcode() == ISD::SELECT) {
11112       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11113       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11114           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11115         return false;
11116       // The loads must not depend on one another.
11117       if (LLD->isPredecessorOf(RLD) ||
11118           RLD->isPredecessorOf(LLD))
11119         return false;
11120       Addr = DAG.getSelect(SDLoc(TheSelect),
11121                            LLD->getBasePtr().getValueType(),
11122                            TheSelect->getOperand(0), LLD->getBasePtr(),
11123                            RLD->getBasePtr());
11124     } else {  // Otherwise SELECT_CC
11125       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11126       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11127
11128       if ((LLD->hasAnyUseOfValue(1) &&
11129            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11130           (RLD->hasAnyUseOfValue(1) &&
11131            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11132         return false;
11133
11134       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11135                          LLD->getBasePtr().getValueType(),
11136                          TheSelect->getOperand(0),
11137                          TheSelect->getOperand(1),
11138                          LLD->getBasePtr(), RLD->getBasePtr(),
11139                          TheSelect->getOperand(4));
11140     }
11141
11142     SDValue Load;
11143     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11144       Load = DAG.getLoad(TheSelect->getValueType(0),
11145                          SDLoc(TheSelect),
11146                          // FIXME: Discards pointer and TBAA info.
11147                          LLD->getChain(), Addr, MachinePointerInfo(),
11148                          LLD->isVolatile(), LLD->isNonTemporal(),
11149                          LLD->isInvariant(), LLD->getAlignment());
11150     } else {
11151       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11152                             RLD->getExtensionType() : LLD->getExtensionType(),
11153                             SDLoc(TheSelect),
11154                             TheSelect->getValueType(0),
11155                             // FIXME: Discards pointer and TBAA info.
11156                             LLD->getChain(), Addr, MachinePointerInfo(),
11157                             LLD->getMemoryVT(), LLD->isVolatile(),
11158                             LLD->isNonTemporal(), LLD->getAlignment());
11159     }
11160
11161     // Users of the select now use the result of the load.
11162     CombineTo(TheSelect, Load);
11163
11164     // Users of the old loads now use the new load's chain.  We know the
11165     // old-load value is dead now.
11166     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11167     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11168     return true;
11169   }
11170
11171   return false;
11172 }
11173
11174 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11175 /// where 'cond' is the comparison specified by CC.
11176 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11177                                       SDValue N2, SDValue N3,
11178                                       ISD::CondCode CC, bool NotExtCompare) {
11179   // (x ? y : y) -> y.
11180   if (N2 == N3) return N2;
11181
11182   EVT VT = N2.getValueType();
11183   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11184   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11185   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11186
11187   // Determine if the condition we're dealing with is constant
11188   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11189                               N0, N1, CC, DL, false);
11190   if (SCC.getNode()) AddToWorkList(SCC.getNode());
11191   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11192
11193   // fold select_cc true, x, y -> x
11194   if (SCCC && !SCCC->isNullValue())
11195     return N2;
11196   // fold select_cc false, x, y -> y
11197   if (SCCC && SCCC->isNullValue())
11198     return N3;
11199
11200   // Check to see if we can simplify the select into an fabs node
11201   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11202     // Allow either -0.0 or 0.0
11203     if (CFP->getValueAPF().isZero()) {
11204       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11205       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11206           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11207           N2 == N3.getOperand(0))
11208         return DAG.getNode(ISD::FABS, DL, VT, N0);
11209
11210       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11211       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11212           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11213           N2.getOperand(0) == N3)
11214         return DAG.getNode(ISD::FABS, DL, VT, N3);
11215     }
11216   }
11217
11218   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11219   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11220   // in it.  This is a win when the constant is not otherwise available because
11221   // it replaces two constant pool loads with one.  We only do this if the FP
11222   // type is known to be legal, because if it isn't, then we are before legalize
11223   // types an we want the other legalization to happen first (e.g. to avoid
11224   // messing with soft float) and if the ConstantFP is not legal, because if
11225   // it is legal, we may not need to store the FP constant in a constant pool.
11226   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11227     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11228       if (TLI.isTypeLegal(N2.getValueType()) &&
11229           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11230                TargetLowering::Legal &&
11231            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11232            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11233           // If both constants have multiple uses, then we won't need to do an
11234           // extra load, they are likely around in registers for other users.
11235           (TV->hasOneUse() || FV->hasOneUse())) {
11236         Constant *Elts[] = {
11237           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11238           const_cast<ConstantFP*>(TV->getConstantFPValue())
11239         };
11240         Type *FPTy = Elts[0]->getType();
11241         const DataLayout &TD = *TLI.getDataLayout();
11242
11243         // Create a ConstantArray of the two constants.
11244         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11245         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11246                                             TD.getPrefTypeAlignment(FPTy));
11247         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11248
11249         // Get the offsets to the 0 and 1 element of the array so that we can
11250         // select between them.
11251         SDValue Zero = DAG.getIntPtrConstant(0);
11252         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11253         SDValue One = DAG.getIntPtrConstant(EltSize);
11254
11255         SDValue Cond = DAG.getSetCC(DL,
11256                                     getSetCCResultType(N0.getValueType()),
11257                                     N0, N1, CC);
11258         AddToWorkList(Cond.getNode());
11259         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11260                                           Cond, One, Zero);
11261         AddToWorkList(CstOffset.getNode());
11262         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11263                             CstOffset);
11264         AddToWorkList(CPIdx.getNode());
11265         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11266                            MachinePointerInfo::getConstantPool(), false,
11267                            false, false, Alignment);
11268
11269       }
11270     }
11271
11272   // Check to see if we can perform the "gzip trick", transforming
11273   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11274   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11275       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11276        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11277     EVT XType = N0.getValueType();
11278     EVT AType = N2.getValueType();
11279     if (XType.bitsGE(AType)) {
11280       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11281       // single-bit constant.
11282       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11283         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11284         ShCtV = XType.getSizeInBits()-ShCtV-1;
11285         SDValue ShCt = DAG.getConstant(ShCtV,
11286                                        getShiftAmountTy(N0.getValueType()));
11287         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11288                                     XType, N0, ShCt);
11289         AddToWorkList(Shift.getNode());
11290
11291         if (XType.bitsGT(AType)) {
11292           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11293           AddToWorkList(Shift.getNode());
11294         }
11295
11296         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11297       }
11298
11299       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11300                                   XType, N0,
11301                                   DAG.getConstant(XType.getSizeInBits()-1,
11302                                          getShiftAmountTy(N0.getValueType())));
11303       AddToWorkList(Shift.getNode());
11304
11305       if (XType.bitsGT(AType)) {
11306         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11307         AddToWorkList(Shift.getNode());
11308       }
11309
11310       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11311     }
11312   }
11313
11314   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11315   // where y is has a single bit set.
11316   // A plaintext description would be, we can turn the SELECT_CC into an AND
11317   // when the condition can be materialized as an all-ones register.  Any
11318   // single bit-test can be materialized as an all-ones register with
11319   // shift-left and shift-right-arith.
11320   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11321       N0->getValueType(0) == VT &&
11322       N1C && N1C->isNullValue() &&
11323       N2C && N2C->isNullValue()) {
11324     SDValue AndLHS = N0->getOperand(0);
11325     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11326     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11327       // Shift the tested bit over the sign bit.
11328       APInt AndMask = ConstAndRHS->getAPIntValue();
11329       SDValue ShlAmt =
11330         DAG.getConstant(AndMask.countLeadingZeros(),
11331                         getShiftAmountTy(AndLHS.getValueType()));
11332       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11333
11334       // Now arithmetic right shift it all the way over, so the result is either
11335       // all-ones, or zero.
11336       SDValue ShrAmt =
11337         DAG.getConstant(AndMask.getBitWidth()-1,
11338                         getShiftAmountTy(Shl.getValueType()));
11339       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11340
11341       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11342     }
11343   }
11344
11345   // fold select C, 16, 0 -> shl C, 4
11346   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11347       TLI.getBooleanContents(N0.getValueType()) ==
11348           TargetLowering::ZeroOrOneBooleanContent) {
11349
11350     // If the caller doesn't want us to simplify this into a zext of a compare,
11351     // don't do it.
11352     if (NotExtCompare && N2C->getAPIntValue() == 1)
11353       return SDValue();
11354
11355     // Get a SetCC of the condition
11356     // NOTE: Don't create a SETCC if it's not legal on this target.
11357     if (!LegalOperations ||
11358         TLI.isOperationLegal(ISD::SETCC,
11359           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11360       SDValue Temp, SCC;
11361       // cast from setcc result type to select result type
11362       if (LegalTypes) {
11363         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11364                             N0, N1, CC);
11365         if (N2.getValueType().bitsLT(SCC.getValueType()))
11366           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11367                                         N2.getValueType());
11368         else
11369           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11370                              N2.getValueType(), SCC);
11371       } else {
11372         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11373         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11374                            N2.getValueType(), SCC);
11375       }
11376
11377       AddToWorkList(SCC.getNode());
11378       AddToWorkList(Temp.getNode());
11379
11380       if (N2C->getAPIntValue() == 1)
11381         return Temp;
11382
11383       // shl setcc result by log2 n2c
11384       return DAG.getNode(
11385           ISD::SHL, DL, N2.getValueType(), Temp,
11386           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11387                           getShiftAmountTy(Temp.getValueType())));
11388     }
11389   }
11390
11391   // Check to see if this is the equivalent of setcc
11392   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11393   // otherwise, go ahead with the folds.
11394   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11395     EVT XType = N0.getValueType();
11396     if (!LegalOperations ||
11397         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11398       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11399       if (Res.getValueType() != VT)
11400         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11401       return Res;
11402     }
11403
11404     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11405     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11406         (!LegalOperations ||
11407          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11408       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11409       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11410                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11411                                        getShiftAmountTy(Ctlz.getValueType())));
11412     }
11413     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11414     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11415       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11416                                   XType, DAG.getConstant(0, XType), N0);
11417       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11418       return DAG.getNode(ISD::SRL, DL, XType,
11419                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11420                          DAG.getConstant(XType.getSizeInBits()-1,
11421                                          getShiftAmountTy(XType)));
11422     }
11423     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11424     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11425       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11426                                  DAG.getConstant(XType.getSizeInBits()-1,
11427                                          getShiftAmountTy(N0.getValueType())));
11428       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11429     }
11430   }
11431
11432   // Check to see if this is an integer abs.
11433   // select_cc setg[te] X,  0,  X, -X ->
11434   // select_cc setgt    X, -1,  X, -X ->
11435   // select_cc setl[te] X,  0, -X,  X ->
11436   // select_cc setlt    X,  1, -X,  X ->
11437   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11438   if (N1C) {
11439     ConstantSDNode *SubC = nullptr;
11440     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11441          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11442         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11443       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11444     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11445               (N1C->isOne() && CC == ISD::SETLT)) &&
11446              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11447       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11448
11449     EVT XType = N0.getValueType();
11450     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11451       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11452                                   N0,
11453                                   DAG.getConstant(XType.getSizeInBits()-1,
11454                                          getShiftAmountTy(N0.getValueType())));
11455       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11456                                 XType, N0, Shift);
11457       AddToWorkList(Shift.getNode());
11458       AddToWorkList(Add.getNode());
11459       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11460     }
11461   }
11462
11463   return SDValue();
11464 }
11465
11466 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11467 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11468                                    SDValue N1, ISD::CondCode Cond,
11469                                    SDLoc DL, bool foldBooleans) {
11470   TargetLowering::DAGCombinerInfo
11471     DagCombineInfo(DAG, Level, false, this);
11472   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11473 }
11474
11475 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11476 /// return a DAG expression to select that will generate the same value by
11477 /// multiplying by a magic number.  See:
11478 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11479 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11480   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11481   if (!C)
11482     return SDValue();
11483
11484   // Avoid division by zero.
11485   if (!C->getAPIntValue())
11486     return SDValue();
11487
11488   std::vector<SDNode*> Built;
11489   SDValue S =
11490       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11491
11492   for (SDNode *N : Built)
11493     AddToWorkList(N);
11494   return S;
11495 }
11496
11497 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11498 /// return a DAG expression to select that will generate the same value by
11499 /// multiplying by a magic number.  See:
11500 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11501 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11502   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11503   if (!C)
11504     return SDValue();
11505
11506   // Avoid division by zero.
11507   if (!C->getAPIntValue())
11508     return SDValue();
11509
11510   std::vector<SDNode*> Built;
11511   SDValue S =
11512       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11513
11514   for (SDNode *N : Built)
11515     AddToWorkList(N);
11516   return S;
11517 }
11518
11519 /// FindBaseOffset - Return true if base is a frame index, which is known not
11520 // to alias with anything but itself.  Provides base object and offset as
11521 // results.
11522 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11523                            const GlobalValue *&GV, const void *&CV) {
11524   // Assume it is a primitive operation.
11525   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11526
11527   // If it's an adding a simple constant then integrate the offset.
11528   if (Base.getOpcode() == ISD::ADD) {
11529     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11530       Base = Base.getOperand(0);
11531       Offset += C->getZExtValue();
11532     }
11533   }
11534
11535   // Return the underlying GlobalValue, and update the Offset.  Return false
11536   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11537   // by multiple nodes with different offsets.
11538   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11539     GV = G->getGlobal();
11540     Offset += G->getOffset();
11541     return false;
11542   }
11543
11544   // Return the underlying Constant value, and update the Offset.  Return false
11545   // for ConstantSDNodes since the same constant pool entry may be represented
11546   // by multiple nodes with different offsets.
11547   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11548     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11549                                          : (const void *)C->getConstVal();
11550     Offset += C->getOffset();
11551     return false;
11552   }
11553   // If it's any of the following then it can't alias with anything but itself.
11554   return isa<FrameIndexSDNode>(Base);
11555 }
11556
11557 /// isAlias - Return true if there is any possibility that the two addresses
11558 /// overlap.
11559 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11560   // If they are the same then they must be aliases.
11561   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11562
11563   // If they are both volatile then they cannot be reordered.
11564   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11565
11566   // Gather base node and offset information.
11567   SDValue Base1, Base2;
11568   int64_t Offset1, Offset2;
11569   const GlobalValue *GV1, *GV2;
11570   const void *CV1, *CV2;
11571   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11572                                       Base1, Offset1, GV1, CV1);
11573   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11574                                       Base2, Offset2, GV2, CV2);
11575
11576   // If they have a same base address then check to see if they overlap.
11577   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11578     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11579              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11580
11581   // It is possible for different frame indices to alias each other, mostly
11582   // when tail call optimization reuses return address slots for arguments.
11583   // To catch this case, look up the actual index of frame indices to compute
11584   // the real alias relationship.
11585   if (isFrameIndex1 && isFrameIndex2) {
11586     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11587     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11588     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11589     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11590              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11591   }
11592
11593   // Otherwise, if we know what the bases are, and they aren't identical, then
11594   // we know they cannot alias.
11595   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11596     return false;
11597
11598   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11599   // compared to the size and offset of the access, we may be able to prove they
11600   // do not alias.  This check is conservative for now to catch cases created by
11601   // splitting vector types.
11602   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11603       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11604       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11605        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11606       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11607     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11608     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11609
11610     // There is no overlap between these relatively aligned accesses of similar
11611     // size, return no alias.
11612     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11613         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11614       return false;
11615   }
11616
11617   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11618     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11619 #ifndef NDEBUG
11620   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11621       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11622     UseAA = false;
11623 #endif
11624   if (UseAA &&
11625       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11626     // Use alias analysis information.
11627     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11628                                  Op1->getSrcValueOffset());
11629     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11630         Op0->getSrcValueOffset() - MinOffset;
11631     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11632         Op1->getSrcValueOffset() - MinOffset;
11633     AliasAnalysis::AliasResult AAResult =
11634         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11635                                          Overlap1,
11636                                          UseTBAA ? Op0->getTBAAInfo() : nullptr),
11637                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11638                                          Overlap2,
11639                                          UseTBAA ? Op1->getTBAAInfo() : nullptr));
11640     if (AAResult == AliasAnalysis::NoAlias)
11641       return false;
11642   }
11643
11644   // Otherwise we have to assume they alias.
11645   return true;
11646 }
11647
11648 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11649 /// looking for aliasing nodes and adding them to the Aliases vector.
11650 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11651                                    SmallVectorImpl<SDValue> &Aliases) {
11652   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11653   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11654
11655   // Get alias information for node.
11656   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11657
11658   // Starting off.
11659   Chains.push_back(OriginalChain);
11660   unsigned Depth = 0;
11661
11662   // Look at each chain and determine if it is an alias.  If so, add it to the
11663   // aliases list.  If not, then continue up the chain looking for the next
11664   // candidate.
11665   while (!Chains.empty()) {
11666     SDValue Chain = Chains.back();
11667     Chains.pop_back();
11668
11669     // For TokenFactor nodes, look at each operand and only continue up the
11670     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11671     // find more and revert to original chain since the xform is unlikely to be
11672     // profitable.
11673     //
11674     // FIXME: The depth check could be made to return the last non-aliasing
11675     // chain we found before we hit a tokenfactor rather than the original
11676     // chain.
11677     if (Depth > 6 || Aliases.size() == 2) {
11678       Aliases.clear();
11679       Aliases.push_back(OriginalChain);
11680       return;
11681     }
11682
11683     // Don't bother if we've been before.
11684     if (!Visited.insert(Chain.getNode()))
11685       continue;
11686
11687     switch (Chain.getOpcode()) {
11688     case ISD::EntryToken:
11689       // Entry token is ideal chain operand, but handled in FindBetterChain.
11690       break;
11691
11692     case ISD::LOAD:
11693     case ISD::STORE: {
11694       // Get alias information for Chain.
11695       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11696           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11697
11698       // If chain is alias then stop here.
11699       if (!(IsLoad && IsOpLoad) &&
11700           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11701         Aliases.push_back(Chain);
11702       } else {
11703         // Look further up the chain.
11704         Chains.push_back(Chain.getOperand(0));
11705         ++Depth;
11706       }
11707       break;
11708     }
11709
11710     case ISD::TokenFactor:
11711       // We have to check each of the operands of the token factor for "small"
11712       // token factors, so we queue them up.  Adding the operands to the queue
11713       // (stack) in reverse order maintains the original order and increases the
11714       // likelihood that getNode will find a matching token factor (CSE.)
11715       if (Chain.getNumOperands() > 16) {
11716         Aliases.push_back(Chain);
11717         break;
11718       }
11719       for (unsigned n = Chain.getNumOperands(); n;)
11720         Chains.push_back(Chain.getOperand(--n));
11721       ++Depth;
11722       break;
11723
11724     default:
11725       // For all other instructions we will just have to take what we can get.
11726       Aliases.push_back(Chain);
11727       break;
11728     }
11729   }
11730
11731   // We need to be careful here to also search for aliases through the
11732   // value operand of a store, etc. Consider the following situation:
11733   //   Token1 = ...
11734   //   L1 = load Token1, %52
11735   //   S1 = store Token1, L1, %51
11736   //   L2 = load Token1, %52+8
11737   //   S2 = store Token1, L2, %51+8
11738   //   Token2 = Token(S1, S2)
11739   //   L3 = load Token2, %53
11740   //   S3 = store Token2, L3, %52
11741   //   L4 = load Token2, %53+8
11742   //   S4 = store Token2, L4, %52+8
11743   // If we search for aliases of S3 (which loads address %52), and we look
11744   // only through the chain, then we'll miss the trivial dependence on L1
11745   // (which also loads from %52). We then might change all loads and
11746   // stores to use Token1 as their chain operand, which could result in
11747   // copying %53 into %52 before copying %52 into %51 (which should
11748   // happen first).
11749   //
11750   // The problem is, however, that searching for such data dependencies
11751   // can become expensive, and the cost is not directly related to the
11752   // chain depth. Instead, we'll rule out such configurations here by
11753   // insisting that we've visited all chain users (except for users
11754   // of the original chain, which is not necessary). When doing this,
11755   // we need to look through nodes we don't care about (otherwise, things
11756   // like register copies will interfere with trivial cases).
11757
11758   SmallVector<const SDNode *, 16> Worklist;
11759   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11760        IE = Visited.end(); I != IE; ++I)
11761     if (*I != OriginalChain.getNode())
11762       Worklist.push_back(*I);
11763
11764   while (!Worklist.empty()) {
11765     const SDNode *M = Worklist.pop_back_val();
11766
11767     // We have already visited M, and want to make sure we've visited any uses
11768     // of M that we care about. For uses that we've not visisted, and don't
11769     // care about, queue them to the worklist.
11770
11771     for (SDNode::use_iterator UI = M->use_begin(),
11772          UIE = M->use_end(); UI != UIE; ++UI)
11773       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11774         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11775           // We've not visited this use, and we care about it (it could have an
11776           // ordering dependency with the original node).
11777           Aliases.clear();
11778           Aliases.push_back(OriginalChain);
11779           return;
11780         }
11781
11782         // We've not visited this use, but we don't care about it. Mark it as
11783         // visited and enqueue it to the worklist.
11784         Worklist.push_back(*UI);
11785       }
11786   }
11787 }
11788
11789 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11790 /// for a better chain (aliasing node.)
11791 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11792   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11793
11794   // Accumulate all the aliases to this node.
11795   GatherAllAliases(N, OldChain, Aliases);
11796
11797   // If no operands then chain to entry token.
11798   if (Aliases.size() == 0)
11799     return DAG.getEntryNode();
11800
11801   // If a single operand then chain to it.  We don't need to revisit it.
11802   if (Aliases.size() == 1)
11803     return Aliases[0];
11804
11805   // Construct a custom tailored token factor.
11806   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11807 }
11808
11809 // SelectionDAG::Combine - This is the entry point for the file.
11810 //
11811 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11812                            CodeGenOpt::Level OptLevel) {
11813   /// run - This is the main entry point to this class.
11814   ///
11815   DAGCombiner(*this, AA, OptLevel).Run(Level);
11816 }