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