comment cleanup; NFC
[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/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitAND(SDNode *N);
249     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250     SDValue visitOR(SDNode *N);
251     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252     SDValue visitXOR(SDNode *N);
253     SDValue SimplifyVBinOp(SDNode *N);
254     SDValue visitSHL(SDNode *N);
255     SDValue visitSRA(SDNode *N);
256     SDValue visitSRL(SDNode *N);
257     SDValue visitRotate(SDNode *N);
258     SDValue visitCTLZ(SDNode *N);
259     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
260     SDValue visitCTTZ(SDNode *N);
261     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
262     SDValue visitCTPOP(SDNode *N);
263     SDValue visitSELECT(SDNode *N);
264     SDValue visitVSELECT(SDNode *N);
265     SDValue visitSELECT_CC(SDNode *N);
266     SDValue visitSETCC(SDNode *N);
267     SDValue visitSIGN_EXTEND(SDNode *N);
268     SDValue visitZERO_EXTEND(SDNode *N);
269     SDValue visitANY_EXTEND(SDNode *N);
270     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271     SDValue visitTRUNCATE(SDNode *N);
272     SDValue visitBITCAST(SDNode *N);
273     SDValue visitBUILD_PAIR(SDNode *N);
274     SDValue visitFADD(SDNode *N);
275     SDValue visitFSUB(SDNode *N);
276     SDValue visitFMUL(SDNode *N);
277     SDValue visitFMA(SDNode *N);
278     SDValue visitFDIV(SDNode *N);
279     SDValue visitFREM(SDNode *N);
280     SDValue visitFSQRT(SDNode *N);
281     SDValue visitFCOPYSIGN(SDNode *N);
282     SDValue visitSINT_TO_FP(SDNode *N);
283     SDValue visitUINT_TO_FP(SDNode *N);
284     SDValue visitFP_TO_SINT(SDNode *N);
285     SDValue visitFP_TO_UINT(SDNode *N);
286     SDValue visitFP_ROUND(SDNode *N);
287     SDValue visitFP_ROUND_INREG(SDNode *N);
288     SDValue visitFP_EXTEND(SDNode *N);
289     SDValue visitFNEG(SDNode *N);
290     SDValue visitFABS(SDNode *N);
291     SDValue visitFCEIL(SDNode *N);
292     SDValue visitFTRUNC(SDNode *N);
293     SDValue visitFFLOOR(SDNode *N);
294     SDValue visitFMINNUM(SDNode *N);
295     SDValue visitFMAXNUM(SDNode *N);
296     SDValue visitBRCOND(SDNode *N);
297     SDValue visitBR_CC(SDNode *N);
298     SDValue visitLOAD(SDNode *N);
299     SDValue visitSTORE(SDNode *N);
300     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
301     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
302     SDValue visitBUILD_VECTOR(SDNode *N);
303     SDValue visitCONCAT_VECTORS(SDNode *N);
304     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
305     SDValue visitVECTOR_SHUFFLE(SDNode *N);
306     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
307     SDValue visitINSERT_SUBVECTOR(SDNode *N);
308     SDValue visitMLOAD(SDNode *N);
309     SDValue visitMSTORE(SDNode *N);
310
311     SDValue XformToShuffleWithZero(SDNode *N);
312     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
313
314     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
315
316     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
317     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
318     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
319     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
320                              SDValue N3, ISD::CondCode CC,
321                              bool NotExtCompare = false);
322     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
323                           SDLoc DL, bool foldBooleans = true);
324
325     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
326                            SDValue &CC) const;
327     bool isOneUseSetCC(SDValue N) const;
328
329     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
330                                          unsigned HiOp);
331     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
332     SDValue CombineExtLoad(SDNode *N);
333     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
334     SDValue BuildSDIV(SDNode *N);
335     SDValue BuildSDIVPow2(SDNode *N);
336     SDValue BuildUDIV(SDNode *N);
337     SDValue BuildReciprocalEstimate(SDValue Op);
338     SDValue BuildRsqrtEstimate(SDValue Op);
339     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
340     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
341     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
342                                bool DemandHighBits = true);
343     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
344     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
345                               SDValue InnerPos, SDValue InnerNeg,
346                               unsigned PosOpcode, unsigned NegOpcode,
347                               SDLoc DL);
348     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
349     SDValue ReduceLoadWidth(SDNode *N);
350     SDValue ReduceLoadOpStoreWidth(SDNode *N);
351     SDValue TransformFPLoadStorePair(SDNode *N);
352     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
353     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
354
355     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
356
357     /// Walk up chain skipping non-aliasing memory nodes,
358     /// looking for aliasing nodes and adding them to the Aliases vector.
359     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
360                           SmallVectorImpl<SDValue> &Aliases);
361
362     /// Return true if there is any possibility that the two addresses overlap.
363     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
364
365     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
366     /// chain (aliasing node.)
367     SDValue FindBetterChain(SDNode *N, SDValue Chain);
368
369     /// Holds a pointer to an LSBaseSDNode as well as information on where it
370     /// is located in a sequence of memory operations connected by a chain.
371     struct MemOpLink {
372       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
373       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
374       // Ptr to the mem node.
375       LSBaseSDNode *MemNode;
376       // Offset from the base ptr.
377       int64_t OffsetFromBase;
378       // What is the sequence number of this mem node.
379       // Lowest mem operand in the DAG starts at zero.
380       unsigned SequenceNum;
381     };
382
383     /// This is a helper function for MergeConsecutiveStores. When the source
384     /// elements of the consecutive stores are all constants or all extracted
385     /// vector elements, try to merge them into one larger store.
386     /// \return True if a merged store was created.
387     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
388                                          EVT MemVT, unsigned NumElem,
389                                          bool IsConstantSrc, bool UseVector);
390
391     /// Merge consecutive store operations into a wide store.
392     /// This optimization uses wide integers or vectors when possible.
393     /// \return True if some memory operations were changed.
394     bool MergeConsecutiveStores(StoreSDNode *N);
395
396     /// \brief Try to transform a truncation where C is a constant:
397     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
398     ///
399     /// \p N needs to be a truncation and its first operand an AND. Other
400     /// requirements are checked by the function (e.g. that trunc is
401     /// single-use) and if missed an empty SDValue is returned.
402     SDValue distributeTruncateThroughAnd(SDNode *N);
403
404   public:
405     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
406         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
407           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
408       auto *F = DAG.getMachineFunction().getFunction();
409       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
410                     F->hasFnAttribute(Attribute::MinSize);
411     }
412
413     /// Runs the dag combiner on all nodes in the work list
414     void Run(CombineLevel AtLevel);
415
416     SelectionDAG &getDAG() const { return DAG; }
417
418     /// Returns a type large enough to hold any valid shift amount - before type
419     /// legalization these can be huge.
420     EVT getShiftAmountTy(EVT LHSTy) {
421       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
422       if (LHSTy.isVector())
423         return LHSTy;
424       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
425                         : TLI.getPointerTy();
426     }
427
428     /// This method returns true if we are running before type legalization or
429     /// if the specified VT is legal.
430     bool isTypeLegal(const EVT &VT) {
431       if (!LegalTypes) return true;
432       return TLI.isTypeLegal(VT);
433     }
434
435     /// Convenience wrapper around TargetLowering::getSetCCResultType
436     EVT getSetCCResultType(EVT VT) const {
437       return TLI.getSetCCResultType(*DAG.getContext(), VT);
438     }
439   };
440 }
441
442
443 namespace {
444 /// This class is a DAGUpdateListener that removes any deleted
445 /// nodes from the worklist.
446 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
447   DAGCombiner &DC;
448 public:
449   explicit WorklistRemover(DAGCombiner &dc)
450     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
451
452   void NodeDeleted(SDNode *N, SDNode *E) override {
453     DC.removeFromWorklist(N);
454   }
455 };
456 }
457
458 //===----------------------------------------------------------------------===//
459 //  TargetLowering::DAGCombinerInfo implementation
460 //===----------------------------------------------------------------------===//
461
462 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
463   ((DAGCombiner*)DC)->AddToWorklist(N);
464 }
465
466 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
467   ((DAGCombiner*)DC)->removeFromWorklist(N);
468 }
469
470 SDValue TargetLowering::DAGCombinerInfo::
471 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
472   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
473 }
474
475 SDValue TargetLowering::DAGCombinerInfo::
476 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
477   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
478 }
479
480
481 SDValue TargetLowering::DAGCombinerInfo::
482 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
483   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
484 }
485
486 void TargetLowering::DAGCombinerInfo::
487 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
488   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
489 }
490
491 //===----------------------------------------------------------------------===//
492 // Helper Functions
493 //===----------------------------------------------------------------------===//
494
495 void DAGCombiner::deleteAndRecombine(SDNode *N) {
496   removeFromWorklist(N);
497
498   // If the operands of this node are only used by the node, they will now be
499   // dead. Make sure to re-visit them and recursively delete dead nodes.
500   for (const SDValue &Op : N->ops())
501     // For an operand generating multiple values, one of the values may
502     // become dead allowing further simplification (e.g. split index
503     // arithmetic from an indexed load).
504     if (Op->hasOneUse() || Op->getNumValues() > 1)
505       AddToWorklist(Op.getNode());
506
507   DAG.DeleteNode(N);
508 }
509
510 /// Return 1 if we can compute the negated form of the specified expression for
511 /// the same cost as the expression itself, or 2 if we can compute the negated
512 /// form more cheaply than the expression itself.
513 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
514                                const TargetLowering &TLI,
515                                const TargetOptions *Options,
516                                unsigned Depth = 0) {
517   // fneg is removable even if it has multiple uses.
518   if (Op.getOpcode() == ISD::FNEG) return 2;
519
520   // Don't allow anything with multiple uses.
521   if (!Op.hasOneUse()) return 0;
522
523   // Don't recurse exponentially.
524   if (Depth > 6) return 0;
525
526   switch (Op.getOpcode()) {
527   default: return false;
528   case ISD::ConstantFP:
529     // Don't invert constant FP values after legalize.  The negated constant
530     // isn't necessarily legal.
531     return LegalOperations ? 0 : 1;
532   case ISD::FADD:
533     // FIXME: determine better conditions for this xform.
534     if (!Options->UnsafeFPMath) return 0;
535
536     // After operation legalization, it might not be legal to create new FSUBs.
537     if (LegalOperations &&
538         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
539       return 0;
540
541     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
542     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
543                                     Options, Depth + 1))
544       return V;
545     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
546     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
547                               Depth + 1);
548   case ISD::FSUB:
549     // We can't turn -(A-B) into B-A when we honor signed zeros.
550     if (!Options->UnsafeFPMath) return 0;
551
552     // fold (fneg (fsub A, B)) -> (fsub B, A)
553     return 1;
554
555   case ISD::FMUL:
556   case ISD::FDIV:
557     if (Options->HonorSignDependentRoundingFPMath()) return 0;
558
559     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
560     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
561                                     Options, Depth + 1))
562       return V;
563
564     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
565                               Depth + 1);
566
567   case ISD::FP_EXTEND:
568   case ISD::FP_ROUND:
569   case ISD::FSIN:
570     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
571                               Depth + 1);
572   }
573 }
574
575 /// If isNegatibleForFree returns true, return the newly negated expression.
576 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
577                                     bool LegalOperations, unsigned Depth = 0) {
578   const TargetOptions &Options = DAG.getTarget().Options;
579   // fneg is removable even if it has multiple uses.
580   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
581
582   // Don't allow anything with multiple uses.
583   assert(Op.hasOneUse() && "Unknown reuse!");
584
585   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
586   switch (Op.getOpcode()) {
587   default: llvm_unreachable("Unknown code");
588   case ISD::ConstantFP: {
589     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
590     V.changeSign();
591     return DAG.getConstantFP(V, Op.getValueType());
592   }
593   case ISD::FADD:
594     // FIXME: determine better conditions for this xform.
595     assert(Options.UnsafeFPMath);
596
597     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
598     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
599                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
600       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
601                          GetNegatedExpression(Op.getOperand(0), DAG,
602                                               LegalOperations, Depth+1),
603                          Op.getOperand(1));
604     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
605     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
606                        GetNegatedExpression(Op.getOperand(1), DAG,
607                                             LegalOperations, Depth+1),
608                        Op.getOperand(0));
609   case ISD::FSUB:
610     // We can't turn -(A-B) into B-A when we honor signed zeros.
611     assert(Options.UnsafeFPMath);
612
613     // fold (fneg (fsub 0, B)) -> B
614     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
615       if (N0CFP->getValueAPF().isZero())
616         return Op.getOperand(1);
617
618     // fold (fneg (fsub A, B)) -> (fsub B, A)
619     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
620                        Op.getOperand(1), Op.getOperand(0));
621
622   case ISD::FMUL:
623   case ISD::FDIV:
624     assert(!Options.HonorSignDependentRoundingFPMath());
625
626     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
627     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
628                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
629       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
630                          GetNegatedExpression(Op.getOperand(0), DAG,
631                                               LegalOperations, Depth+1),
632                          Op.getOperand(1));
633
634     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
635     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
636                        Op.getOperand(0),
637                        GetNegatedExpression(Op.getOperand(1), DAG,
638                                             LegalOperations, Depth+1));
639
640   case ISD::FP_EXTEND:
641   case ISD::FSIN:
642     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
643                        GetNegatedExpression(Op.getOperand(0), DAG,
644                                             LegalOperations, Depth+1));
645   case ISD::FP_ROUND:
646       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
647                          GetNegatedExpression(Op.getOperand(0), DAG,
648                                               LegalOperations, Depth+1),
649                          Op.getOperand(1));
650   }
651 }
652
653 // Return true if this node is a setcc, or is a select_cc
654 // that selects between the target values used for true and false, making it
655 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
656 // the appropriate nodes based on the type of node we are checking. This
657 // simplifies life a bit for the callers.
658 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
659                                     SDValue &CC) const {
660   if (N.getOpcode() == ISD::SETCC) {
661     LHS = N.getOperand(0);
662     RHS = N.getOperand(1);
663     CC  = N.getOperand(2);
664     return true;
665   }
666
667   if (N.getOpcode() != ISD::SELECT_CC ||
668       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
669       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
670     return false;
671
672   if (TLI.getBooleanContents(N.getValueType()) ==
673       TargetLowering::UndefinedBooleanContent)
674     return false;
675
676   LHS = N.getOperand(0);
677   RHS = N.getOperand(1);
678   CC  = N.getOperand(4);
679   return true;
680 }
681
682 /// Return true if this is a SetCC-equivalent operation with only one use.
683 /// If this is true, it allows the users to invert the operation for free when
684 /// it is profitable to do so.
685 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
686   SDValue N0, N1, N2;
687   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
688     return true;
689   return false;
690 }
691
692 /// Returns true if N is a BUILD_VECTOR node whose
693 /// elements are all the same constant or undefined.
694 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
695   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
696   if (!C)
697     return false;
698
699   APInt SplatUndef;
700   unsigned SplatBitSize;
701   bool HasAnyUndefs;
702   EVT EltVT = N->getValueType(0).getVectorElementType();
703   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
704                              HasAnyUndefs) &&
705           EltVT.getSizeInBits() >= SplatBitSize);
706 }
707
708 // \brief Returns the SDNode if it is a constant BuildVector or constant.
709 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
710   if (isa<ConstantSDNode>(N))
711     return N.getNode();
712   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
713   if (BV && BV->isConstant())
714     return BV;
715   return nullptr;
716 }
717
718 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
719   if (isa<ConstantSDNode>(N))
720     return N.getNode();
721   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
722     return N.getNode();
723   return nullptr;
724 }
725
726 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
727   if (isa<ConstantFPSDNode>(N))
728     return N.getNode();
729   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
730     return N.getNode();
731   return nullptr;
732 }
733
734 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
735 // int.
736 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
737   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
738     return CN;
739
740   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
741     BitVector UndefElements;
742     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
743
744     // BuildVectors can truncate their operands. Ignore that case here.
745     // FIXME: We blindly ignore splats which include undef which is overly
746     // pessimistic.
747     if (CN && UndefElements.none() &&
748         CN->getValueType(0) == N.getValueType().getScalarType())
749       return CN;
750   }
751
752   return nullptr;
753 }
754
755 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
756 // float.
757 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
758   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
759     return CN;
760
761   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
762     BitVector UndefElements;
763     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
764
765     if (CN && UndefElements.none())
766       return CN;
767   }
768
769   return nullptr;
770 }
771
772 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
773                                     SDValue N0, SDValue N1) {
774   EVT VT = N0.getValueType();
775   if (N0.getOpcode() == Opc) {
776     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
777       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
778         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
779         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
780           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
781         return SDValue();
782       }
783       if (N0.hasOneUse()) {
784         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
785         // use
786         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
787         if (!OpNode.getNode())
788           return SDValue();
789         AddToWorklist(OpNode.getNode());
790         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
791       }
792     }
793   }
794
795   if (N1.getOpcode() == Opc) {
796     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
797       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
798         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
799         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
800           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
801         return SDValue();
802       }
803       if (N1.hasOneUse()) {
804         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
805         // use
806         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
807         if (!OpNode.getNode())
808           return SDValue();
809         AddToWorklist(OpNode.getNode());
810         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
811       }
812     }
813   }
814
815   return SDValue();
816 }
817
818 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
819                                bool AddTo) {
820   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
821   ++NodesCombined;
822   DEBUG(dbgs() << "\nReplacing.1 ";
823         N->dump(&DAG);
824         dbgs() << "\nWith: ";
825         To[0].getNode()->dump(&DAG);
826         dbgs() << " and " << NumTo-1 << " other values\n");
827   for (unsigned i = 0, e = NumTo; i != e; ++i)
828     assert((!To[i].getNode() ||
829             N->getValueType(i) == To[i].getValueType()) &&
830            "Cannot combine value to value of different type!");
831
832   WorklistRemover DeadNodes(*this);
833   DAG.ReplaceAllUsesWith(N, To);
834   if (AddTo) {
835     // Push the new nodes and any users onto the worklist
836     for (unsigned i = 0, e = NumTo; i != e; ++i) {
837       if (To[i].getNode()) {
838         AddToWorklist(To[i].getNode());
839         AddUsersToWorklist(To[i].getNode());
840       }
841     }
842   }
843
844   // Finally, if the node is now dead, remove it from the graph.  The node
845   // may not be dead if the replacement process recursively simplified to
846   // something else needing this node.
847   if (N->use_empty())
848     deleteAndRecombine(N);
849   return SDValue(N, 0);
850 }
851
852 void DAGCombiner::
853 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
854   // Replace all uses.  If any nodes become isomorphic to other nodes and
855   // are deleted, make sure to remove them from our worklist.
856   WorklistRemover DeadNodes(*this);
857   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
858
859   // Push the new node and any (possibly new) users onto the worklist.
860   AddToWorklist(TLO.New.getNode());
861   AddUsersToWorklist(TLO.New.getNode());
862
863   // Finally, if the node is now dead, remove it from the graph.  The node
864   // may not be dead if the replacement process recursively simplified to
865   // something else needing this node.
866   if (TLO.Old.getNode()->use_empty())
867     deleteAndRecombine(TLO.Old.getNode());
868 }
869
870 /// Check the specified integer node value to see if it can be simplified or if
871 /// things it uses can be simplified by bit propagation. If so, return true.
872 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
873   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
874   APInt KnownZero, KnownOne;
875   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
876     return false;
877
878   // Revisit the node.
879   AddToWorklist(Op.getNode());
880
881   // Replace the old value with the new one.
882   ++NodesCombined;
883   DEBUG(dbgs() << "\nReplacing.2 ";
884         TLO.Old.getNode()->dump(&DAG);
885         dbgs() << "\nWith: ";
886         TLO.New.getNode()->dump(&DAG);
887         dbgs() << '\n');
888
889   CommitTargetLoweringOpt(TLO);
890   return true;
891 }
892
893 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
894   SDLoc dl(Load);
895   EVT VT = Load->getValueType(0);
896   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
897
898   DEBUG(dbgs() << "\nReplacing.9 ";
899         Load->dump(&DAG);
900         dbgs() << "\nWith: ";
901         Trunc.getNode()->dump(&DAG);
902         dbgs() << '\n');
903   WorklistRemover DeadNodes(*this);
904   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
905   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
906   deleteAndRecombine(Load);
907   AddToWorklist(Trunc.getNode());
908 }
909
910 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
911   Replace = false;
912   SDLoc dl(Op);
913   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
914     EVT MemVT = LD->getMemoryVT();
915     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
916       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
917                                                        : ISD::EXTLOAD)
918       : LD->getExtensionType();
919     Replace = true;
920     return DAG.getExtLoad(ExtType, dl, PVT,
921                           LD->getChain(), LD->getBasePtr(),
922                           MemVT, LD->getMemOperand());
923   }
924
925   unsigned Opc = Op.getOpcode();
926   switch (Opc) {
927   default: break;
928   case ISD::AssertSext:
929     return DAG.getNode(ISD::AssertSext, dl, PVT,
930                        SExtPromoteOperand(Op.getOperand(0), PVT),
931                        Op.getOperand(1));
932   case ISD::AssertZext:
933     return DAG.getNode(ISD::AssertZext, dl, PVT,
934                        ZExtPromoteOperand(Op.getOperand(0), PVT),
935                        Op.getOperand(1));
936   case ISD::Constant: {
937     unsigned ExtOpc =
938       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
939     return DAG.getNode(ExtOpc, dl, PVT, Op);
940   }
941   }
942
943   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
944     return SDValue();
945   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
946 }
947
948 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
949   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
950     return SDValue();
951   EVT OldVT = Op.getValueType();
952   SDLoc dl(Op);
953   bool Replace = false;
954   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
955   if (!NewOp.getNode())
956     return SDValue();
957   AddToWorklist(NewOp.getNode());
958
959   if (Replace)
960     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
961   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
962                      DAG.getValueType(OldVT));
963 }
964
965 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
966   EVT OldVT = Op.getValueType();
967   SDLoc dl(Op);
968   bool Replace = false;
969   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
970   if (!NewOp.getNode())
971     return SDValue();
972   AddToWorklist(NewOp.getNode());
973
974   if (Replace)
975     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
976   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
977 }
978
979 /// Promote the specified integer binary operation if the target indicates it is
980 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
981 /// i32 since i16 instructions are longer.
982 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
983   if (!LegalOperations)
984     return SDValue();
985
986   EVT VT = Op.getValueType();
987   if (VT.isVector() || !VT.isInteger())
988     return SDValue();
989
990   // If operation type is 'undesirable', e.g. i16 on x86, consider
991   // promoting it.
992   unsigned Opc = Op.getOpcode();
993   if (TLI.isTypeDesirableForOp(Opc, VT))
994     return SDValue();
995
996   EVT PVT = VT;
997   // Consult target whether it is a good idea to promote this operation and
998   // what's the right type to promote it to.
999   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1000     assert(PVT != VT && "Don't know what type to promote to!");
1001
1002     bool Replace0 = false;
1003     SDValue N0 = Op.getOperand(0);
1004     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1005     if (!NN0.getNode())
1006       return SDValue();
1007
1008     bool Replace1 = false;
1009     SDValue N1 = Op.getOperand(1);
1010     SDValue NN1;
1011     if (N0 == N1)
1012       NN1 = NN0;
1013     else {
1014       NN1 = PromoteOperand(N1, PVT, Replace1);
1015       if (!NN1.getNode())
1016         return SDValue();
1017     }
1018
1019     AddToWorklist(NN0.getNode());
1020     if (NN1.getNode())
1021       AddToWorklist(NN1.getNode());
1022
1023     if (Replace0)
1024       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1025     if (Replace1)
1026       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1027
1028     DEBUG(dbgs() << "\nPromoting ";
1029           Op.getNode()->dump(&DAG));
1030     SDLoc dl(Op);
1031     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1032                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1033   }
1034   return SDValue();
1035 }
1036
1037 /// Promote the specified integer shift operation if the target indicates it is
1038 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1039 /// i32 since i16 instructions are longer.
1040 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1041   if (!LegalOperations)
1042     return SDValue();
1043
1044   EVT VT = Op.getValueType();
1045   if (VT.isVector() || !VT.isInteger())
1046     return SDValue();
1047
1048   // If operation type is 'undesirable', e.g. i16 on x86, consider
1049   // promoting it.
1050   unsigned Opc = Op.getOpcode();
1051   if (TLI.isTypeDesirableForOp(Opc, VT))
1052     return SDValue();
1053
1054   EVT PVT = VT;
1055   // Consult target whether it is a good idea to promote this operation and
1056   // what's the right type to promote it to.
1057   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1058     assert(PVT != VT && "Don't know what type to promote to!");
1059
1060     bool Replace = false;
1061     SDValue N0 = Op.getOperand(0);
1062     if (Opc == ISD::SRA)
1063       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1064     else if (Opc == ISD::SRL)
1065       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1066     else
1067       N0 = PromoteOperand(N0, PVT, Replace);
1068     if (!N0.getNode())
1069       return SDValue();
1070
1071     AddToWorklist(N0.getNode());
1072     if (Replace)
1073       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1074
1075     DEBUG(dbgs() << "\nPromoting ";
1076           Op.getNode()->dump(&DAG));
1077     SDLoc dl(Op);
1078     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1079                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1080   }
1081   return SDValue();
1082 }
1083
1084 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1085   if (!LegalOperations)
1086     return SDValue();
1087
1088   EVT VT = Op.getValueType();
1089   if (VT.isVector() || !VT.isInteger())
1090     return SDValue();
1091
1092   // If operation type is 'undesirable', e.g. i16 on x86, consider
1093   // promoting it.
1094   unsigned Opc = Op.getOpcode();
1095   if (TLI.isTypeDesirableForOp(Opc, VT))
1096     return SDValue();
1097
1098   EVT PVT = VT;
1099   // Consult target whether it is a good idea to promote this operation and
1100   // what's the right type to promote it to.
1101   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1102     assert(PVT != VT && "Don't know what type to promote to!");
1103     // fold (aext (aext x)) -> (aext x)
1104     // fold (aext (zext x)) -> (zext x)
1105     // fold (aext (sext x)) -> (sext x)
1106     DEBUG(dbgs() << "\nPromoting ";
1107           Op.getNode()->dump(&DAG));
1108     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1109   }
1110   return SDValue();
1111 }
1112
1113 bool DAGCombiner::PromoteLoad(SDValue Op) {
1114   if (!LegalOperations)
1115     return false;
1116
1117   EVT VT = Op.getValueType();
1118   if (VT.isVector() || !VT.isInteger())
1119     return false;
1120
1121   // If operation type is 'undesirable', e.g. i16 on x86, consider
1122   // promoting it.
1123   unsigned Opc = Op.getOpcode();
1124   if (TLI.isTypeDesirableForOp(Opc, VT))
1125     return false;
1126
1127   EVT PVT = VT;
1128   // Consult target whether it is a good idea to promote this operation and
1129   // what's the right type to promote it to.
1130   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1131     assert(PVT != VT && "Don't know what type to promote to!");
1132
1133     SDLoc dl(Op);
1134     SDNode *N = Op.getNode();
1135     LoadSDNode *LD = cast<LoadSDNode>(N);
1136     EVT MemVT = LD->getMemoryVT();
1137     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1138       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1139                                                        : ISD::EXTLOAD)
1140       : LD->getExtensionType();
1141     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1142                                    LD->getChain(), LD->getBasePtr(),
1143                                    MemVT, LD->getMemOperand());
1144     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1145
1146     DEBUG(dbgs() << "\nPromoting ";
1147           N->dump(&DAG);
1148           dbgs() << "\nTo: ";
1149           Result.getNode()->dump(&DAG);
1150           dbgs() << '\n');
1151     WorklistRemover DeadNodes(*this);
1152     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1153     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1154     deleteAndRecombine(N);
1155     AddToWorklist(Result.getNode());
1156     return true;
1157   }
1158   return false;
1159 }
1160
1161 /// \brief Recursively delete a node which has no uses and any operands for
1162 /// which it is the only use.
1163 ///
1164 /// Note that this both deletes the nodes and removes them from the worklist.
1165 /// It also adds any nodes who have had a user deleted to the worklist as they
1166 /// may now have only one use and subject to other combines.
1167 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1168   if (!N->use_empty())
1169     return false;
1170
1171   SmallSetVector<SDNode *, 16> Nodes;
1172   Nodes.insert(N);
1173   do {
1174     N = Nodes.pop_back_val();
1175     if (!N)
1176       continue;
1177
1178     if (N->use_empty()) {
1179       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1180         Nodes.insert(N->getOperand(i).getNode());
1181
1182       removeFromWorklist(N);
1183       DAG.DeleteNode(N);
1184     } else {
1185       AddToWorklist(N);
1186     }
1187   } while (!Nodes.empty());
1188   return true;
1189 }
1190
1191 //===----------------------------------------------------------------------===//
1192 //  Main DAG Combiner implementation
1193 //===----------------------------------------------------------------------===//
1194
1195 void DAGCombiner::Run(CombineLevel AtLevel) {
1196   // set the instance variables, so that the various visit routines may use it.
1197   Level = AtLevel;
1198   LegalOperations = Level >= AfterLegalizeVectorOps;
1199   LegalTypes = Level >= AfterLegalizeTypes;
1200
1201   // Add all the dag nodes to the worklist.
1202   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1203        E = DAG.allnodes_end(); I != E; ++I)
1204     AddToWorklist(I);
1205
1206   // Create a dummy node (which is not added to allnodes), that adds a reference
1207   // to the root node, preventing it from being deleted, and tracking any
1208   // changes of the root.
1209   HandleSDNode Dummy(DAG.getRoot());
1210
1211   // while the worklist isn't empty, find a node and
1212   // try and combine it.
1213   while (!WorklistMap.empty()) {
1214     SDNode *N;
1215     // The Worklist holds the SDNodes in order, but it may contain null entries.
1216     do {
1217       N = Worklist.pop_back_val();
1218     } while (!N);
1219
1220     bool GoodWorklistEntry = WorklistMap.erase(N);
1221     (void)GoodWorklistEntry;
1222     assert(GoodWorklistEntry &&
1223            "Found a worklist entry without a corresponding map entry!");
1224
1225     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1226     // N is deleted from the DAG, since they too may now be dead or may have a
1227     // reduced number of uses, allowing other xforms.
1228     if (recursivelyDeleteUnusedNodes(N))
1229       continue;
1230
1231     WorklistRemover DeadNodes(*this);
1232
1233     // If this combine is running after legalizing the DAG, re-legalize any
1234     // nodes pulled off the worklist.
1235     if (Level == AfterLegalizeDAG) {
1236       SmallSetVector<SDNode *, 16> UpdatedNodes;
1237       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1238
1239       for (SDNode *LN : UpdatedNodes) {
1240         AddToWorklist(LN);
1241         AddUsersToWorklist(LN);
1242       }
1243       if (!NIsValid)
1244         continue;
1245     }
1246
1247     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1248
1249     // Add any operands of the new node which have not yet been combined to the
1250     // worklist as well. Because the worklist uniques things already, this
1251     // won't repeatedly process the same operand.
1252     CombinedNodes.insert(N);
1253     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1254       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1255         AddToWorklist(N->getOperand(i).getNode());
1256
1257     SDValue RV = combine(N);
1258
1259     if (!RV.getNode())
1260       continue;
1261
1262     ++NodesCombined;
1263
1264     // If we get back the same node we passed in, rather than a new node or
1265     // zero, we know that the node must have defined multiple values and
1266     // CombineTo was used.  Since CombineTo takes care of the worklist
1267     // mechanics for us, we have no work to do in this case.
1268     if (RV.getNode() == N)
1269       continue;
1270
1271     assert(N->getOpcode() != ISD::DELETED_NODE &&
1272            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1273            "Node was deleted but visit returned new node!");
1274
1275     DEBUG(dbgs() << " ... into: ";
1276           RV.getNode()->dump(&DAG));
1277
1278     // Transfer debug value.
1279     DAG.TransferDbgValues(SDValue(N, 0), RV);
1280     if (N->getNumValues() == RV.getNode()->getNumValues())
1281       DAG.ReplaceAllUsesWith(N, RV.getNode());
1282     else {
1283       assert(N->getValueType(0) == RV.getValueType() &&
1284              N->getNumValues() == 1 && "Type mismatch");
1285       SDValue OpV = RV;
1286       DAG.ReplaceAllUsesWith(N, &OpV);
1287     }
1288
1289     // Push the new node and any users onto the worklist
1290     AddToWorklist(RV.getNode());
1291     AddUsersToWorklist(RV.getNode());
1292
1293     // Finally, if the node is now dead, remove it from the graph.  The node
1294     // may not be dead if the replacement process recursively simplified to
1295     // something else needing this node. This will also take care of adding any
1296     // operands which have lost a user to the worklist.
1297     recursivelyDeleteUnusedNodes(N);
1298   }
1299
1300   // If the root changed (e.g. it was a dead load, update the root).
1301   DAG.setRoot(Dummy.getValue());
1302   DAG.RemoveDeadNodes();
1303 }
1304
1305 SDValue DAGCombiner::visit(SDNode *N) {
1306   switch (N->getOpcode()) {
1307   default: break;
1308   case ISD::TokenFactor:        return visitTokenFactor(N);
1309   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1310   case ISD::ADD:                return visitADD(N);
1311   case ISD::SUB:                return visitSUB(N);
1312   case ISD::ADDC:               return visitADDC(N);
1313   case ISD::SUBC:               return visitSUBC(N);
1314   case ISD::ADDE:               return visitADDE(N);
1315   case ISD::SUBE:               return visitSUBE(N);
1316   case ISD::MUL:                return visitMUL(N);
1317   case ISD::SDIV:               return visitSDIV(N);
1318   case ISD::UDIV:               return visitUDIV(N);
1319   case ISD::SREM:               return visitSREM(N);
1320   case ISD::UREM:               return visitUREM(N);
1321   case ISD::MULHU:              return visitMULHU(N);
1322   case ISD::MULHS:              return visitMULHS(N);
1323   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1324   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1325   case ISD::SMULO:              return visitSMULO(N);
1326   case ISD::UMULO:              return visitUMULO(N);
1327   case ISD::SDIVREM:            return visitSDIVREM(N);
1328   case ISD::UDIVREM:            return visitUDIVREM(N);
1329   case ISD::AND:                return visitAND(N);
1330   case ISD::OR:                 return visitOR(N);
1331   case ISD::XOR:                return visitXOR(N);
1332   case ISD::SHL:                return visitSHL(N);
1333   case ISD::SRA:                return visitSRA(N);
1334   case ISD::SRL:                return visitSRL(N);
1335   case ISD::ROTR:
1336   case ISD::ROTL:               return visitRotate(N);
1337   case ISD::CTLZ:               return visitCTLZ(N);
1338   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1339   case ISD::CTTZ:               return visitCTTZ(N);
1340   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1341   case ISD::CTPOP:              return visitCTPOP(N);
1342   case ISD::SELECT:             return visitSELECT(N);
1343   case ISD::VSELECT:            return visitVSELECT(N);
1344   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1345   case ISD::SETCC:              return visitSETCC(N);
1346   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1347   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1348   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1349   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1350   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1351   case ISD::BITCAST:            return visitBITCAST(N);
1352   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1353   case ISD::FADD:               return visitFADD(N);
1354   case ISD::FSUB:               return visitFSUB(N);
1355   case ISD::FMUL:               return visitFMUL(N);
1356   case ISD::FMA:                return visitFMA(N);
1357   case ISD::FDIV:               return visitFDIV(N);
1358   case ISD::FREM:               return visitFREM(N);
1359   case ISD::FSQRT:              return visitFSQRT(N);
1360   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1361   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1362   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1363   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1364   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1365   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1366   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1367   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1368   case ISD::FNEG:               return visitFNEG(N);
1369   case ISD::FABS:               return visitFABS(N);
1370   case ISD::FFLOOR:             return visitFFLOOR(N);
1371   case ISD::FMINNUM:            return visitFMINNUM(N);
1372   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1373   case ISD::FCEIL:              return visitFCEIL(N);
1374   case ISD::FTRUNC:             return visitFTRUNC(N);
1375   case ISD::BRCOND:             return visitBRCOND(N);
1376   case ISD::BR_CC:              return visitBR_CC(N);
1377   case ISD::LOAD:               return visitLOAD(N);
1378   case ISD::STORE:              return visitSTORE(N);
1379   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1380   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1381   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1382   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1383   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1384   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1385   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1386   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1387   case ISD::MLOAD:              return visitMLOAD(N);
1388   case ISD::MSTORE:             return visitMSTORE(N);
1389   }
1390   return SDValue();
1391 }
1392
1393 SDValue DAGCombiner::combine(SDNode *N) {
1394   SDValue RV = visit(N);
1395
1396   // If nothing happened, try a target-specific DAG combine.
1397   if (!RV.getNode()) {
1398     assert(N->getOpcode() != ISD::DELETED_NODE &&
1399            "Node was deleted but visit returned NULL!");
1400
1401     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1402         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1403
1404       // Expose the DAG combiner to the target combiner impls.
1405       TargetLowering::DAGCombinerInfo
1406         DagCombineInfo(DAG, Level, false, this);
1407
1408       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1409     }
1410   }
1411
1412   // If nothing happened still, try promoting the operation.
1413   if (!RV.getNode()) {
1414     switch (N->getOpcode()) {
1415     default: break;
1416     case ISD::ADD:
1417     case ISD::SUB:
1418     case ISD::MUL:
1419     case ISD::AND:
1420     case ISD::OR:
1421     case ISD::XOR:
1422       RV = PromoteIntBinOp(SDValue(N, 0));
1423       break;
1424     case ISD::SHL:
1425     case ISD::SRA:
1426     case ISD::SRL:
1427       RV = PromoteIntShiftOp(SDValue(N, 0));
1428       break;
1429     case ISD::SIGN_EXTEND:
1430     case ISD::ZERO_EXTEND:
1431     case ISD::ANY_EXTEND:
1432       RV = PromoteExtend(SDValue(N, 0));
1433       break;
1434     case ISD::LOAD:
1435       if (PromoteLoad(SDValue(N, 0)))
1436         RV = SDValue(N, 0);
1437       break;
1438     }
1439   }
1440
1441   // If N is a commutative binary node, try commuting it to enable more
1442   // sdisel CSE.
1443   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1444       N->getNumValues() == 1) {
1445     SDValue N0 = N->getOperand(0);
1446     SDValue N1 = N->getOperand(1);
1447
1448     // Constant operands are canonicalized to RHS.
1449     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1450       SDValue Ops[] = {N1, N0};
1451       SDNode *CSENode;
1452       if (const BinaryWithFlagsSDNode *BinNode =
1453               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1454         CSENode = DAG.getNodeIfExists(
1455             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1456             BinNode->hasNoSignedWrap(), BinNode->isExact());
1457       } else {
1458         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1459       }
1460       if (CSENode)
1461         return SDValue(CSENode, 0);
1462     }
1463   }
1464
1465   return RV;
1466 }
1467
1468 /// Given a node, return its input chain if it has one, otherwise return a null
1469 /// sd operand.
1470 static SDValue getInputChainForNode(SDNode *N) {
1471   if (unsigned NumOps = N->getNumOperands()) {
1472     if (N->getOperand(0).getValueType() == MVT::Other)
1473       return N->getOperand(0);
1474     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1475       return N->getOperand(NumOps-1);
1476     for (unsigned i = 1; i < NumOps-1; ++i)
1477       if (N->getOperand(i).getValueType() == MVT::Other)
1478         return N->getOperand(i);
1479   }
1480   return SDValue();
1481 }
1482
1483 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1484   // If N has two operands, where one has an input chain equal to the other,
1485   // the 'other' chain is redundant.
1486   if (N->getNumOperands() == 2) {
1487     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1488       return N->getOperand(0);
1489     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1490       return N->getOperand(1);
1491   }
1492
1493   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1494   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1495   SmallPtrSet<SDNode*, 16> SeenOps;
1496   bool Changed = false;             // If we should replace this token factor.
1497
1498   // Start out with this token factor.
1499   TFs.push_back(N);
1500
1501   // Iterate through token factors.  The TFs grows when new token factors are
1502   // encountered.
1503   for (unsigned i = 0; i < TFs.size(); ++i) {
1504     SDNode *TF = TFs[i];
1505
1506     // Check each of the operands.
1507     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1508       SDValue Op = TF->getOperand(i);
1509
1510       switch (Op.getOpcode()) {
1511       case ISD::EntryToken:
1512         // Entry tokens don't need to be added to the list. They are
1513         // redundant.
1514         Changed = true;
1515         break;
1516
1517       case ISD::TokenFactor:
1518         if (Op.hasOneUse() &&
1519             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1520           // Queue up for processing.
1521           TFs.push_back(Op.getNode());
1522           // Clean up in case the token factor is removed.
1523           AddToWorklist(Op.getNode());
1524           Changed = true;
1525           break;
1526         }
1527         // Fall thru
1528
1529       default:
1530         // Only add if it isn't already in the list.
1531         if (SeenOps.insert(Op.getNode()).second)
1532           Ops.push_back(Op);
1533         else
1534           Changed = true;
1535         break;
1536       }
1537     }
1538   }
1539
1540   SDValue Result;
1541
1542   // If we've changed things around then replace token factor.
1543   if (Changed) {
1544     if (Ops.empty()) {
1545       // The entry token is the only possible outcome.
1546       Result = DAG.getEntryNode();
1547     } else {
1548       // New and improved token factor.
1549       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1550     }
1551
1552     // Add users to worklist if AA is enabled, since it may introduce
1553     // a lot of new chained token factors while removing memory deps.
1554     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1555       : DAG.getSubtarget().useAA();
1556     return CombineTo(N, Result, UseAA /*add to worklist*/);
1557   }
1558
1559   return Result;
1560 }
1561
1562 /// MERGE_VALUES can always be eliminated.
1563 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1564   WorklistRemover DeadNodes(*this);
1565   // Replacing results may cause a different MERGE_VALUES to suddenly
1566   // be CSE'd with N, and carry its uses with it. Iterate until no
1567   // uses remain, to ensure that the node can be safely deleted.
1568   // First add the users of this node to the work list so that they
1569   // can be tried again once they have new operands.
1570   AddUsersToWorklist(N);
1571   do {
1572     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1573       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1574   } while (!N->use_empty());
1575   deleteAndRecombine(N);
1576   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1577 }
1578
1579 SDValue DAGCombiner::visitADD(SDNode *N) {
1580   SDValue N0 = N->getOperand(0);
1581   SDValue N1 = N->getOperand(1);
1582   EVT VT = N0.getValueType();
1583
1584   // fold vector ops
1585   if (VT.isVector()) {
1586     SDValue FoldedVOp = SimplifyVBinOp(N);
1587     if (FoldedVOp.getNode()) return FoldedVOp;
1588
1589     // fold (add x, 0) -> x, vector edition
1590     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1591       return N0;
1592     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1593       return N1;
1594   }
1595
1596   // fold (add x, undef) -> undef
1597   if (N0.getOpcode() == ISD::UNDEF)
1598     return N0;
1599   if (N1.getOpcode() == ISD::UNDEF)
1600     return N1;
1601   // fold (add c1, c2) -> c1+c2
1602   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1603   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1604   if (N0C && N1C)
1605     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1606   // canonicalize constant to RHS
1607   if (N0C && !N1C)
1608     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1609   // fold (add x, 0) -> x
1610   if (N1C && N1C->isNullValue())
1611     return N0;
1612   // fold (add Sym, c) -> Sym+c
1613   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1614     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1615         GA->getOpcode() == ISD::GlobalAddress)
1616       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1617                                   GA->getOffset() +
1618                                     (uint64_t)N1C->getSExtValue());
1619   // fold ((c1-A)+c2) -> (c1+c2)-A
1620   if (N1C && N0.getOpcode() == ISD::SUB)
1621     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1622       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1623                          DAG.getConstant(N1C->getAPIntValue()+
1624                                          N0C->getAPIntValue(), VT),
1625                          N0.getOperand(1));
1626   // reassociate add
1627   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1628   if (RADD.getNode())
1629     return RADD;
1630   // fold ((0-A) + B) -> B-A
1631   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1632       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1633     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1634   // fold (A + (0-B)) -> A-B
1635   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1636       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1637     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1638   // fold (A+(B-A)) -> B
1639   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1640     return N1.getOperand(0);
1641   // fold ((B-A)+A) -> B
1642   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1643     return N0.getOperand(0);
1644   // fold (A+(B-(A+C))) to (B-C)
1645   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1646       N0 == N1.getOperand(1).getOperand(0))
1647     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1648                        N1.getOperand(1).getOperand(1));
1649   // fold (A+(B-(C+A))) to (B-C)
1650   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1651       N0 == N1.getOperand(1).getOperand(1))
1652     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1653                        N1.getOperand(1).getOperand(0));
1654   // fold (A+((B-A)+or-C)) to (B+or-C)
1655   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1656       N1.getOperand(0).getOpcode() == ISD::SUB &&
1657       N0 == N1.getOperand(0).getOperand(1))
1658     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1659                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1660
1661   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1662   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1663     SDValue N00 = N0.getOperand(0);
1664     SDValue N01 = N0.getOperand(1);
1665     SDValue N10 = N1.getOperand(0);
1666     SDValue N11 = N1.getOperand(1);
1667
1668     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1669       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1670                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1671                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1672   }
1673
1674   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1675     return SDValue(N, 0);
1676
1677   // fold (a+b) -> (a|b) iff a and b share no bits.
1678   if (VT.isInteger() && !VT.isVector()) {
1679     APInt LHSZero, LHSOne;
1680     APInt RHSZero, RHSOne;
1681     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1682
1683     if (LHSZero.getBoolValue()) {
1684       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1685
1686       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1687       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1688       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1689         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1690           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1691       }
1692     }
1693   }
1694
1695   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1696   if (N1.getOpcode() == ISD::SHL &&
1697       N1.getOperand(0).getOpcode() == ISD::SUB)
1698     if (ConstantSDNode *C =
1699           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1700       if (C->getAPIntValue() == 0)
1701         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1702                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1703                                        N1.getOperand(0).getOperand(1),
1704                                        N1.getOperand(1)));
1705   if (N0.getOpcode() == ISD::SHL &&
1706       N0.getOperand(0).getOpcode() == ISD::SUB)
1707     if (ConstantSDNode *C =
1708           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1709       if (C->getAPIntValue() == 0)
1710         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1711                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1712                                        N0.getOperand(0).getOperand(1),
1713                                        N0.getOperand(1)));
1714
1715   if (N1.getOpcode() == ISD::AND) {
1716     SDValue AndOp0 = N1.getOperand(0);
1717     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1718     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1719     unsigned DestBits = VT.getScalarType().getSizeInBits();
1720
1721     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1722     // and similar xforms where the inner op is either ~0 or 0.
1723     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1724       SDLoc DL(N);
1725       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1726     }
1727   }
1728
1729   // add (sext i1), X -> sub X, (zext i1)
1730   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1731       N0.getOperand(0).getValueType() == MVT::i1 &&
1732       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1733     SDLoc DL(N);
1734     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1735     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1736   }
1737
1738   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1739   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1740     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1741     if (TN->getVT() == MVT::i1) {
1742       SDLoc DL(N);
1743       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1744                                  DAG.getConstant(1, VT));
1745       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1746     }
1747   }
1748
1749   return SDValue();
1750 }
1751
1752 SDValue DAGCombiner::visitADDC(SDNode *N) {
1753   SDValue N0 = N->getOperand(0);
1754   SDValue N1 = N->getOperand(1);
1755   EVT VT = N0.getValueType();
1756
1757   // If the flag result is dead, turn this into an ADD.
1758   if (!N->hasAnyUseOfValue(1))
1759     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1760                      DAG.getNode(ISD::CARRY_FALSE,
1761                                  SDLoc(N), MVT::Glue));
1762
1763   // canonicalize constant to RHS.
1764   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1765   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1766   if (N0C && !N1C)
1767     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1768
1769   // fold (addc x, 0) -> x + no carry out
1770   if (N1C && N1C->isNullValue())
1771     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1772                                         SDLoc(N), MVT::Glue));
1773
1774   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1775   APInt LHSZero, LHSOne;
1776   APInt RHSZero, RHSOne;
1777   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1778
1779   if (LHSZero.getBoolValue()) {
1780     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1781
1782     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1783     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1784     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1785       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1786                        DAG.getNode(ISD::CARRY_FALSE,
1787                                    SDLoc(N), MVT::Glue));
1788   }
1789
1790   return SDValue();
1791 }
1792
1793 SDValue DAGCombiner::visitADDE(SDNode *N) {
1794   SDValue N0 = N->getOperand(0);
1795   SDValue N1 = N->getOperand(1);
1796   SDValue CarryIn = N->getOperand(2);
1797
1798   // canonicalize constant to RHS
1799   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1800   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1801   if (N0C && !N1C)
1802     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1803                        N1, N0, CarryIn);
1804
1805   // fold (adde x, y, false) -> (addc x, y)
1806   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1807     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1808
1809   return SDValue();
1810 }
1811
1812 // Since it may not be valid to emit a fold to zero for vector initializers
1813 // check if we can before folding.
1814 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1815                              SelectionDAG &DAG,
1816                              bool LegalOperations, bool LegalTypes) {
1817   if (!VT.isVector())
1818     return DAG.getConstant(0, VT);
1819   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1820     return DAG.getConstant(0, VT);
1821   return SDValue();
1822 }
1823
1824 SDValue DAGCombiner::visitSUB(SDNode *N) {
1825   SDValue N0 = N->getOperand(0);
1826   SDValue N1 = N->getOperand(1);
1827   EVT VT = N0.getValueType();
1828
1829   // fold vector ops
1830   if (VT.isVector()) {
1831     SDValue FoldedVOp = SimplifyVBinOp(N);
1832     if (FoldedVOp.getNode()) return FoldedVOp;
1833
1834     // fold (sub x, 0) -> x, vector edition
1835     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1836       return N0;
1837   }
1838
1839   // fold (sub x, x) -> 0
1840   // FIXME: Refactor this and xor and other similar operations together.
1841   if (N0 == N1)
1842     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1843   // fold (sub c1, c2) -> c1-c2
1844   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1845   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1846   if (N0C && N1C)
1847     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1848   // fold (sub x, c) -> (add x, -c)
1849   if (N1C)
1850     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1851                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1852   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1853   if (N0C && N0C->isAllOnesValue())
1854     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1855   // fold A-(A-B) -> B
1856   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1857     return N1.getOperand(1);
1858   // fold (A+B)-A -> B
1859   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1860     return N0.getOperand(1);
1861   // fold (A+B)-B -> A
1862   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1863     return N0.getOperand(0);
1864   // fold C2-(A+C1) -> (C2-C1)-A
1865   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1866     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1867   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1868     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1869                                    VT);
1870     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1871                        N1.getOperand(0));
1872   }
1873   // fold ((A+(B+or-C))-B) -> A+or-C
1874   if (N0.getOpcode() == ISD::ADD &&
1875       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1876        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1877       N0.getOperand(1).getOperand(0) == N1)
1878     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1879                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1880   // fold ((A+(C+B))-B) -> A+C
1881   if (N0.getOpcode() == ISD::ADD &&
1882       N0.getOperand(1).getOpcode() == ISD::ADD &&
1883       N0.getOperand(1).getOperand(1) == N1)
1884     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1885                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1886   // fold ((A-(B-C))-C) -> A-B
1887   if (N0.getOpcode() == ISD::SUB &&
1888       N0.getOperand(1).getOpcode() == ISD::SUB &&
1889       N0.getOperand(1).getOperand(1) == N1)
1890     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1891                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1892
1893   // If either operand of a sub is undef, the result is undef
1894   if (N0.getOpcode() == ISD::UNDEF)
1895     return N0;
1896   if (N1.getOpcode() == ISD::UNDEF)
1897     return N1;
1898
1899   // If the relocation model supports it, consider symbol offsets.
1900   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1901     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1902       // fold (sub Sym, c) -> Sym-c
1903       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1904         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1905                                     GA->getOffset() -
1906                                       (uint64_t)N1C->getSExtValue());
1907       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1908       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1909         if (GA->getGlobal() == GB->getGlobal())
1910           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1911                                  VT);
1912     }
1913
1914   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1915   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1916     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1917     if (TN->getVT() == MVT::i1) {
1918       SDLoc DL(N);
1919       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1920                                  DAG.getConstant(1, VT));
1921       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1922     }
1923   }
1924
1925   return SDValue();
1926 }
1927
1928 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1929   SDValue N0 = N->getOperand(0);
1930   SDValue N1 = N->getOperand(1);
1931   EVT VT = N0.getValueType();
1932
1933   // If the flag result is dead, turn this into an SUB.
1934   if (!N->hasAnyUseOfValue(1))
1935     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1936                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1937                                  MVT::Glue));
1938
1939   // fold (subc x, x) -> 0 + no borrow
1940   if (N0 == N1)
1941     return CombineTo(N, DAG.getConstant(0, VT),
1942                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1943                                  MVT::Glue));
1944
1945   // fold (subc x, 0) -> x + no borrow
1946   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1947   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1948   if (N1C && N1C->isNullValue())
1949     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1950                                         MVT::Glue));
1951
1952   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1953   if (N0C && N0C->isAllOnesValue())
1954     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1955                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1956                                  MVT::Glue));
1957
1958   return SDValue();
1959 }
1960
1961 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1962   SDValue N0 = N->getOperand(0);
1963   SDValue N1 = N->getOperand(1);
1964   SDValue CarryIn = N->getOperand(2);
1965
1966   // fold (sube x, y, false) -> (subc x, y)
1967   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1968     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1969
1970   return SDValue();
1971 }
1972
1973 SDValue DAGCombiner::visitMUL(SDNode *N) {
1974   SDValue N0 = N->getOperand(0);
1975   SDValue N1 = N->getOperand(1);
1976   EVT VT = N0.getValueType();
1977
1978   // fold (mul x, undef) -> 0
1979   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1980     return DAG.getConstant(0, VT);
1981
1982   bool N0IsConst = false;
1983   bool N1IsConst = false;
1984   APInt ConstValue0, ConstValue1;
1985   // fold vector ops
1986   if (VT.isVector()) {
1987     SDValue FoldedVOp = SimplifyVBinOp(N);
1988     if (FoldedVOp.getNode()) return FoldedVOp;
1989
1990     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1991     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1992   } else {
1993     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1994     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1995                             : APInt();
1996     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1997     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1998                             : APInt();
1999   }
2000
2001   // fold (mul c1, c2) -> c1*c2
2002   if (N0IsConst && N1IsConst)
2003     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
2004
2005   // canonicalize constant to RHS
2006   if (N0IsConst && !N1IsConst)
2007     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2008   // fold (mul x, 0) -> 0
2009   if (N1IsConst && ConstValue1 == 0)
2010     return N1;
2011   // We require a splat of the entire scalar bit width for non-contiguous
2012   // bit patterns.
2013   bool IsFullSplat =
2014     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2015   // fold (mul x, 1) -> x
2016   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2017     return N0;
2018   // fold (mul x, -1) -> 0-x
2019   if (N1IsConst && ConstValue1.isAllOnesValue())
2020     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2021                        DAG.getConstant(0, VT), N0);
2022   // fold (mul x, (1 << c)) -> x << c
2023   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
2024     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2025                        DAG.getConstant(ConstValue1.logBase2(),
2026                                        getShiftAmountTy(N0.getValueType())));
2027   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2028   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2029     unsigned Log2Val = (-ConstValue1).logBase2();
2030     // FIXME: If the input is something that is easily negated (e.g. a
2031     // single-use add), we should put the negate there.
2032     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2033                        DAG.getConstant(0, VT),
2034                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2035                             DAG.getConstant(Log2Val,
2036                                       getShiftAmountTy(N0.getValueType()))));
2037   }
2038
2039   APInt Val;
2040   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2041   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2042       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2043                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2044     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2045                              N1, N0.getOperand(1));
2046     AddToWorklist(C3.getNode());
2047     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2048                        N0.getOperand(0), C3);
2049   }
2050
2051   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2052   // use.
2053   {
2054     SDValue Sh(nullptr,0), Y(nullptr,0);
2055     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2056     if (N0.getOpcode() == ISD::SHL &&
2057         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2058                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2059         N0.getNode()->hasOneUse()) {
2060       Sh = N0; Y = N1;
2061     } else if (N1.getOpcode() == ISD::SHL &&
2062                isa<ConstantSDNode>(N1.getOperand(1)) &&
2063                N1.getNode()->hasOneUse()) {
2064       Sh = N1; Y = N0;
2065     }
2066
2067     if (Sh.getNode()) {
2068       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2069                                 Sh.getOperand(0), Y);
2070       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2071                          Mul, Sh.getOperand(1));
2072     }
2073   }
2074
2075   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2076   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2077       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2078                      isa<ConstantSDNode>(N0.getOperand(1))))
2079     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2080                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2081                                    N0.getOperand(0), N1),
2082                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2083                                    N0.getOperand(1), N1));
2084
2085   // reassociate mul
2086   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2087   if (RMUL.getNode())
2088     return RMUL;
2089
2090   return SDValue();
2091 }
2092
2093 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2094   SDValue N0 = N->getOperand(0);
2095   SDValue N1 = N->getOperand(1);
2096   EVT VT = N->getValueType(0);
2097
2098   // fold vector ops
2099   if (VT.isVector()) {
2100     SDValue FoldedVOp = SimplifyVBinOp(N);
2101     if (FoldedVOp.getNode()) return FoldedVOp;
2102   }
2103
2104   // fold (sdiv c1, c2) -> c1/c2
2105   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2106   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2107   if (N0C && N1C && !N1C->isNullValue())
2108     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2109   // fold (sdiv X, 1) -> X
2110   if (N1C && N1C->getAPIntValue() == 1LL)
2111     return N0;
2112   // fold (sdiv X, -1) -> 0-X
2113   if (N1C && N1C->isAllOnesValue())
2114     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2115                        DAG.getConstant(0, VT), N0);
2116   // If we know the sign bits of both operands are zero, strength reduce to a
2117   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2118   if (!VT.isVector()) {
2119     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2120       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2121                          N0, N1);
2122   }
2123
2124   // fold (sdiv X, pow2) -> simple ops after legalize
2125   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2126                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2127     // If dividing by powers of two is cheap, then don't perform the following
2128     // fold.
2129     if (TLI.isPow2SDivCheap())
2130       return SDValue();
2131
2132     // Target-specific implementation of sdiv x, pow2.
2133     SDValue Res = BuildSDIVPow2(N);
2134     if (Res.getNode())
2135       return Res;
2136
2137     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2138
2139     // Splat the sign bit into the register
2140     SDValue SGN =
2141         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2142                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2143                                     getShiftAmountTy(N0.getValueType())));
2144     AddToWorklist(SGN.getNode());
2145
2146     // Add (N0 < 0) ? abs2 - 1 : 0;
2147     SDValue SRL =
2148         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2149                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2150                                     getShiftAmountTy(SGN.getValueType())));
2151     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2152     AddToWorklist(SRL.getNode());
2153     AddToWorklist(ADD.getNode());    // Divide by pow2
2154     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2155                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2156
2157     // If we're dividing by a positive value, we're done.  Otherwise, we must
2158     // negate the result.
2159     if (N1C->getAPIntValue().isNonNegative())
2160       return SRA;
2161
2162     AddToWorklist(SRA.getNode());
2163     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2164   }
2165
2166   // if integer divide is expensive and we satisfy the requirements, emit an
2167   // alternate sequence.
2168   if (N1C && !TLI.isIntDivCheap()) {
2169     SDValue Op = BuildSDIV(N);
2170     if (Op.getNode()) return Op;
2171   }
2172
2173   // undef / X -> 0
2174   if (N0.getOpcode() == ISD::UNDEF)
2175     return DAG.getConstant(0, VT);
2176   // X / undef -> undef
2177   if (N1.getOpcode() == ISD::UNDEF)
2178     return N1;
2179
2180   return SDValue();
2181 }
2182
2183 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2184   SDValue N0 = N->getOperand(0);
2185   SDValue N1 = N->getOperand(1);
2186   EVT VT = N->getValueType(0);
2187
2188   // fold vector ops
2189   if (VT.isVector()) {
2190     SDValue FoldedVOp = SimplifyVBinOp(N);
2191     if (FoldedVOp.getNode()) return FoldedVOp;
2192   }
2193
2194   // fold (udiv c1, c2) -> c1/c2
2195   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2196   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2197   if (N0C && N1C && !N1C->isNullValue())
2198     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2199   // fold (udiv x, (1 << c)) -> x >>u c
2200   if (N1C && N1C->getAPIntValue().isPowerOf2())
2201     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2202                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2203                                        getShiftAmountTy(N0.getValueType())));
2204   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2205   if (N1.getOpcode() == ISD::SHL) {
2206     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2207       if (SHC->getAPIntValue().isPowerOf2()) {
2208         EVT ADDVT = N1.getOperand(1).getValueType();
2209         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2210                                   N1.getOperand(1),
2211                                   DAG.getConstant(SHC->getAPIntValue()
2212                                                                   .logBase2(),
2213                                                   ADDVT));
2214         AddToWorklist(Add.getNode());
2215         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2216       }
2217     }
2218   }
2219   // fold (udiv x, c) -> alternate
2220   if (N1C && !TLI.isIntDivCheap()) {
2221     SDValue Op = BuildUDIV(N);
2222     if (Op.getNode()) return Op;
2223   }
2224
2225   // undef / X -> 0
2226   if (N0.getOpcode() == ISD::UNDEF)
2227     return DAG.getConstant(0, VT);
2228   // X / undef -> undef
2229   if (N1.getOpcode() == ISD::UNDEF)
2230     return N1;
2231
2232   return SDValue();
2233 }
2234
2235 SDValue DAGCombiner::visitSREM(SDNode *N) {
2236   SDValue N0 = N->getOperand(0);
2237   SDValue N1 = N->getOperand(1);
2238   EVT VT = N->getValueType(0);
2239
2240   // fold (srem c1, c2) -> c1%c2
2241   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2242   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2243   if (N0C && N1C && !N1C->isNullValue())
2244     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2245   // If we know the sign bits of both operands are zero, strength reduce to a
2246   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2247   if (!VT.isVector()) {
2248     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2249       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2250   }
2251
2252   // If X/C can be simplified by the division-by-constant logic, lower
2253   // X%C to the equivalent of X-X/C*C.
2254   if (N1C && !N1C->isNullValue()) {
2255     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2256     AddToWorklist(Div.getNode());
2257     SDValue OptimizedDiv = combine(Div.getNode());
2258     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2259       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2260                                 OptimizedDiv, N1);
2261       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2262       AddToWorklist(Mul.getNode());
2263       return Sub;
2264     }
2265   }
2266
2267   // undef % X -> 0
2268   if (N0.getOpcode() == ISD::UNDEF)
2269     return DAG.getConstant(0, VT);
2270   // X % undef -> undef
2271   if (N1.getOpcode() == ISD::UNDEF)
2272     return N1;
2273
2274   return SDValue();
2275 }
2276
2277 SDValue DAGCombiner::visitUREM(SDNode *N) {
2278   SDValue N0 = N->getOperand(0);
2279   SDValue N1 = N->getOperand(1);
2280   EVT VT = N->getValueType(0);
2281
2282   // fold (urem c1, c2) -> c1%c2
2283   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2284   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2285   if (N0C && N1C && !N1C->isNullValue())
2286     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2287   // fold (urem x, pow2) -> (and x, pow2-1)
2288   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2289     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2290                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2291   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2292   if (N1.getOpcode() == ISD::SHL) {
2293     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2294       if (SHC->getAPIntValue().isPowerOf2()) {
2295         SDValue Add =
2296           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2297                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2298                                  VT));
2299         AddToWorklist(Add.getNode());
2300         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2301       }
2302     }
2303   }
2304
2305   // If X/C can be simplified by the division-by-constant logic, lower
2306   // X%C to the equivalent of X-X/C*C.
2307   if (N1C && !N1C->isNullValue()) {
2308     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2309     AddToWorklist(Div.getNode());
2310     SDValue OptimizedDiv = combine(Div.getNode());
2311     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2312       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2313                                 OptimizedDiv, N1);
2314       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2315       AddToWorklist(Mul.getNode());
2316       return Sub;
2317     }
2318   }
2319
2320   // undef % X -> 0
2321   if (N0.getOpcode() == ISD::UNDEF)
2322     return DAG.getConstant(0, VT);
2323   // X % undef -> undef
2324   if (N1.getOpcode() == ISD::UNDEF)
2325     return N1;
2326
2327   return SDValue();
2328 }
2329
2330 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2331   SDValue N0 = N->getOperand(0);
2332   SDValue N1 = N->getOperand(1);
2333   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2334   EVT VT = N->getValueType(0);
2335   SDLoc DL(N);
2336
2337   // fold (mulhs x, 0) -> 0
2338   if (N1C && N1C->isNullValue())
2339     return N1;
2340   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2341   if (N1C && N1C->getAPIntValue() == 1)
2342     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2343                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2344                                        getShiftAmountTy(N0.getValueType())));
2345   // fold (mulhs x, undef) -> 0
2346   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2347     return DAG.getConstant(0, VT);
2348
2349   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2350   // plus a shift.
2351   if (VT.isSimple() && !VT.isVector()) {
2352     MVT Simple = VT.getSimpleVT();
2353     unsigned SimpleSize = Simple.getSizeInBits();
2354     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2355     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2356       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2357       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2358       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2359       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2360             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2361       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2362     }
2363   }
2364
2365   return SDValue();
2366 }
2367
2368 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2369   SDValue N0 = N->getOperand(0);
2370   SDValue N1 = N->getOperand(1);
2371   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2372   EVT VT = N->getValueType(0);
2373   SDLoc DL(N);
2374
2375   // fold (mulhu x, 0) -> 0
2376   if (N1C && N1C->isNullValue())
2377     return N1;
2378   // fold (mulhu x, 1) -> 0
2379   if (N1C && N1C->getAPIntValue() == 1)
2380     return DAG.getConstant(0, N0.getValueType());
2381   // fold (mulhu x, undef) -> 0
2382   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2383     return DAG.getConstant(0, VT);
2384
2385   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2386   // plus a shift.
2387   if (VT.isSimple() && !VT.isVector()) {
2388     MVT Simple = VT.getSimpleVT();
2389     unsigned SimpleSize = Simple.getSizeInBits();
2390     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2391     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2392       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2393       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2394       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2395       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2396             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2397       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2398     }
2399   }
2400
2401   return SDValue();
2402 }
2403
2404 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2405 /// give the opcodes for the two computations that are being performed. Return
2406 /// true if a simplification was made.
2407 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2408                                                 unsigned HiOp) {
2409   // If the high half is not needed, just compute the low half.
2410   bool HiExists = N->hasAnyUseOfValue(1);
2411   if (!HiExists &&
2412       (!LegalOperations ||
2413        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2414     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2415     return CombineTo(N, Res, Res);
2416   }
2417
2418   // If the low half is not needed, just compute the high half.
2419   bool LoExists = N->hasAnyUseOfValue(0);
2420   if (!LoExists &&
2421       (!LegalOperations ||
2422        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2423     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2424     return CombineTo(N, Res, Res);
2425   }
2426
2427   // If both halves are used, return as it is.
2428   if (LoExists && HiExists)
2429     return SDValue();
2430
2431   // If the two computed results can be simplified separately, separate them.
2432   if (LoExists) {
2433     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2434     AddToWorklist(Lo.getNode());
2435     SDValue LoOpt = combine(Lo.getNode());
2436     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2437         (!LegalOperations ||
2438          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2439       return CombineTo(N, LoOpt, LoOpt);
2440   }
2441
2442   if (HiExists) {
2443     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2444     AddToWorklist(Hi.getNode());
2445     SDValue HiOpt = combine(Hi.getNode());
2446     if (HiOpt.getNode() && HiOpt != Hi &&
2447         (!LegalOperations ||
2448          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2449       return CombineTo(N, HiOpt, HiOpt);
2450   }
2451
2452   return SDValue();
2453 }
2454
2455 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2456   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2457   if (Res.getNode()) return Res;
2458
2459   EVT VT = N->getValueType(0);
2460   SDLoc DL(N);
2461
2462   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2463   // plus a shift.
2464   if (VT.isSimple() && !VT.isVector()) {
2465     MVT Simple = VT.getSimpleVT();
2466     unsigned SimpleSize = Simple.getSizeInBits();
2467     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2468     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2469       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2470       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2471       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2472       // Compute the high part as N1.
2473       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2474             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2475       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2476       // Compute the low part as N0.
2477       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2478       return CombineTo(N, Lo, Hi);
2479     }
2480   }
2481
2482   return SDValue();
2483 }
2484
2485 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2486   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2487   if (Res.getNode()) return Res;
2488
2489   EVT VT = N->getValueType(0);
2490   SDLoc DL(N);
2491
2492   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2493   // plus a shift.
2494   if (VT.isSimple() && !VT.isVector()) {
2495     MVT Simple = VT.getSimpleVT();
2496     unsigned SimpleSize = Simple.getSizeInBits();
2497     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2498     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2499       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2500       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2501       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2502       // Compute the high part as N1.
2503       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2504             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2505       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2506       // Compute the low part as N0.
2507       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2508       return CombineTo(N, Lo, Hi);
2509     }
2510   }
2511
2512   return SDValue();
2513 }
2514
2515 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2516   // (smulo x, 2) -> (saddo x, x)
2517   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2518     if (C2->getAPIntValue() == 2)
2519       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2520                          N->getOperand(0), N->getOperand(0));
2521
2522   return SDValue();
2523 }
2524
2525 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2526   // (umulo x, 2) -> (uaddo x, x)
2527   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2528     if (C2->getAPIntValue() == 2)
2529       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2530                          N->getOperand(0), N->getOperand(0));
2531
2532   return SDValue();
2533 }
2534
2535 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2536   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2537   if (Res.getNode()) return Res;
2538
2539   return SDValue();
2540 }
2541
2542 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2543   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2544   if (Res.getNode()) return Res;
2545
2546   return SDValue();
2547 }
2548
2549 /// If this is a binary operator with two operands of the same opcode, try to
2550 /// simplify it.
2551 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2552   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2553   EVT VT = N0.getValueType();
2554   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2555
2556   // Bail early if none of these transforms apply.
2557   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2558
2559   // For each of OP in AND/OR/XOR:
2560   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2561   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2562   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2563   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2564   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2565   //
2566   // do not sink logical op inside of a vector extend, since it may combine
2567   // into a vsetcc.
2568   EVT Op0VT = N0.getOperand(0).getValueType();
2569   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2570        N0.getOpcode() == ISD::SIGN_EXTEND ||
2571        N0.getOpcode() == ISD::BSWAP ||
2572        // Avoid infinite looping with PromoteIntBinOp.
2573        (N0.getOpcode() == ISD::ANY_EXTEND &&
2574         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2575        (N0.getOpcode() == ISD::TRUNCATE &&
2576         (!TLI.isZExtFree(VT, Op0VT) ||
2577          !TLI.isTruncateFree(Op0VT, VT)) &&
2578         TLI.isTypeLegal(Op0VT))) &&
2579       !VT.isVector() &&
2580       Op0VT == N1.getOperand(0).getValueType() &&
2581       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2582     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2583                                  N0.getOperand(0).getValueType(),
2584                                  N0.getOperand(0), N1.getOperand(0));
2585     AddToWorklist(ORNode.getNode());
2586     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2587   }
2588
2589   // For each of OP in SHL/SRL/SRA/AND...
2590   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2591   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2592   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2593   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2594        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2595       N0.getOperand(1) == N1.getOperand(1)) {
2596     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2597                                  N0.getOperand(0).getValueType(),
2598                                  N0.getOperand(0), N1.getOperand(0));
2599     AddToWorklist(ORNode.getNode());
2600     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2601                        ORNode, N0.getOperand(1));
2602   }
2603
2604   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2605   // Only perform this optimization after type legalization and before
2606   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2607   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2608   // we don't want to undo this promotion.
2609   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2610   // on scalars.
2611   if ((N0.getOpcode() == ISD::BITCAST ||
2612        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2613       Level == AfterLegalizeTypes) {
2614     SDValue In0 = N0.getOperand(0);
2615     SDValue In1 = N1.getOperand(0);
2616     EVT In0Ty = In0.getValueType();
2617     EVT In1Ty = In1.getValueType();
2618     SDLoc DL(N);
2619     // If both incoming values are integers, and the original types are the
2620     // same.
2621     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2622       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2623       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2624       AddToWorklist(Op.getNode());
2625       return BC;
2626     }
2627   }
2628
2629   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2630   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2631   // If both shuffles use the same mask, and both shuffle within a single
2632   // vector, then it is worthwhile to move the swizzle after the operation.
2633   // The type-legalizer generates this pattern when loading illegal
2634   // vector types from memory. In many cases this allows additional shuffle
2635   // optimizations.
2636   // There are other cases where moving the shuffle after the xor/and/or
2637   // is profitable even if shuffles don't perform a swizzle.
2638   // If both shuffles use the same mask, and both shuffles have the same first
2639   // or second operand, then it might still be profitable to move the shuffle
2640   // after the xor/and/or operation.
2641   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2642     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2643     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2644
2645     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2646            "Inputs to shuffles are not the same type");
2647
2648     // Check that both shuffles use the same mask. The masks are known to be of
2649     // the same length because the result vector type is the same.
2650     // Check also that shuffles have only one use to avoid introducing extra
2651     // instructions.
2652     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2653         SVN0->getMask().equals(SVN1->getMask())) {
2654       SDValue ShOp = N0->getOperand(1);
2655
2656       // Don't try to fold this node if it requires introducing a
2657       // build vector of all zeros that might be illegal at this stage.
2658       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2659         if (!LegalTypes)
2660           ShOp = DAG.getConstant(0, VT);
2661         else
2662           ShOp = SDValue();
2663       }
2664
2665       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2666       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2667       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2668       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2669         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2670                                       N0->getOperand(0), N1->getOperand(0));
2671         AddToWorklist(NewNode.getNode());
2672         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2673                                     &SVN0->getMask()[0]);
2674       }
2675
2676       // Don't try to fold this node if it requires introducing a
2677       // build vector of all zeros that might be illegal at this stage.
2678       ShOp = N0->getOperand(0);
2679       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2680         if (!LegalTypes)
2681           ShOp = DAG.getConstant(0, VT);
2682         else
2683           ShOp = SDValue();
2684       }
2685
2686       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2687       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2688       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2689       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2690         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2691                                       N0->getOperand(1), N1->getOperand(1));
2692         AddToWorklist(NewNode.getNode());
2693         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2694                                     &SVN0->getMask()[0]);
2695       }
2696     }
2697   }
2698
2699   return SDValue();
2700 }
2701
2702 /// This contains all DAGCombine rules which reduce two values combined by
2703 /// an And operation to a single value. This makes them reusable in the context
2704 /// of visitSELECT(). Rules involving constants are not included as
2705 /// visitSELECT() already handles those cases.
2706 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2707                                   SDNode *LocReference) {
2708   EVT VT = N1.getValueType();
2709
2710   // fold (and x, undef) -> 0
2711   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2712     return DAG.getConstant(0, VT);
2713   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2714   SDValue LL, LR, RL, RR, CC0, CC1;
2715   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2716     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2717     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2718
2719     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2720         LL.getValueType().isInteger()) {
2721       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2722       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2723         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2724                                      LR.getValueType(), LL, RL);
2725         AddToWorklist(ORNode.getNode());
2726         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2727       }
2728       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2729       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2730         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2731                                       LR.getValueType(), LL, RL);
2732         AddToWorklist(ANDNode.getNode());
2733         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2734       }
2735       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2736       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2737         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2738                                      LR.getValueType(), LL, RL);
2739         AddToWorklist(ORNode.getNode());
2740         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2741       }
2742     }
2743     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2744     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2745         Op0 == Op1 && LL.getValueType().isInteger() &&
2746       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2747                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2748                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2749                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2750       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2751                                     LL, DAG.getConstant(1, LL.getValueType()));
2752       AddToWorklist(ADDNode.getNode());
2753       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2754                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2755     }
2756     // canonicalize equivalent to ll == rl
2757     if (LL == RR && LR == RL) {
2758       Op1 = ISD::getSetCCSwappedOperands(Op1);
2759       std::swap(RL, RR);
2760     }
2761     if (LL == RL && LR == RR) {
2762       bool isInteger = LL.getValueType().isInteger();
2763       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2764       if (Result != ISD::SETCC_INVALID &&
2765           (!LegalOperations ||
2766            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2767             TLI.isOperationLegal(ISD::SETCC,
2768                             getSetCCResultType(N0.getSimpleValueType())))))
2769         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2770                             LL, LR, Result);
2771     }
2772   }
2773
2774   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2775       VT.getSizeInBits() <= 64) {
2776     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2777       APInt ADDC = ADDI->getAPIntValue();
2778       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2779         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2780         // immediate for an add, but it is legal if its top c2 bits are set,
2781         // transform the ADD so the immediate doesn't need to be materialized
2782         // in a register.
2783         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2784           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2785                                              SRLI->getZExtValue());
2786           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2787             ADDC |= Mask;
2788             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2789               SDValue NewAdd =
2790                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2791                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2792               CombineTo(N0.getNode(), NewAdd);
2793               // Return N so it doesn't get rechecked!
2794               return SDValue(LocReference, 0);
2795             }
2796           }
2797         }
2798       }
2799     }
2800   }
2801
2802   return SDValue();
2803 }
2804
2805 SDValue DAGCombiner::visitAND(SDNode *N) {
2806   SDValue N0 = N->getOperand(0);
2807   SDValue N1 = N->getOperand(1);
2808   EVT VT = N1.getValueType();
2809
2810   // fold vector ops
2811   if (VT.isVector()) {
2812     SDValue FoldedVOp = SimplifyVBinOp(N);
2813     if (FoldedVOp.getNode()) return FoldedVOp;
2814
2815     // fold (and x, 0) -> 0, vector edition
2816     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2817       // do not return N0, because undef node may exist in N0
2818       return DAG.getConstant(
2819           APInt::getNullValue(
2820               N0.getValueType().getScalarType().getSizeInBits()),
2821           N0.getValueType());
2822     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2823       // do not return N1, because undef node may exist in N1
2824       return DAG.getConstant(
2825           APInt::getNullValue(
2826               N1.getValueType().getScalarType().getSizeInBits()),
2827           N1.getValueType());
2828
2829     // fold (and x, -1) -> x, vector edition
2830     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2831       return N1;
2832     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2833       return N0;
2834   }
2835
2836   // fold (and c1, c2) -> c1&c2
2837   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2838   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2839   if (N0C && N1C)
2840     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2841   // canonicalize constant to RHS
2842   if (N0C && !N1C)
2843     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2844   // fold (and x, -1) -> x
2845   if (N1C && N1C->isAllOnesValue())
2846     return N0;
2847   // if (and x, c) is known to be zero, return 0
2848   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2849   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2850                                    APInt::getAllOnesValue(BitWidth)))
2851     return DAG.getConstant(0, VT);
2852   // reassociate and
2853   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2854   if (RAND.getNode())
2855     return RAND;
2856   // fold (and (or x, C), D) -> D if (C & D) == D
2857   if (N1C && N0.getOpcode() == ISD::OR)
2858     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2859       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2860         return N1;
2861   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2862   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2863     SDValue N0Op0 = N0.getOperand(0);
2864     APInt Mask = ~N1C->getAPIntValue();
2865     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2866     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2867       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2868                                  N0.getValueType(), N0Op0);
2869
2870       // Replace uses of the AND with uses of the Zero extend node.
2871       CombineTo(N, Zext);
2872
2873       // We actually want to replace all uses of the any_extend with the
2874       // zero_extend, to avoid duplicating things.  This will later cause this
2875       // AND to be folded.
2876       CombineTo(N0.getNode(), Zext);
2877       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2878     }
2879   }
2880   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2881   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2882   // already be zero by virtue of the width of the base type of the load.
2883   //
2884   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2885   // more cases.
2886   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2887        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2888       N0.getOpcode() == ISD::LOAD) {
2889     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2890                                          N0 : N0.getOperand(0) );
2891
2892     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2893     // This can be a pure constant or a vector splat, in which case we treat the
2894     // vector as a scalar and use the splat value.
2895     APInt Constant = APInt::getNullValue(1);
2896     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2897       Constant = C->getAPIntValue();
2898     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2899       APInt SplatValue, SplatUndef;
2900       unsigned SplatBitSize;
2901       bool HasAnyUndefs;
2902       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2903                                              SplatBitSize, HasAnyUndefs);
2904       if (IsSplat) {
2905         // Undef bits can contribute to a possible optimisation if set, so
2906         // set them.
2907         SplatValue |= SplatUndef;
2908
2909         // The splat value may be something like "0x00FFFFFF", which means 0 for
2910         // the first vector value and FF for the rest, repeating. We need a mask
2911         // that will apply equally to all members of the vector, so AND all the
2912         // lanes of the constant together.
2913         EVT VT = Vector->getValueType(0);
2914         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2915
2916         // If the splat value has been compressed to a bitlength lower
2917         // than the size of the vector lane, we need to re-expand it to
2918         // the lane size.
2919         if (BitWidth > SplatBitSize)
2920           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2921                SplatBitSize < BitWidth;
2922                SplatBitSize = SplatBitSize * 2)
2923             SplatValue |= SplatValue.shl(SplatBitSize);
2924
2925         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2926         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2927         if (SplatBitSize % BitWidth == 0) {
2928           Constant = APInt::getAllOnesValue(BitWidth);
2929           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2930             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2931         }
2932       }
2933     }
2934
2935     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2936     // actually legal and isn't going to get expanded, else this is a false
2937     // optimisation.
2938     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2939                                                     Load->getValueType(0),
2940                                                     Load->getMemoryVT());
2941
2942     // Resize the constant to the same size as the original memory access before
2943     // extension. If it is still the AllOnesValue then this AND is completely
2944     // unneeded.
2945     Constant =
2946       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2947
2948     bool B;
2949     switch (Load->getExtensionType()) {
2950     default: B = false; break;
2951     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2952     case ISD::ZEXTLOAD:
2953     case ISD::NON_EXTLOAD: B = true; break;
2954     }
2955
2956     if (B && Constant.isAllOnesValue()) {
2957       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2958       // preserve semantics once we get rid of the AND.
2959       SDValue NewLoad(Load, 0);
2960       if (Load->getExtensionType() == ISD::EXTLOAD) {
2961         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2962                               Load->getValueType(0), SDLoc(Load),
2963                               Load->getChain(), Load->getBasePtr(),
2964                               Load->getOffset(), Load->getMemoryVT(),
2965                               Load->getMemOperand());
2966         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2967         if (Load->getNumValues() == 3) {
2968           // PRE/POST_INC loads have 3 values.
2969           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2970                            NewLoad.getValue(2) };
2971           CombineTo(Load, To, 3, true);
2972         } else {
2973           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2974         }
2975       }
2976
2977       // Fold the AND away, taking care not to fold to the old load node if we
2978       // replaced it.
2979       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2980
2981       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2982     }
2983   }
2984
2985   // fold (and (load x), 255) -> (zextload x, i8)
2986   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2987   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2988   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2989               (N0.getOpcode() == ISD::ANY_EXTEND &&
2990                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2991     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2992     LoadSDNode *LN0 = HasAnyExt
2993       ? cast<LoadSDNode>(N0.getOperand(0))
2994       : cast<LoadSDNode>(N0);
2995     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2996         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2997       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2998       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2999         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3000         EVT LoadedVT = LN0->getMemoryVT();
3001         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3002
3003         if (ExtVT == LoadedVT &&
3004             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3005                                                     ExtVT))) {
3006
3007           SDValue NewLoad =
3008             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3009                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3010                            LN0->getMemOperand());
3011           AddToWorklist(N);
3012           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3013           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3014         }
3015
3016         // Do not change the width of a volatile load.
3017         // Do not generate loads of non-round integer types since these can
3018         // be expensive (and would be wrong if the type is not byte sized).
3019         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3020             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3021                                                     ExtVT))) {
3022           EVT PtrType = LN0->getOperand(1).getValueType();
3023
3024           unsigned Alignment = LN0->getAlignment();
3025           SDValue NewPtr = LN0->getBasePtr();
3026
3027           // For big endian targets, we need to add an offset to the pointer
3028           // to load the correct bytes.  For little endian systems, we merely
3029           // need to read fewer bytes from the same pointer.
3030           if (TLI.isBigEndian()) {
3031             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3032             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3033             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3034             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3035                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
3036             Alignment = MinAlign(Alignment, PtrOff);
3037           }
3038
3039           AddToWorklist(NewPtr.getNode());
3040
3041           SDValue Load =
3042             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3043                            LN0->getChain(), NewPtr,
3044                            LN0->getPointerInfo(),
3045                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3046                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3047           AddToWorklist(N);
3048           CombineTo(LN0, Load, Load.getValue(1));
3049           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3050         }
3051       }
3052     }
3053   }
3054
3055   if (SDValue Combined = visitANDLike(N0, N1, N))
3056     return Combined;
3057
3058   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3059   if (N0.getOpcode() == N1.getOpcode()) {
3060     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3061     if (Tmp.getNode()) return Tmp;
3062   }
3063
3064   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3065   // fold (and (sra)) -> (and (srl)) when possible.
3066   if (!VT.isVector() &&
3067       SimplifyDemandedBits(SDValue(N, 0)))
3068     return SDValue(N, 0);
3069
3070   // fold (zext_inreg (extload x)) -> (zextload x)
3071   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3072     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3073     EVT MemVT = LN0->getMemoryVT();
3074     // If we zero all the possible extended bits, then we can turn this into
3075     // a zextload if we are running before legalize or the operation is legal.
3076     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3077     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3078                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3079         ((!LegalOperations && !LN0->isVolatile()) ||
3080          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3081       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3082                                        LN0->getChain(), LN0->getBasePtr(),
3083                                        MemVT, LN0->getMemOperand());
3084       AddToWorklist(N);
3085       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3086       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3087     }
3088   }
3089   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3090   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3091       N0.hasOneUse()) {
3092     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3093     EVT MemVT = LN0->getMemoryVT();
3094     // If we zero all the possible extended bits, then we can turn this into
3095     // a zextload if we are running before legalize or the operation is legal.
3096     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3097     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3098                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3099         ((!LegalOperations && !LN0->isVolatile()) ||
3100          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3101       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3102                                        LN0->getChain(), LN0->getBasePtr(),
3103                                        MemVT, LN0->getMemOperand());
3104       AddToWorklist(N);
3105       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3106       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3107     }
3108   }
3109   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3110   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3111     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3112                                        N0.getOperand(1), false);
3113     if (BSwap.getNode())
3114       return BSwap;
3115   }
3116
3117   return SDValue();
3118 }
3119
3120 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3121 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3122                                         bool DemandHighBits) {
3123   if (!LegalOperations)
3124     return SDValue();
3125
3126   EVT VT = N->getValueType(0);
3127   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3128     return SDValue();
3129   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3130     return SDValue();
3131
3132   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3133   bool LookPassAnd0 = false;
3134   bool LookPassAnd1 = false;
3135   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3136       std::swap(N0, N1);
3137   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3138       std::swap(N0, N1);
3139   if (N0.getOpcode() == ISD::AND) {
3140     if (!N0.getNode()->hasOneUse())
3141       return SDValue();
3142     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3143     if (!N01C || N01C->getZExtValue() != 0xFF00)
3144       return SDValue();
3145     N0 = N0.getOperand(0);
3146     LookPassAnd0 = true;
3147   }
3148
3149   if (N1.getOpcode() == ISD::AND) {
3150     if (!N1.getNode()->hasOneUse())
3151       return SDValue();
3152     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3153     if (!N11C || N11C->getZExtValue() != 0xFF)
3154       return SDValue();
3155     N1 = N1.getOperand(0);
3156     LookPassAnd1 = true;
3157   }
3158
3159   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3160     std::swap(N0, N1);
3161   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3162     return SDValue();
3163   if (!N0.getNode()->hasOneUse() ||
3164       !N1.getNode()->hasOneUse())
3165     return SDValue();
3166
3167   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3168   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3169   if (!N01C || !N11C)
3170     return SDValue();
3171   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3172     return SDValue();
3173
3174   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3175   SDValue N00 = N0->getOperand(0);
3176   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3177     if (!N00.getNode()->hasOneUse())
3178       return SDValue();
3179     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3180     if (!N001C || N001C->getZExtValue() != 0xFF)
3181       return SDValue();
3182     N00 = N00.getOperand(0);
3183     LookPassAnd0 = true;
3184   }
3185
3186   SDValue N10 = N1->getOperand(0);
3187   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3188     if (!N10.getNode()->hasOneUse())
3189       return SDValue();
3190     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3191     if (!N101C || N101C->getZExtValue() != 0xFF00)
3192       return SDValue();
3193     N10 = N10.getOperand(0);
3194     LookPassAnd1 = true;
3195   }
3196
3197   if (N00 != N10)
3198     return SDValue();
3199
3200   // Make sure everything beyond the low halfword gets set to zero since the SRL
3201   // 16 will clear the top bits.
3202   unsigned OpSizeInBits = VT.getSizeInBits();
3203   if (DemandHighBits && OpSizeInBits > 16) {
3204     // If the left-shift isn't masked out then the only way this is a bswap is
3205     // if all bits beyond the low 8 are 0. In that case the entire pattern
3206     // reduces to a left shift anyway: leave it for other parts of the combiner.
3207     if (!LookPassAnd0)
3208       return SDValue();
3209
3210     // However, if the right shift isn't masked out then it might be because
3211     // it's not needed. See if we can spot that too.
3212     if (!LookPassAnd1 &&
3213         !DAG.MaskedValueIsZero(
3214             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3215       return SDValue();
3216   }
3217
3218   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3219   if (OpSizeInBits > 16)
3220     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3221                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3222   return Res;
3223 }
3224
3225 /// Return true if the specified node is an element that makes up a 32-bit
3226 /// packed halfword byteswap.
3227 /// ((x & 0x000000ff) << 8) |
3228 /// ((x & 0x0000ff00) >> 8) |
3229 /// ((x & 0x00ff0000) << 8) |
3230 /// ((x & 0xff000000) >> 8)
3231 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3232   if (!N.getNode()->hasOneUse())
3233     return false;
3234
3235   unsigned Opc = N.getOpcode();
3236   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3237     return false;
3238
3239   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3240   if (!N1C)
3241     return false;
3242
3243   unsigned Num;
3244   switch (N1C->getZExtValue()) {
3245   default:
3246     return false;
3247   case 0xFF:       Num = 0; break;
3248   case 0xFF00:     Num = 1; break;
3249   case 0xFF0000:   Num = 2; break;
3250   case 0xFF000000: Num = 3; break;
3251   }
3252
3253   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3254   SDValue N0 = N.getOperand(0);
3255   if (Opc == ISD::AND) {
3256     if (Num == 0 || Num == 2) {
3257       // (x >> 8) & 0xff
3258       // (x >> 8) & 0xff0000
3259       if (N0.getOpcode() != ISD::SRL)
3260         return false;
3261       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3262       if (!C || C->getZExtValue() != 8)
3263         return false;
3264     } else {
3265       // (x << 8) & 0xff00
3266       // (x << 8) & 0xff000000
3267       if (N0.getOpcode() != ISD::SHL)
3268         return false;
3269       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3270       if (!C || C->getZExtValue() != 8)
3271         return false;
3272     }
3273   } else if (Opc == ISD::SHL) {
3274     // (x & 0xff) << 8
3275     // (x & 0xff0000) << 8
3276     if (Num != 0 && Num != 2)
3277       return false;
3278     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3279     if (!C || C->getZExtValue() != 8)
3280       return false;
3281   } else { // Opc == ISD::SRL
3282     // (x & 0xff00) >> 8
3283     // (x & 0xff000000) >> 8
3284     if (Num != 1 && Num != 3)
3285       return false;
3286     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3287     if (!C || C->getZExtValue() != 8)
3288       return false;
3289   }
3290
3291   if (Parts[Num])
3292     return false;
3293
3294   Parts[Num] = N0.getOperand(0).getNode();
3295   return true;
3296 }
3297
3298 /// Match a 32-bit packed halfword bswap. That is
3299 /// ((x & 0x000000ff) << 8) |
3300 /// ((x & 0x0000ff00) >> 8) |
3301 /// ((x & 0x00ff0000) << 8) |
3302 /// ((x & 0xff000000) >> 8)
3303 /// => (rotl (bswap x), 16)
3304 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3305   if (!LegalOperations)
3306     return SDValue();
3307
3308   EVT VT = N->getValueType(0);
3309   if (VT != MVT::i32)
3310     return SDValue();
3311   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3312     return SDValue();
3313
3314   // Look for either
3315   // (or (or (and), (and)), (or (and), (and)))
3316   // (or (or (or (and), (and)), (and)), (and))
3317   if (N0.getOpcode() != ISD::OR)
3318     return SDValue();
3319   SDValue N00 = N0.getOperand(0);
3320   SDValue N01 = N0.getOperand(1);
3321   SDNode *Parts[4] = {};
3322
3323   if (N1.getOpcode() == ISD::OR &&
3324       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3325     // (or (or (and), (and)), (or (and), (and)))
3326     SDValue N000 = N00.getOperand(0);
3327     if (!isBSwapHWordElement(N000, Parts))
3328       return SDValue();
3329
3330     SDValue N001 = N00.getOperand(1);
3331     if (!isBSwapHWordElement(N001, Parts))
3332       return SDValue();
3333     SDValue N010 = N01.getOperand(0);
3334     if (!isBSwapHWordElement(N010, Parts))
3335       return SDValue();
3336     SDValue N011 = N01.getOperand(1);
3337     if (!isBSwapHWordElement(N011, Parts))
3338       return SDValue();
3339   } else {
3340     // (or (or (or (and), (and)), (and)), (and))
3341     if (!isBSwapHWordElement(N1, Parts))
3342       return SDValue();
3343     if (!isBSwapHWordElement(N01, Parts))
3344       return SDValue();
3345     if (N00.getOpcode() != ISD::OR)
3346       return SDValue();
3347     SDValue N000 = N00.getOperand(0);
3348     if (!isBSwapHWordElement(N000, Parts))
3349       return SDValue();
3350     SDValue N001 = N00.getOperand(1);
3351     if (!isBSwapHWordElement(N001, Parts))
3352       return SDValue();
3353   }
3354
3355   // Make sure the parts are all coming from the same node.
3356   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3357     return SDValue();
3358
3359   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3360                               SDValue(Parts[0],0));
3361
3362   // Result of the bswap should be rotated by 16. If it's not legal, then
3363   // do  (x << 16) | (x >> 16).
3364   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3365   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3366     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3367   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3368     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3369   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3370                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3371                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3372 }
3373
3374 /// This contains all DAGCombine rules which reduce two values combined by
3375 /// an Or operation to a single value \see visitANDLike().
3376 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3377   EVT VT = N1.getValueType();
3378   // fold (or x, undef) -> -1
3379   if (!LegalOperations &&
3380       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3381     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3382     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3383   }
3384   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3385   SDValue LL, LR, RL, RR, CC0, CC1;
3386   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3387     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3388     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3389
3390     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3391         LL.getValueType().isInteger()) {
3392       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3393       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3394       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3395           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3396         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3397                                      LR.getValueType(), LL, RL);
3398         AddToWorklist(ORNode.getNode());
3399         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3400       }
3401       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3402       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3403       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3404           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3405         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3406                                       LR.getValueType(), LL, RL);
3407         AddToWorklist(ANDNode.getNode());
3408         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3409       }
3410     }
3411     // canonicalize equivalent to ll == rl
3412     if (LL == RR && LR == RL) {
3413       Op1 = ISD::getSetCCSwappedOperands(Op1);
3414       std::swap(RL, RR);
3415     }
3416     if (LL == RL && LR == RR) {
3417       bool isInteger = LL.getValueType().isInteger();
3418       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3419       if (Result != ISD::SETCC_INVALID &&
3420           (!LegalOperations ||
3421            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3422             TLI.isOperationLegal(ISD::SETCC,
3423               getSetCCResultType(N0.getValueType())))))
3424         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3425                             LL, LR, Result);
3426     }
3427   }
3428
3429   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3430   if (N0.getOpcode() == ISD::AND &&
3431       N1.getOpcode() == ISD::AND &&
3432       N0.getOperand(1).getOpcode() == ISD::Constant &&
3433       N1.getOperand(1).getOpcode() == ISD::Constant &&
3434       // Don't increase # computations.
3435       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3436     // We can only do this xform if we know that bits from X that are set in C2
3437     // but not in C1 are already zero.  Likewise for Y.
3438     const APInt &LHSMask =
3439       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3440     const APInt &RHSMask =
3441       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3442
3443     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3444         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3445       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3446                               N0.getOperand(0), N1.getOperand(0));
3447       return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, X,
3448                          DAG.getConstant(LHSMask | RHSMask, VT));
3449     }
3450   }
3451
3452   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3453   if (N0.getOpcode() == ISD::AND &&
3454       N1.getOpcode() == ISD::AND &&
3455       N0.getOperand(0) == N1.getOperand(0) &&
3456       // Don't increase # computations.
3457       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3458     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3459                             N0.getOperand(1), N1.getOperand(1));
3460     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3461   }
3462
3463   return SDValue();
3464 }
3465
3466 SDValue DAGCombiner::visitOR(SDNode *N) {
3467   SDValue N0 = N->getOperand(0);
3468   SDValue N1 = N->getOperand(1);
3469   EVT VT = N1.getValueType();
3470
3471   // fold vector ops
3472   if (VT.isVector()) {
3473     SDValue FoldedVOp = SimplifyVBinOp(N);
3474     if (FoldedVOp.getNode()) return FoldedVOp;
3475
3476     // fold (or x, 0) -> x, vector edition
3477     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3478       return N1;
3479     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3480       return N0;
3481
3482     // fold (or x, -1) -> -1, vector edition
3483     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3484       // do not return N0, because undef node may exist in N0
3485       return DAG.getConstant(
3486           APInt::getAllOnesValue(
3487               N0.getValueType().getScalarType().getSizeInBits()),
3488           N0.getValueType());
3489     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3490       // do not return N1, because undef node may exist in N1
3491       return DAG.getConstant(
3492           APInt::getAllOnesValue(
3493               N1.getValueType().getScalarType().getSizeInBits()),
3494           N1.getValueType());
3495
3496     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3497     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3498     // Do this only if the resulting shuffle is legal.
3499     if (isa<ShuffleVectorSDNode>(N0) &&
3500         isa<ShuffleVectorSDNode>(N1) &&
3501         // Avoid folding a node with illegal type.
3502         TLI.isTypeLegal(VT) &&
3503         N0->getOperand(1) == N1->getOperand(1) &&
3504         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3505       bool CanFold = true;
3506       unsigned NumElts = VT.getVectorNumElements();
3507       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3508       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3509       // We construct two shuffle masks:
3510       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3511       // and N1 as the second operand.
3512       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3513       // and N0 as the second operand.
3514       // We do this because OR is commutable and therefore there might be
3515       // two ways to fold this node into a shuffle.
3516       SmallVector<int,4> Mask1;
3517       SmallVector<int,4> Mask2;
3518
3519       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3520         int M0 = SV0->getMaskElt(i);
3521         int M1 = SV1->getMaskElt(i);
3522
3523         // Both shuffle indexes are undef. Propagate Undef.
3524         if (M0 < 0 && M1 < 0) {
3525           Mask1.push_back(M0);
3526           Mask2.push_back(M0);
3527           continue;
3528         }
3529
3530         if (M0 < 0 || M1 < 0 ||
3531             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3532             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3533           CanFold = false;
3534           break;
3535         }
3536
3537         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3538         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3539       }
3540
3541       if (CanFold) {
3542         // Fold this sequence only if the resulting shuffle is 'legal'.
3543         if (TLI.isShuffleMaskLegal(Mask1, VT))
3544           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3545                                       N1->getOperand(0), &Mask1[0]);
3546         if (TLI.isShuffleMaskLegal(Mask2, VT))
3547           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3548                                       N0->getOperand(0), &Mask2[0]);
3549       }
3550     }
3551   }
3552
3553   // fold (or c1, c2) -> c1|c2
3554   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3555   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3556   if (N0C && N1C)
3557     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3558   // canonicalize constant to RHS
3559   if (N0C && !N1C)
3560     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3561   // fold (or x, 0) -> x
3562   if (N1C && N1C->isNullValue())
3563     return N0;
3564   // fold (or x, -1) -> -1
3565   if (N1C && N1C->isAllOnesValue())
3566     return N1;
3567   // fold (or x, c) -> c iff (x & ~c) == 0
3568   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3569     return N1;
3570
3571   if (SDValue Combined = visitORLike(N0, N1, N))
3572     return Combined;
3573
3574   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3575   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3576   if (BSwap.getNode())
3577     return BSwap;
3578   BSwap = MatchBSwapHWordLow(N, N0, N1);
3579   if (BSwap.getNode())
3580     return BSwap;
3581
3582   // reassociate or
3583   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3584   if (ROR.getNode())
3585     return ROR;
3586   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3587   // iff (c1 & c2) == 0.
3588   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3589              isa<ConstantSDNode>(N0.getOperand(1))) {
3590     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3591     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3592       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3593         return DAG.getNode(
3594             ISD::AND, SDLoc(N), VT,
3595             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3596       return SDValue();
3597     }
3598   }
3599   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3600   if (N0.getOpcode() == N1.getOpcode()) {
3601     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3602     if (Tmp.getNode()) return Tmp;
3603   }
3604
3605   // See if this is some rotate idiom.
3606   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3607     return SDValue(Rot, 0);
3608
3609   // Simplify the operands using demanded-bits information.
3610   if (!VT.isVector() &&
3611       SimplifyDemandedBits(SDValue(N, 0)))
3612     return SDValue(N, 0);
3613
3614   return SDValue();
3615 }
3616
3617 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3618 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3619   if (Op.getOpcode() == ISD::AND) {
3620     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3621       Mask = Op.getOperand(1);
3622       Op = Op.getOperand(0);
3623     } else {
3624       return false;
3625     }
3626   }
3627
3628   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3629     Shift = Op;
3630     return true;
3631   }
3632
3633   return false;
3634 }
3635
3636 // Return true if we can prove that, whenever Neg and Pos are both in the
3637 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3638 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3639 //
3640 //     (or (shift1 X, Neg), (shift2 X, Pos))
3641 //
3642 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3643 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3644 // to consider shift amounts with defined behavior.
3645 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3646   // If OpSize is a power of 2 then:
3647   //
3648   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3649   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3650   //
3651   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3652   // for the stronger condition:
3653   //
3654   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3655   //
3656   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3657   // we can just replace Neg with Neg' for the rest of the function.
3658   //
3659   // In other cases we check for the even stronger condition:
3660   //
3661   //     Neg == OpSize - Pos                                    [B]
3662   //
3663   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3664   // behavior if Pos == 0 (and consequently Neg == OpSize).
3665   //
3666   // We could actually use [A] whenever OpSize is a power of 2, but the
3667   // only extra cases that it would match are those uninteresting ones
3668   // where Neg and Pos are never in range at the same time.  E.g. for
3669   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3670   // as well as (sub 32, Pos), but:
3671   //
3672   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3673   //
3674   // always invokes undefined behavior for 32-bit X.
3675   //
3676   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3677   unsigned MaskLoBits = 0;
3678   if (Neg.getOpcode() == ISD::AND &&
3679       isPowerOf2_64(OpSize) &&
3680       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3681       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3682     Neg = Neg.getOperand(0);
3683     MaskLoBits = Log2_64(OpSize);
3684   }
3685
3686   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3687   if (Neg.getOpcode() != ISD::SUB)
3688     return 0;
3689   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3690   if (!NegC)
3691     return 0;
3692   SDValue NegOp1 = Neg.getOperand(1);
3693
3694   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3695   // Pos'.  The truncation is redundant for the purpose of the equality.
3696   if (MaskLoBits &&
3697       Pos.getOpcode() == ISD::AND &&
3698       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3699       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3700     Pos = Pos.getOperand(0);
3701
3702   // The condition we need is now:
3703   //
3704   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3705   //
3706   // If NegOp1 == Pos then we need:
3707   //
3708   //              OpSize & Mask == NegC & Mask
3709   //
3710   // (because "x & Mask" is a truncation and distributes through subtraction).
3711   APInt Width;
3712   if (Pos == NegOp1)
3713     Width = NegC->getAPIntValue();
3714   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3715   // Then the condition we want to prove becomes:
3716   //
3717   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3718   //
3719   // which, again because "x & Mask" is a truncation, becomes:
3720   //
3721   //                NegC & Mask == (OpSize - PosC) & Mask
3722   //              OpSize & Mask == (NegC + PosC) & Mask
3723   else if (Pos.getOpcode() == ISD::ADD &&
3724            Pos.getOperand(0) == NegOp1 &&
3725            Pos.getOperand(1).getOpcode() == ISD::Constant)
3726     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3727              NegC->getAPIntValue());
3728   else
3729     return false;
3730
3731   // Now we just need to check that OpSize & Mask == Width & Mask.
3732   if (MaskLoBits)
3733     // Opsize & Mask is 0 since Mask is Opsize - 1.
3734     return Width.getLoBits(MaskLoBits) == 0;
3735   return Width == OpSize;
3736 }
3737
3738 // A subroutine of MatchRotate used once we have found an OR of two opposite
3739 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3740 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3741 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3742 // Neg with outer conversions stripped away.
3743 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3744                                        SDValue Neg, SDValue InnerPos,
3745                                        SDValue InnerNeg, unsigned PosOpcode,
3746                                        unsigned NegOpcode, SDLoc DL) {
3747   // fold (or (shl x, (*ext y)),
3748   //          (srl x, (*ext (sub 32, y)))) ->
3749   //   (rotl x, y) or (rotr x, (sub 32, y))
3750   //
3751   // fold (or (shl x, (*ext (sub 32, y))),
3752   //          (srl x, (*ext y))) ->
3753   //   (rotr x, y) or (rotl x, (sub 32, y))
3754   EVT VT = Shifted.getValueType();
3755   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3756     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3757     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3758                        HasPos ? Pos : Neg).getNode();
3759   }
3760
3761   return nullptr;
3762 }
3763
3764 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3765 // idioms for rotate, and if the target supports rotation instructions, generate
3766 // a rot[lr].
3767 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3768   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3769   EVT VT = LHS.getValueType();
3770   if (!TLI.isTypeLegal(VT)) return nullptr;
3771
3772   // The target must have at least one rotate flavor.
3773   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3774   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3775   if (!HasROTL && !HasROTR) return nullptr;
3776
3777   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3778   SDValue LHSShift;   // The shift.
3779   SDValue LHSMask;    // AND value if any.
3780   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3781     return nullptr; // Not part of a rotate.
3782
3783   SDValue RHSShift;   // The shift.
3784   SDValue RHSMask;    // AND value if any.
3785   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3786     return nullptr; // Not part of a rotate.
3787
3788   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3789     return nullptr;   // Not shifting the same value.
3790
3791   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3792     return nullptr;   // Shifts must disagree.
3793
3794   // Canonicalize shl to left side in a shl/srl pair.
3795   if (RHSShift.getOpcode() == ISD::SHL) {
3796     std::swap(LHS, RHS);
3797     std::swap(LHSShift, RHSShift);
3798     std::swap(LHSMask , RHSMask );
3799   }
3800
3801   unsigned OpSizeInBits = VT.getSizeInBits();
3802   SDValue LHSShiftArg = LHSShift.getOperand(0);
3803   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3804   SDValue RHSShiftArg = RHSShift.getOperand(0);
3805   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3806
3807   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3808   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3809   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3810       RHSShiftAmt.getOpcode() == ISD::Constant) {
3811     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3812     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3813     if ((LShVal + RShVal) != OpSizeInBits)
3814       return nullptr;
3815
3816     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3817                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3818
3819     // If there is an AND of either shifted operand, apply it to the result.
3820     if (LHSMask.getNode() || RHSMask.getNode()) {
3821       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3822
3823       if (LHSMask.getNode()) {
3824         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3825         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3826       }
3827       if (RHSMask.getNode()) {
3828         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3829         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3830       }
3831
3832       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3833     }
3834
3835     return Rot.getNode();
3836   }
3837
3838   // If there is a mask here, and we have a variable shift, we can't be sure
3839   // that we're masking out the right stuff.
3840   if (LHSMask.getNode() || RHSMask.getNode())
3841     return nullptr;
3842
3843   // If the shift amount is sign/zext/any-extended just peel it off.
3844   SDValue LExtOp0 = LHSShiftAmt;
3845   SDValue RExtOp0 = RHSShiftAmt;
3846   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3847        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3848        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3849        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3850       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3851        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3852        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3853        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3854     LExtOp0 = LHSShiftAmt.getOperand(0);
3855     RExtOp0 = RHSShiftAmt.getOperand(0);
3856   }
3857
3858   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3859                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3860   if (TryL)
3861     return TryL;
3862
3863   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3864                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3865   if (TryR)
3866     return TryR;
3867
3868   return nullptr;
3869 }
3870
3871 SDValue DAGCombiner::visitXOR(SDNode *N) {
3872   SDValue N0 = N->getOperand(0);
3873   SDValue N1 = N->getOperand(1);
3874   EVT VT = N0.getValueType();
3875
3876   // fold vector ops
3877   if (VT.isVector()) {
3878     SDValue FoldedVOp = SimplifyVBinOp(N);
3879     if (FoldedVOp.getNode()) return FoldedVOp;
3880
3881     // fold (xor x, 0) -> x, vector edition
3882     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3883       return N1;
3884     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3885       return N0;
3886   }
3887
3888   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3889   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3890     return DAG.getConstant(0, VT);
3891   // fold (xor x, undef) -> undef
3892   if (N0.getOpcode() == ISD::UNDEF)
3893     return N0;
3894   if (N1.getOpcode() == ISD::UNDEF)
3895     return N1;
3896   // fold (xor c1, c2) -> c1^c2
3897   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3898   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3899   if (N0C && N1C)
3900     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3901   // canonicalize constant to RHS
3902   if (N0C && !N1C)
3903     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3904   // fold (xor x, 0) -> x
3905   if (N1C && N1C->isNullValue())
3906     return N0;
3907   // reassociate xor
3908   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3909   if (RXOR.getNode())
3910     return RXOR;
3911
3912   // fold !(x cc y) -> (x !cc y)
3913   SDValue LHS, RHS, CC;
3914   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3915     bool isInt = LHS.getValueType().isInteger();
3916     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3917                                                isInt);
3918
3919     if (!LegalOperations ||
3920         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3921       switch (N0.getOpcode()) {
3922       default:
3923         llvm_unreachable("Unhandled SetCC Equivalent!");
3924       case ISD::SETCC:
3925         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3926       case ISD::SELECT_CC:
3927         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3928                                N0.getOperand(3), NotCC);
3929       }
3930     }
3931   }
3932
3933   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3934   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3935       N0.getNode()->hasOneUse() &&
3936       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3937     SDValue V = N0.getOperand(0);
3938     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3939                     DAG.getConstant(1, V.getValueType()));
3940     AddToWorklist(V.getNode());
3941     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3942   }
3943
3944   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3945   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3946       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3947     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3948     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3949       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3950       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3951       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3952       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3953       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3954     }
3955   }
3956   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3957   if (N1C && N1C->isAllOnesValue() &&
3958       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3959     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3960     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3961       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3962       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3963       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3964       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3965       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3966     }
3967   }
3968   // fold (xor (and x, y), y) -> (and (not x), y)
3969   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3970       N0->getOperand(1) == N1) {
3971     SDValue X = N0->getOperand(0);
3972     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3973     AddToWorklist(NotX.getNode());
3974     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3975   }
3976   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3977   if (N1C && N0.getOpcode() == ISD::XOR) {
3978     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3979     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3980     if (N00C)
3981       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3982                          DAG.getConstant(N1C->getAPIntValue() ^
3983                                          N00C->getAPIntValue(), VT));
3984     if (N01C)
3985       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3986                          DAG.getConstant(N1C->getAPIntValue() ^
3987                                          N01C->getAPIntValue(), VT));
3988   }
3989   // fold (xor x, x) -> 0
3990   if (N0 == N1)
3991     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3992
3993   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
3994   // Here is a concrete example of this equivalence:
3995   // i16   x ==  14
3996   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
3997   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
3998   //
3999   // =>
4000   //
4001   // i16     ~1      == 0b1111111111111110
4002   // i16 rol(~1, 14) == 0b1011111111111111
4003   //
4004   // Some additional tips to help conceptualize this transform:
4005   // - Try to see the operation as placing a single zero in a value of all ones.
4006   // - There exists no value for x which would allow the result to contain zero.
4007   // - Values of x larger than the bitwidth are undefined and do not require a
4008   //   consistent result.
4009   // - Pushing the zero left requires shifting one bits in from the right.
4010   // A rotate left of ~1 is a nice way of achieving the desired result.
4011   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4012     if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4013       if (N0.getOpcode() == ISD::SHL)
4014         if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4015           if (N1C->isAllOnesValue() && ShlLHS->isOne())
4016             return DAG.getNode(ISD::ROTL, SDLoc(N), VT, DAG.getConstant(~1, VT),
4017                                N0.getOperand(1));
4018
4019   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4020   if (N0.getOpcode() == N1.getOpcode()) {
4021     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4022     if (Tmp.getNode()) return Tmp;
4023   }
4024
4025   // Simplify the expression using non-local knowledge.
4026   if (!VT.isVector() &&
4027       SimplifyDemandedBits(SDValue(N, 0)))
4028     return SDValue(N, 0);
4029
4030   return SDValue();
4031 }
4032
4033 /// Handle transforms common to the three shifts, when the shift amount is a
4034 /// constant.
4035 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4036   // We can't and shouldn't fold opaque constants.
4037   if (Amt->isOpaque())
4038     return SDValue();
4039
4040   SDNode *LHS = N->getOperand(0).getNode();
4041   if (!LHS->hasOneUse()) return SDValue();
4042
4043   // We want to pull some binops through shifts, so that we have (and (shift))
4044   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4045   // thing happens with address calculations, so it's important to canonicalize
4046   // it.
4047   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4048
4049   switch (LHS->getOpcode()) {
4050   default: return SDValue();
4051   case ISD::OR:
4052   case ISD::XOR:
4053     HighBitSet = false; // We can only transform sra if the high bit is clear.
4054     break;
4055   case ISD::AND:
4056     HighBitSet = true;  // We can only transform sra if the high bit is set.
4057     break;
4058   case ISD::ADD:
4059     if (N->getOpcode() != ISD::SHL)
4060       return SDValue(); // only shl(add) not sr[al](add).
4061     HighBitSet = false; // We can only transform sra if the high bit is clear.
4062     break;
4063   }
4064
4065   // We require the RHS of the binop to be a constant and not opaque as well.
4066   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4067   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4068
4069   // FIXME: disable this unless the input to the binop is a shift by a constant.
4070   // If it is not a shift, it pessimizes some common cases like:
4071   //
4072   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4073   //    int bar(int *X, int i) { return X[i & 255]; }
4074   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4075   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4076        BinOpLHSVal->getOpcode() != ISD::SRA &&
4077        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4078       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4079     return SDValue();
4080
4081   EVT VT = N->getValueType(0);
4082
4083   // If this is a signed shift right, and the high bit is modified by the
4084   // logical operation, do not perform the transformation. The highBitSet
4085   // boolean indicates the value of the high bit of the constant which would
4086   // cause it to be modified for this operation.
4087   if (N->getOpcode() == ISD::SRA) {
4088     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4089     if (BinOpRHSSignSet != HighBitSet)
4090       return SDValue();
4091   }
4092
4093   if (!TLI.isDesirableToCommuteWithShift(LHS))
4094     return SDValue();
4095
4096   // Fold the constants, shifting the binop RHS by the shift amount.
4097   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4098                                N->getValueType(0),
4099                                LHS->getOperand(1), N->getOperand(1));
4100   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4101
4102   // Create the new shift.
4103   SDValue NewShift = DAG.getNode(N->getOpcode(),
4104                                  SDLoc(LHS->getOperand(0)),
4105                                  VT, LHS->getOperand(0), N->getOperand(1));
4106
4107   // Create the new binop.
4108   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4109 }
4110
4111 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4112   assert(N->getOpcode() == ISD::TRUNCATE);
4113   assert(N->getOperand(0).getOpcode() == ISD::AND);
4114
4115   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4116   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4117     SDValue N01 = N->getOperand(0).getOperand(1);
4118
4119     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4120       EVT TruncVT = N->getValueType(0);
4121       SDValue N00 = N->getOperand(0).getOperand(0);
4122       APInt TruncC = N01C->getAPIntValue();
4123       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4124
4125       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4126                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4127                          DAG.getConstant(TruncC, TruncVT));
4128     }
4129   }
4130
4131   return SDValue();
4132 }
4133
4134 SDValue DAGCombiner::visitRotate(SDNode *N) {
4135   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4136   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4137       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4138     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4139     if (NewOp1.getNode())
4140       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4141                          N->getOperand(0), NewOp1);
4142   }
4143   return SDValue();
4144 }
4145
4146 SDValue DAGCombiner::visitSHL(SDNode *N) {
4147   SDValue N0 = N->getOperand(0);
4148   SDValue N1 = N->getOperand(1);
4149   EVT VT = N0.getValueType();
4150   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4151
4152   // fold vector ops
4153   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4154   if (VT.isVector()) {
4155     SDValue FoldedVOp = SimplifyVBinOp(N);
4156     if (FoldedVOp.getNode()) return FoldedVOp;
4157
4158     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4159     // If setcc produces all-one true value then:
4160     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4161     if (N1CV && N1CV->isConstant()) {
4162       if (N0.getOpcode() == ISD::AND) {
4163         SDValue N00 = N0->getOperand(0);
4164         SDValue N01 = N0->getOperand(1);
4165         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4166
4167         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4168             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4169                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4170           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
4171             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4172         }
4173       } else {
4174         N1C = isConstOrConstSplat(N1);
4175       }
4176     }
4177   }
4178
4179   // fold (shl c1, c2) -> c1<<c2
4180   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4181   if (N0C && N1C)
4182     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4183   // fold (shl 0, x) -> 0
4184   if (N0C && N0C->isNullValue())
4185     return N0;
4186   // fold (shl x, c >= size(x)) -> undef
4187   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4188     return DAG.getUNDEF(VT);
4189   // fold (shl x, 0) -> x
4190   if (N1C && N1C->isNullValue())
4191     return N0;
4192   // fold (shl undef, x) -> 0
4193   if (N0.getOpcode() == ISD::UNDEF)
4194     return DAG.getConstant(0, VT);
4195   // if (shl x, c) is known to be zero, return 0
4196   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4197                             APInt::getAllOnesValue(OpSizeInBits)))
4198     return DAG.getConstant(0, VT);
4199   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4200   if (N1.getOpcode() == ISD::TRUNCATE &&
4201       N1.getOperand(0).getOpcode() == ISD::AND) {
4202     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4203     if (NewOp1.getNode())
4204       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4205   }
4206
4207   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4208     return SDValue(N, 0);
4209
4210   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4211   if (N1C && N0.getOpcode() == ISD::SHL) {
4212     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4213       uint64_t c1 = N0C1->getZExtValue();
4214       uint64_t c2 = N1C->getZExtValue();
4215       if (c1 + c2 >= OpSizeInBits)
4216         return DAG.getConstant(0, VT);
4217       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4218                          DAG.getConstant(c1 + c2, N1.getValueType()));
4219     }
4220   }
4221
4222   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4223   // For this to be valid, the second form must not preserve any of the bits
4224   // that are shifted out by the inner shift in the first form.  This means
4225   // the outer shift size must be >= the number of bits added by the ext.
4226   // As a corollary, we don't care what kind of ext it is.
4227   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4228               N0.getOpcode() == ISD::ANY_EXTEND ||
4229               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4230       N0.getOperand(0).getOpcode() == ISD::SHL) {
4231     SDValue N0Op0 = N0.getOperand(0);
4232     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4233       uint64_t c1 = N0Op0C1->getZExtValue();
4234       uint64_t c2 = N1C->getZExtValue();
4235       EVT InnerShiftVT = N0Op0.getValueType();
4236       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4237       if (c2 >= OpSizeInBits - InnerShiftSize) {
4238         if (c1 + c2 >= OpSizeInBits)
4239           return DAG.getConstant(0, VT);
4240         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4241                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4242                                        N0Op0->getOperand(0)),
4243                            DAG.getConstant(c1 + c2, N1.getValueType()));
4244       }
4245     }
4246   }
4247
4248   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4249   // Only fold this if the inner zext has no other uses to avoid increasing
4250   // the total number of instructions.
4251   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4252       N0.getOperand(0).getOpcode() == ISD::SRL) {
4253     SDValue N0Op0 = N0.getOperand(0);
4254     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4255       uint64_t c1 = N0Op0C1->getZExtValue();
4256       if (c1 < VT.getScalarSizeInBits()) {
4257         uint64_t c2 = N1C->getZExtValue();
4258         if (c1 == c2) {
4259           SDValue NewOp0 = N0.getOperand(0);
4260           EVT CountVT = NewOp0.getOperand(1).getValueType();
4261           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4262                                        NewOp0, DAG.getConstant(c2, CountVT));
4263           AddToWorklist(NewSHL.getNode());
4264           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4265         }
4266       }
4267     }
4268   }
4269
4270   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4271   //                               (and (srl x, (sub c1, c2), MASK)
4272   // Only fold this if the inner shift has no other uses -- if it does, folding
4273   // this will increase the total number of instructions.
4274   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4275     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4276       uint64_t c1 = N0C1->getZExtValue();
4277       if (c1 < OpSizeInBits) {
4278         uint64_t c2 = N1C->getZExtValue();
4279         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4280         SDValue Shift;
4281         if (c2 > c1) {
4282           Mask = Mask.shl(c2 - c1);
4283           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4284                               DAG.getConstant(c2 - c1, N1.getValueType()));
4285         } else {
4286           Mask = Mask.lshr(c1 - c2);
4287           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4288                               DAG.getConstant(c1 - c2, N1.getValueType()));
4289         }
4290         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4291                            DAG.getConstant(Mask, VT));
4292       }
4293     }
4294   }
4295   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4296   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4297     unsigned BitSize = VT.getScalarSizeInBits();
4298     SDValue HiBitsMask =
4299       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4300                                             BitSize - N1C->getZExtValue()), VT);
4301     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4302                        HiBitsMask);
4303   }
4304
4305   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4306   // Variant of version done on multiply, except mul by a power of 2 is turned
4307   // into a shift.
4308   APInt Val;
4309   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4310       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4311        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4312     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4313     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4314     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4315   }
4316
4317   if (N1C) {
4318     SDValue NewSHL = visitShiftByConstant(N, N1C);
4319     if (NewSHL.getNode())
4320       return NewSHL;
4321   }
4322
4323   return SDValue();
4324 }
4325
4326 SDValue DAGCombiner::visitSRA(SDNode *N) {
4327   SDValue N0 = N->getOperand(0);
4328   SDValue N1 = N->getOperand(1);
4329   EVT VT = N0.getValueType();
4330   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4331
4332   // fold vector ops
4333   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4334   if (VT.isVector()) {
4335     SDValue FoldedVOp = SimplifyVBinOp(N);
4336     if (FoldedVOp.getNode()) return FoldedVOp;
4337
4338     N1C = isConstOrConstSplat(N1);
4339   }
4340
4341   // fold (sra c1, c2) -> (sra c1, c2)
4342   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4343   if (N0C && N1C)
4344     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4345   // fold (sra 0, x) -> 0
4346   if (N0C && N0C->isNullValue())
4347     return N0;
4348   // fold (sra -1, x) -> -1
4349   if (N0C && N0C->isAllOnesValue())
4350     return N0;
4351   // fold (sra x, (setge c, size(x))) -> undef
4352   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4353     return DAG.getUNDEF(VT);
4354   // fold (sra x, 0) -> x
4355   if (N1C && N1C->isNullValue())
4356     return N0;
4357   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4358   // sext_inreg.
4359   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4360     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4361     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4362     if (VT.isVector())
4363       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4364                                ExtVT, VT.getVectorNumElements());
4365     if ((!LegalOperations ||
4366          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4367       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4368                          N0.getOperand(0), DAG.getValueType(ExtVT));
4369   }
4370
4371   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4372   if (N1C && N0.getOpcode() == ISD::SRA) {
4373     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4374       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4375       if (Sum >= OpSizeInBits)
4376         Sum = OpSizeInBits - 1;
4377       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4378                          DAG.getConstant(Sum, N1.getValueType()));
4379     }
4380   }
4381
4382   // fold (sra (shl X, m), (sub result_size, n))
4383   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4384   // result_size - n != m.
4385   // If truncate is free for the target sext(shl) is likely to result in better
4386   // code.
4387   if (N0.getOpcode() == ISD::SHL && N1C) {
4388     // Get the two constanst of the shifts, CN0 = m, CN = n.
4389     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4390     if (N01C) {
4391       LLVMContext &Ctx = *DAG.getContext();
4392       // Determine what the truncate's result bitsize and type would be.
4393       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4394
4395       if (VT.isVector())
4396         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4397
4398       // Determine the residual right-shift amount.
4399       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4400
4401       // If the shift is not a no-op (in which case this should be just a sign
4402       // extend already), the truncated to type is legal, sign_extend is legal
4403       // on that type, and the truncate to that type is both legal and free,
4404       // perform the transform.
4405       if ((ShiftAmt > 0) &&
4406           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4407           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4408           TLI.isTruncateFree(VT, TruncVT)) {
4409
4410           SDValue Amt = DAG.getConstant(ShiftAmt,
4411               getShiftAmountTy(N0.getOperand(0).getValueType()));
4412           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4413                                       N0.getOperand(0), Amt);
4414           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4415                                       Shift);
4416           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4417                              N->getValueType(0), Trunc);
4418       }
4419     }
4420   }
4421
4422   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4423   if (N1.getOpcode() == ISD::TRUNCATE &&
4424       N1.getOperand(0).getOpcode() == ISD::AND) {
4425     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4426     if (NewOp1.getNode())
4427       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4428   }
4429
4430   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4431   //      if c1 is equal to the number of bits the trunc removes
4432   if (N0.getOpcode() == ISD::TRUNCATE &&
4433       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4434        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4435       N0.getOperand(0).hasOneUse() &&
4436       N0.getOperand(0).getOperand(1).hasOneUse() &&
4437       N1C) {
4438     SDValue N0Op0 = N0.getOperand(0);
4439     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4440       unsigned LargeShiftVal = LargeShift->getZExtValue();
4441       EVT LargeVT = N0Op0.getValueType();
4442
4443       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4444         SDValue Amt =
4445           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4446                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4447         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4448                                   N0Op0.getOperand(0), Amt);
4449         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4450       }
4451     }
4452   }
4453
4454   // Simplify, based on bits shifted out of the LHS.
4455   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4456     return SDValue(N, 0);
4457
4458
4459   // If the sign bit is known to be zero, switch this to a SRL.
4460   if (DAG.SignBitIsZero(N0))
4461     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4462
4463   if (N1C) {
4464     SDValue NewSRA = visitShiftByConstant(N, N1C);
4465     if (NewSRA.getNode())
4466       return NewSRA;
4467   }
4468
4469   return SDValue();
4470 }
4471
4472 SDValue DAGCombiner::visitSRL(SDNode *N) {
4473   SDValue N0 = N->getOperand(0);
4474   SDValue N1 = N->getOperand(1);
4475   EVT VT = N0.getValueType();
4476   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4477
4478   // fold vector ops
4479   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4480   if (VT.isVector()) {
4481     SDValue FoldedVOp = SimplifyVBinOp(N);
4482     if (FoldedVOp.getNode()) return FoldedVOp;
4483
4484     N1C = isConstOrConstSplat(N1);
4485   }
4486
4487   // fold (srl c1, c2) -> c1 >>u c2
4488   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4489   if (N0C && N1C)
4490     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4491   // fold (srl 0, x) -> 0
4492   if (N0C && N0C->isNullValue())
4493     return N0;
4494   // fold (srl x, c >= size(x)) -> undef
4495   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4496     return DAG.getUNDEF(VT);
4497   // fold (srl x, 0) -> x
4498   if (N1C && N1C->isNullValue())
4499     return N0;
4500   // if (srl x, c) is known to be zero, return 0
4501   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4502                                    APInt::getAllOnesValue(OpSizeInBits)))
4503     return DAG.getConstant(0, VT);
4504
4505   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4506   if (N1C && N0.getOpcode() == ISD::SRL) {
4507     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4508       uint64_t c1 = N01C->getZExtValue();
4509       uint64_t c2 = N1C->getZExtValue();
4510       if (c1 + c2 >= OpSizeInBits)
4511         return DAG.getConstant(0, VT);
4512       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4513                          DAG.getConstant(c1 + c2, N1.getValueType()));
4514     }
4515   }
4516
4517   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4518   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4519       N0.getOperand(0).getOpcode() == ISD::SRL &&
4520       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4521     uint64_t c1 =
4522       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4523     uint64_t c2 = N1C->getZExtValue();
4524     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4525     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4526     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4527     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4528     if (c1 + OpSizeInBits == InnerShiftSize) {
4529       if (c1 + c2 >= InnerShiftSize)
4530         return DAG.getConstant(0, VT);
4531       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4532                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4533                                      N0.getOperand(0)->getOperand(0),
4534                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4535     }
4536   }
4537
4538   // fold (srl (shl x, c), c) -> (and x, cst2)
4539   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4540     unsigned BitSize = N0.getScalarValueSizeInBits();
4541     if (BitSize <= 64) {
4542       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4543       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4544                          DAG.getConstant(~0ULL >> ShAmt, VT));
4545     }
4546   }
4547
4548   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4549   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4550     // Shifting in all undef bits?
4551     EVT SmallVT = N0.getOperand(0).getValueType();
4552     unsigned BitSize = SmallVT.getScalarSizeInBits();
4553     if (N1C->getZExtValue() >= BitSize)
4554       return DAG.getUNDEF(VT);
4555
4556     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4557       uint64_t ShiftAmt = N1C->getZExtValue();
4558       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4559                                        N0.getOperand(0),
4560                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4561       AddToWorklist(SmallShift.getNode());
4562       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4563       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4564                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4565                          DAG.getConstant(Mask, VT));
4566     }
4567   }
4568
4569   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4570   // bit, which is unmodified by sra.
4571   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4572     if (N0.getOpcode() == ISD::SRA)
4573       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4574   }
4575
4576   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4577   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4578       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4579     APInt KnownZero, KnownOne;
4580     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4581
4582     // If any of the input bits are KnownOne, then the input couldn't be all
4583     // zeros, thus the result of the srl will always be zero.
4584     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4585
4586     // If all of the bits input the to ctlz node are known to be zero, then
4587     // the result of the ctlz is "32" and the result of the shift is one.
4588     APInt UnknownBits = ~KnownZero;
4589     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4590
4591     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4592     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4593       // Okay, we know that only that the single bit specified by UnknownBits
4594       // could be set on input to the CTLZ node. If this bit is set, the SRL
4595       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4596       // to an SRL/XOR pair, which is likely to simplify more.
4597       unsigned ShAmt = UnknownBits.countTrailingZeros();
4598       SDValue Op = N0.getOperand(0);
4599
4600       if (ShAmt) {
4601         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4602                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4603         AddToWorklist(Op.getNode());
4604       }
4605
4606       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4607                          Op, DAG.getConstant(1, VT));
4608     }
4609   }
4610
4611   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4612   if (N1.getOpcode() == ISD::TRUNCATE &&
4613       N1.getOperand(0).getOpcode() == ISD::AND) {
4614     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4615     if (NewOp1.getNode())
4616       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4617   }
4618
4619   // fold operands of srl based on knowledge that the low bits are not
4620   // demanded.
4621   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4622     return SDValue(N, 0);
4623
4624   if (N1C) {
4625     SDValue NewSRL = visitShiftByConstant(N, N1C);
4626     if (NewSRL.getNode())
4627       return NewSRL;
4628   }
4629
4630   // Attempt to convert a srl of a load into a narrower zero-extending load.
4631   SDValue NarrowLoad = ReduceLoadWidth(N);
4632   if (NarrowLoad.getNode())
4633     return NarrowLoad;
4634
4635   // Here is a common situation. We want to optimize:
4636   //
4637   //   %a = ...
4638   //   %b = and i32 %a, 2
4639   //   %c = srl i32 %b, 1
4640   //   brcond i32 %c ...
4641   //
4642   // into
4643   //
4644   //   %a = ...
4645   //   %b = and %a, 2
4646   //   %c = setcc eq %b, 0
4647   //   brcond %c ...
4648   //
4649   // However when after the source operand of SRL is optimized into AND, the SRL
4650   // itself may not be optimized further. Look for it and add the BRCOND into
4651   // the worklist.
4652   if (N->hasOneUse()) {
4653     SDNode *Use = *N->use_begin();
4654     if (Use->getOpcode() == ISD::BRCOND)
4655       AddToWorklist(Use);
4656     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4657       // Also look pass the truncate.
4658       Use = *Use->use_begin();
4659       if (Use->getOpcode() == ISD::BRCOND)
4660         AddToWorklist(Use);
4661     }
4662   }
4663
4664   return SDValue();
4665 }
4666
4667 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4668   SDValue N0 = N->getOperand(0);
4669   EVT VT = N->getValueType(0);
4670
4671   // fold (ctlz c1) -> c2
4672   if (isa<ConstantSDNode>(N0))
4673     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4674   return SDValue();
4675 }
4676
4677 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4678   SDValue N0 = N->getOperand(0);
4679   EVT VT = N->getValueType(0);
4680
4681   // fold (ctlz_zero_undef c1) -> c2
4682   if (isa<ConstantSDNode>(N0))
4683     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4684   return SDValue();
4685 }
4686
4687 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4688   SDValue N0 = N->getOperand(0);
4689   EVT VT = N->getValueType(0);
4690
4691   // fold (cttz c1) -> c2
4692   if (isa<ConstantSDNode>(N0))
4693     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4694   return SDValue();
4695 }
4696
4697 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4698   SDValue N0 = N->getOperand(0);
4699   EVT VT = N->getValueType(0);
4700
4701   // fold (cttz_zero_undef c1) -> c2
4702   if (isa<ConstantSDNode>(N0))
4703     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4704   return SDValue();
4705 }
4706
4707 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4708   SDValue N0 = N->getOperand(0);
4709   EVT VT = N->getValueType(0);
4710
4711   // fold (ctpop c1) -> c2
4712   if (isa<ConstantSDNode>(N0))
4713     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4714   return SDValue();
4715 }
4716
4717
4718 /// \brief Generate Min/Max node
4719 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4720                                    SDValue True, SDValue False,
4721                                    ISD::CondCode CC, const TargetLowering &TLI,
4722                                    SelectionDAG &DAG) {
4723   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4724     return SDValue();
4725
4726   switch (CC) {
4727   case ISD::SETOLT:
4728   case ISD::SETOLE:
4729   case ISD::SETLT:
4730   case ISD::SETLE:
4731   case ISD::SETULT:
4732   case ISD::SETULE: {
4733     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4734     if (TLI.isOperationLegal(Opcode, VT))
4735       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4736     return SDValue();
4737   }
4738   case ISD::SETOGT:
4739   case ISD::SETOGE:
4740   case ISD::SETGT:
4741   case ISD::SETGE:
4742   case ISD::SETUGT:
4743   case ISD::SETUGE: {
4744     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4745     if (TLI.isOperationLegal(Opcode, VT))
4746       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4747     return SDValue();
4748   }
4749   default:
4750     return SDValue();
4751   }
4752 }
4753
4754 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4755   SDValue N0 = N->getOperand(0);
4756   SDValue N1 = N->getOperand(1);
4757   SDValue N2 = N->getOperand(2);
4758   EVT VT = N->getValueType(0);
4759   EVT VT0 = N0.getValueType();
4760
4761   // fold (select C, X, X) -> X
4762   if (N1 == N2)
4763     return N1;
4764   // fold (select true, X, Y) -> X
4765   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4766   if (N0C && !N0C->isNullValue())
4767     return N1;
4768   // fold (select false, X, Y) -> Y
4769   if (N0C && N0C->isNullValue())
4770     return N2;
4771   // fold (select C, 1, X) -> (or C, X)
4772   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4773   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4774     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4775   // fold (select C, 0, 1) -> (xor C, 1)
4776   // We can't do this reliably if integer based booleans have different contents
4777   // to floating point based booleans. This is because we can't tell whether we
4778   // have an integer-based boolean or a floating-point-based boolean unless we
4779   // can find the SETCC that produced it and inspect its operands. This is
4780   // fairly easy if C is the SETCC node, but it can potentially be
4781   // undiscoverable (or not reasonably discoverable). For example, it could be
4782   // in another basic block or it could require searching a complicated
4783   // expression.
4784   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4785   if (VT.isInteger() &&
4786       (VT0 == MVT::i1 || (VT0.isInteger() &&
4787                           TLI.getBooleanContents(false, false) ==
4788                               TLI.getBooleanContents(false, true) &&
4789                           TLI.getBooleanContents(false, false) ==
4790                               TargetLowering::ZeroOrOneBooleanContent)) &&
4791       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4792     SDValue XORNode;
4793     if (VT == VT0)
4794       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4795                          N0, DAG.getConstant(1, VT0));
4796     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4797                           N0, DAG.getConstant(1, VT0));
4798     AddToWorklist(XORNode.getNode());
4799     if (VT.bitsGT(VT0))
4800       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4801     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4802   }
4803   // fold (select C, 0, X) -> (and (not C), X)
4804   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4805     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4806     AddToWorklist(NOTNode.getNode());
4807     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4808   }
4809   // fold (select C, X, 1) -> (or (not C), X)
4810   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4811     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4812     AddToWorklist(NOTNode.getNode());
4813     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4814   }
4815   // fold (select C, X, 0) -> (and C, X)
4816   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4817     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4818   // fold (select X, X, Y) -> (or X, Y)
4819   // fold (select X, 1, Y) -> (or X, Y)
4820   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4821     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4822   // fold (select X, Y, X) -> (and X, Y)
4823   // fold (select X, Y, 0) -> (and X, Y)
4824   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4825     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4826
4827   // If we can fold this based on the true/false value, do so.
4828   if (SimplifySelectOps(N, N1, N2))
4829     return SDValue(N, 0);  // Don't revisit N.
4830
4831   // fold selects based on a setcc into other things, such as min/max/abs
4832   if (N0.getOpcode() == ISD::SETCC) {
4833     // select x, y (fcmp lt x, y) -> fminnum x, y
4834     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4835     //
4836     // This is OK if we don't care about what happens if either operand is a
4837     // NaN.
4838     //
4839
4840     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4841     // no signed zeros as well as no nans.
4842     const TargetOptions &Options = DAG.getTarget().Options;
4843     if (Options.UnsafeFPMath &&
4844         VT.isFloatingPoint() && N0.hasOneUse() &&
4845         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4846       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4847
4848       SDValue FMinMax =
4849           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4850                               N1, N2, CC, TLI, DAG);
4851       if (FMinMax)
4852         return FMinMax;
4853     }
4854
4855     if ((!LegalOperations &&
4856          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4857         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4858       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4859                          N0.getOperand(0), N0.getOperand(1),
4860                          N1, N2, N0.getOperand(2));
4861     return SimplifySelect(SDLoc(N), N0, N1, N2);
4862   }
4863
4864   if (VT0 == MVT::i1) {
4865     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4866       // select (and Cond0, Cond1), X, Y
4867       //   -> select Cond0, (select Cond1, X, Y), Y
4868       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4869         SDValue Cond0 = N0->getOperand(0);
4870         SDValue Cond1 = N0->getOperand(1);
4871         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4872                                           N1.getValueType(), Cond1, N1, N2);
4873         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4874                            InnerSelect, N2);
4875       }
4876       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4877       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4878         SDValue Cond0 = N0->getOperand(0);
4879         SDValue Cond1 = N0->getOperand(1);
4880         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4881                                           N1.getValueType(), Cond1, N1, N2);
4882         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4883                            InnerSelect);
4884       }
4885     }
4886
4887     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4888     if (N1->getOpcode() == ISD::SELECT) {
4889       SDValue N1_0 = N1->getOperand(0);
4890       SDValue N1_1 = N1->getOperand(1);
4891       SDValue N1_2 = N1->getOperand(2);
4892       if (N1_2 == N2) {
4893         // Create the actual and node if we can generate good code for it.
4894         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4895           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4896                                     N0, N1_0);
4897           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4898                              N1_1, N2);
4899         }
4900         // Otherwise see if we can optimize the "and" to a better pattern.
4901         if (SDValue Combined = visitANDLike(N0, N1_0, N))
4902           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4903                              N1_1, N2);
4904       }
4905     }
4906     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4907     if (N2->getOpcode() == ISD::SELECT) {
4908       SDValue N2_0 = N2->getOperand(0);
4909       SDValue N2_1 = N2->getOperand(1);
4910       SDValue N2_2 = N2->getOperand(2);
4911       if (N2_1 == N1) {
4912         // Create the actual or node if we can generate good code for it.
4913         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4914           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4915                                    N0, N2_0);
4916           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4917                              N1, N2_2);
4918         }
4919         // Otherwise see if we can optimize to a better pattern.
4920         if (SDValue Combined = visitORLike(N0, N2_0, N))
4921           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4922                              N1, N2_2);
4923       }
4924     }
4925   }
4926
4927   return SDValue();
4928 }
4929
4930 static
4931 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4932   SDLoc DL(N);
4933   EVT LoVT, HiVT;
4934   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4935
4936   // Split the inputs.
4937   SDValue Lo, Hi, LL, LH, RL, RH;
4938   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4939   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4940
4941   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4942   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4943
4944   return std::make_pair(Lo, Hi);
4945 }
4946
4947 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4948 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4949 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4950   SDLoc dl(N);
4951   SDValue Cond = N->getOperand(0);
4952   SDValue LHS = N->getOperand(1);
4953   SDValue RHS = N->getOperand(2);
4954   EVT VT = N->getValueType(0);
4955   int NumElems = VT.getVectorNumElements();
4956   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4957          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4958          Cond.getOpcode() == ISD::BUILD_VECTOR);
4959
4960   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4961   // binary ones here.
4962   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4963     return SDValue();
4964
4965   // We're sure we have an even number of elements due to the
4966   // concat_vectors we have as arguments to vselect.
4967   // Skip BV elements until we find one that's not an UNDEF
4968   // After we find an UNDEF element, keep looping until we get to half the
4969   // length of the BV and see if all the non-undef nodes are the same.
4970   ConstantSDNode *BottomHalf = nullptr;
4971   for (int i = 0; i < NumElems / 2; ++i) {
4972     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4973       continue;
4974
4975     if (BottomHalf == nullptr)
4976       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4977     else if (Cond->getOperand(i).getNode() != BottomHalf)
4978       return SDValue();
4979   }
4980
4981   // Do the same for the second half of the BuildVector
4982   ConstantSDNode *TopHalf = nullptr;
4983   for (int i = NumElems / 2; i < NumElems; ++i) {
4984     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4985       continue;
4986
4987     if (TopHalf == nullptr)
4988       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4989     else if (Cond->getOperand(i).getNode() != TopHalf)
4990       return SDValue();
4991   }
4992
4993   assert(TopHalf && BottomHalf &&
4994          "One half of the selector was all UNDEFs and the other was all the "
4995          "same value. This should have been addressed before this function.");
4996   return DAG.getNode(
4997       ISD::CONCAT_VECTORS, dl, VT,
4998       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4999       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5000 }
5001
5002 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5003
5004   if (Level >= AfterLegalizeTypes)
5005     return SDValue();
5006
5007   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5008   SDValue Mask = MST->getMask();
5009   SDValue Data  = MST->getValue();
5010   SDLoc DL(N);
5011
5012   // If the MSTORE data type requires splitting and the mask is provided by a
5013   // SETCC, then split both nodes and its operands before legalization. This
5014   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5015   // and enables future optimizations (e.g. min/max pattern matching on X86).
5016   if (Mask.getOpcode() == ISD::SETCC) {
5017
5018     // Check if any splitting is required.
5019     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5020         TargetLowering::TypeSplitVector)
5021       return SDValue();
5022
5023     SDValue MaskLo, MaskHi, Lo, Hi;
5024     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5025
5026     EVT LoVT, HiVT;
5027     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5028
5029     SDValue Chain = MST->getChain();
5030     SDValue Ptr   = MST->getBasePtr();
5031
5032     EVT MemoryVT = MST->getMemoryVT();
5033     unsigned Alignment = MST->getOriginalAlignment();
5034
5035     // if Alignment is equal to the vector size,
5036     // take the half of it for the second part
5037     unsigned SecondHalfAlignment =
5038       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5039          Alignment/2 : Alignment;
5040
5041     EVT LoMemVT, HiMemVT;
5042     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5043
5044     SDValue DataLo, DataHi;
5045     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5046
5047     MachineMemOperand *MMO = DAG.getMachineFunction().
5048       getMachineMemOperand(MST->getPointerInfo(),
5049                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5050                            Alignment, MST->getAAInfo(), MST->getRanges());
5051
5052     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5053                             MST->isTruncatingStore());
5054
5055     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5056     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5057                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
5058
5059     MMO = DAG.getMachineFunction().
5060       getMachineMemOperand(MST->getPointerInfo(),
5061                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5062                            SecondHalfAlignment, MST->getAAInfo(),
5063                            MST->getRanges());
5064
5065     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5066                             MST->isTruncatingStore());
5067
5068     AddToWorklist(Lo.getNode());
5069     AddToWorklist(Hi.getNode());
5070
5071     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5072   }
5073   return SDValue();
5074 }
5075
5076 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5077
5078   if (Level >= AfterLegalizeTypes)
5079     return SDValue();
5080
5081   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5082   SDValue Mask = MLD->getMask();
5083   SDLoc DL(N);
5084
5085   // If the MLOAD result requires splitting and the mask is provided by a
5086   // SETCC, then split both nodes and its operands before legalization. This
5087   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5088   // and enables future optimizations (e.g. min/max pattern matching on X86).
5089
5090   if (Mask.getOpcode() == ISD::SETCC) {
5091     EVT VT = N->getValueType(0);
5092
5093     // Check if any splitting is required.
5094     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5095         TargetLowering::TypeSplitVector)
5096       return SDValue();
5097
5098     SDValue MaskLo, MaskHi, Lo, Hi;
5099     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5100
5101     SDValue Src0 = MLD->getSrc0();
5102     SDValue Src0Lo, Src0Hi;
5103     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5104
5105     EVT LoVT, HiVT;
5106     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5107
5108     SDValue Chain = MLD->getChain();
5109     SDValue Ptr   = MLD->getBasePtr();
5110     EVT MemoryVT = MLD->getMemoryVT();
5111     unsigned Alignment = MLD->getOriginalAlignment();
5112
5113     // if Alignment is equal to the vector size,
5114     // take the half of it for the second part
5115     unsigned SecondHalfAlignment =
5116       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5117          Alignment/2 : Alignment;
5118
5119     EVT LoMemVT, HiMemVT;
5120     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5121
5122     MachineMemOperand *MMO = DAG.getMachineFunction().
5123     getMachineMemOperand(MLD->getPointerInfo(),
5124                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5125                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5126
5127     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5128                            ISD::NON_EXTLOAD);
5129
5130     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5131     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5132                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
5133
5134     MMO = DAG.getMachineFunction().
5135     getMachineMemOperand(MLD->getPointerInfo(),
5136                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5137                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5138
5139     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5140                            ISD::NON_EXTLOAD);
5141
5142     AddToWorklist(Lo.getNode());
5143     AddToWorklist(Hi.getNode());
5144
5145     // Build a factor node to remember that this load is independent of the
5146     // other one.
5147     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5148                         Hi.getValue(1));
5149
5150     // Legalized the chain result - switch anything that used the old chain to
5151     // use the new one.
5152     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5153
5154     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5155
5156     SDValue RetOps[] = { LoadRes, Chain };
5157     return DAG.getMergeValues(RetOps, DL);
5158   }
5159   return SDValue();
5160 }
5161
5162 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5163   SDValue N0 = N->getOperand(0);
5164   SDValue N1 = N->getOperand(1);
5165   SDValue N2 = N->getOperand(2);
5166   SDLoc DL(N);
5167
5168   // Canonicalize integer abs.
5169   // vselect (setg[te] X,  0),  X, -X ->
5170   // vselect (setgt    X, -1),  X, -X ->
5171   // vselect (setl[te] X,  0), -X,  X ->
5172   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5173   if (N0.getOpcode() == ISD::SETCC) {
5174     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5175     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5176     bool isAbs = false;
5177     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5178
5179     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5180          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5181         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5182       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5183     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5184              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5185       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5186
5187     if (isAbs) {
5188       EVT VT = LHS.getValueType();
5189       SDValue Shift = DAG.getNode(
5190           ISD::SRA, DL, VT, LHS,
5191           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5192       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5193       AddToWorklist(Shift.getNode());
5194       AddToWorklist(Add.getNode());
5195       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5196     }
5197   }
5198
5199   // If the VSELECT result requires splitting and the mask is provided by a
5200   // SETCC, then split both nodes and its operands before legalization. This
5201   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5202   // and enables future optimizations (e.g. min/max pattern matching on X86).
5203   if (N0.getOpcode() == ISD::SETCC) {
5204     EVT VT = N->getValueType(0);
5205
5206     // Check if any splitting is required.
5207     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5208         TargetLowering::TypeSplitVector)
5209       return SDValue();
5210
5211     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5212     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5213     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5214     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5215
5216     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5217     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5218
5219     // Add the new VSELECT nodes to the work list in case they need to be split
5220     // again.
5221     AddToWorklist(Lo.getNode());
5222     AddToWorklist(Hi.getNode());
5223
5224     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5225   }
5226
5227   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5228   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5229     return N1;
5230   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5231   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5232     return N2;
5233
5234   // The ConvertSelectToConcatVector function is assuming both the above
5235   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5236   // and addressed.
5237   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5238       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5239       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5240     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5241     if (CV.getNode())
5242       return CV;
5243   }
5244
5245   return SDValue();
5246 }
5247
5248 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5249   SDValue N0 = N->getOperand(0);
5250   SDValue N1 = N->getOperand(1);
5251   SDValue N2 = N->getOperand(2);
5252   SDValue N3 = N->getOperand(3);
5253   SDValue N4 = N->getOperand(4);
5254   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5255
5256   // fold select_cc lhs, rhs, x, x, cc -> x
5257   if (N2 == N3)
5258     return N2;
5259
5260   // Determine if the condition we're dealing with is constant
5261   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5262                               N0, N1, CC, SDLoc(N), false);
5263   if (SCC.getNode()) {
5264     AddToWorklist(SCC.getNode());
5265
5266     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5267       if (!SCCC->isNullValue())
5268         return N2;    // cond always true -> true val
5269       else
5270         return N3;    // cond always false -> false val
5271     } else if (SCC->getOpcode() == ISD::UNDEF) {
5272       // When the condition is UNDEF, just return the first operand. This is
5273       // coherent the DAG creation, no setcc node is created in this case
5274       return N2;
5275     } else if (SCC.getOpcode() == ISD::SETCC) {
5276       // Fold to a simpler select_cc
5277       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5278                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5279                          SCC.getOperand(2));
5280     }
5281   }
5282
5283   // If we can fold this based on the true/false value, do so.
5284   if (SimplifySelectOps(N, N2, N3))
5285     return SDValue(N, 0);  // Don't revisit N.
5286
5287   // fold select_cc into other things, such as min/max/abs
5288   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5289 }
5290
5291 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5292   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5293                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5294                        SDLoc(N));
5295 }
5296
5297 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5298 // dag node into a ConstantSDNode or a build_vector of constants.
5299 // This function is called by the DAGCombiner when visiting sext/zext/aext
5300 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5301 // Vector extends are not folded if operations are legal; this is to
5302 // avoid introducing illegal build_vector dag nodes.
5303 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5304                                          SelectionDAG &DAG, bool LegalTypes,
5305                                          bool LegalOperations) {
5306   unsigned Opcode = N->getOpcode();
5307   SDValue N0 = N->getOperand(0);
5308   EVT VT = N->getValueType(0);
5309
5310   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5311          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5312
5313   // fold (sext c1) -> c1
5314   // fold (zext c1) -> c1
5315   // fold (aext c1) -> c1
5316   if (isa<ConstantSDNode>(N0))
5317     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5318
5319   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5320   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5321   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5322   EVT SVT = VT.getScalarType();
5323   if (!(VT.isVector() &&
5324       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5325       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5326     return nullptr;
5327
5328   // We can fold this node into a build_vector.
5329   unsigned VTBits = SVT.getSizeInBits();
5330   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5331   unsigned ShAmt = VTBits - EVTBits;
5332   SmallVector<SDValue, 8> Elts;
5333   unsigned NumElts = N0->getNumOperands();
5334   SDLoc DL(N);
5335
5336   for (unsigned i=0; i != NumElts; ++i) {
5337     SDValue Op = N0->getOperand(i);
5338     if (Op->getOpcode() == ISD::UNDEF) {
5339       Elts.push_back(DAG.getUNDEF(SVT));
5340       continue;
5341     }
5342
5343     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5344     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5345     if (Opcode == ISD::SIGN_EXTEND)
5346       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5347                                      SVT));
5348     else
5349       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5350                                      SVT));
5351   }
5352
5353   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5354 }
5355
5356 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5357 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5358 // transformation. Returns true if extension are possible and the above
5359 // mentioned transformation is profitable.
5360 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5361                                     unsigned ExtOpc,
5362                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5363                                     const TargetLowering &TLI) {
5364   bool HasCopyToRegUses = false;
5365   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5366   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5367                             UE = N0.getNode()->use_end();
5368        UI != UE; ++UI) {
5369     SDNode *User = *UI;
5370     if (User == N)
5371       continue;
5372     if (UI.getUse().getResNo() != N0.getResNo())
5373       continue;
5374     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5375     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5376       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5377       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5378         // Sign bits will be lost after a zext.
5379         return false;
5380       bool Add = false;
5381       for (unsigned i = 0; i != 2; ++i) {
5382         SDValue UseOp = User->getOperand(i);
5383         if (UseOp == N0)
5384           continue;
5385         if (!isa<ConstantSDNode>(UseOp))
5386           return false;
5387         Add = true;
5388       }
5389       if (Add)
5390         ExtendNodes.push_back(User);
5391       continue;
5392     }
5393     // If truncates aren't free and there are users we can't
5394     // extend, it isn't worthwhile.
5395     if (!isTruncFree)
5396       return false;
5397     // Remember if this value is live-out.
5398     if (User->getOpcode() == ISD::CopyToReg)
5399       HasCopyToRegUses = true;
5400   }
5401
5402   if (HasCopyToRegUses) {
5403     bool BothLiveOut = false;
5404     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5405          UI != UE; ++UI) {
5406       SDUse &Use = UI.getUse();
5407       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5408         BothLiveOut = true;
5409         break;
5410       }
5411     }
5412     if (BothLiveOut)
5413       // Both unextended and extended values are live out. There had better be
5414       // a good reason for the transformation.
5415       return ExtendNodes.size();
5416   }
5417   return true;
5418 }
5419
5420 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5421                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5422                                   ISD::NodeType ExtType) {
5423   // Extend SetCC uses if necessary.
5424   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5425     SDNode *SetCC = SetCCs[i];
5426     SmallVector<SDValue, 4> Ops;
5427
5428     for (unsigned j = 0; j != 2; ++j) {
5429       SDValue SOp = SetCC->getOperand(j);
5430       if (SOp == Trunc)
5431         Ops.push_back(ExtLoad);
5432       else
5433         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5434     }
5435
5436     Ops.push_back(SetCC->getOperand(2));
5437     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5438   }
5439 }
5440
5441 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5442 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5443   SDValue N0 = N->getOperand(0);
5444   EVT DstVT = N->getValueType(0);
5445   EVT SrcVT = N0.getValueType();
5446
5447   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5448           N->getOpcode() == ISD::ZERO_EXTEND) &&
5449          "Unexpected node type (not an extend)!");
5450
5451   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5452   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5453   //   (v8i32 (sext (v8i16 (load x))))
5454   // into:
5455   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5456   //                          (v4i32 (sextload (x + 16)))))
5457   // Where uses of the original load, i.e.:
5458   //   (v8i16 (load x))
5459   // are replaced with:
5460   //   (v8i16 (truncate
5461   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5462   //                            (v4i32 (sextload (x + 16)))))))
5463   //
5464   // This combine is only applicable to illegal, but splittable, vectors.
5465   // All legal types, and illegal non-vector types, are handled elsewhere.
5466   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5467   //
5468   if (N0->getOpcode() != ISD::LOAD)
5469     return SDValue();
5470
5471   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5472
5473   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5474       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5475       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5476     return SDValue();
5477
5478   SmallVector<SDNode *, 4> SetCCs;
5479   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5480     return SDValue();
5481
5482   ISD::LoadExtType ExtType =
5483       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5484
5485   // Try to split the vector types to get down to legal types.
5486   EVT SplitSrcVT = SrcVT;
5487   EVT SplitDstVT = DstVT;
5488   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5489          SplitSrcVT.getVectorNumElements() > 1) {
5490     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5491     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5492   }
5493
5494   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5495     return SDValue();
5496
5497   SDLoc DL(N);
5498   const unsigned NumSplits =
5499       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5500   const unsigned Stride = SplitSrcVT.getStoreSize();
5501   SmallVector<SDValue, 4> Loads;
5502   SmallVector<SDValue, 4> Chains;
5503
5504   SDValue BasePtr = LN0->getBasePtr();
5505   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5506     const unsigned Offset = Idx * Stride;
5507     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5508
5509     SDValue SplitLoad = DAG.getExtLoad(
5510         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5511         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5512         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5513         Align, LN0->getAAInfo());
5514
5515     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5516                           DAG.getConstant(Stride, BasePtr.getValueType()));
5517
5518     Loads.push_back(SplitLoad.getValue(0));
5519     Chains.push_back(SplitLoad.getValue(1));
5520   }
5521
5522   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5523   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5524
5525   CombineTo(N, NewValue);
5526
5527   // Replace uses of the original load (before extension)
5528   // with a truncate of the concatenated sextloaded vectors.
5529   SDValue Trunc =
5530       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5531   CombineTo(N0.getNode(), Trunc, NewChain);
5532   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5533                   (ISD::NodeType)N->getOpcode());
5534   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5535 }
5536
5537 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5538   SDValue N0 = N->getOperand(0);
5539   EVT VT = N->getValueType(0);
5540
5541   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5542                                               LegalOperations))
5543     return SDValue(Res, 0);
5544
5545   // fold (sext (sext x)) -> (sext x)
5546   // fold (sext (aext x)) -> (sext x)
5547   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5548     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5549                        N0.getOperand(0));
5550
5551   if (N0.getOpcode() == ISD::TRUNCATE) {
5552     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5553     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5554     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5555     if (NarrowLoad.getNode()) {
5556       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5557       if (NarrowLoad.getNode() != N0.getNode()) {
5558         CombineTo(N0.getNode(), NarrowLoad);
5559         // CombineTo deleted the truncate, if needed, but not what's under it.
5560         AddToWorklist(oye);
5561       }
5562       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5563     }
5564
5565     // See if the value being truncated is already sign extended.  If so, just
5566     // eliminate the trunc/sext pair.
5567     SDValue Op = N0.getOperand(0);
5568     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5569     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5570     unsigned DestBits = VT.getScalarType().getSizeInBits();
5571     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5572
5573     if (OpBits == DestBits) {
5574       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5575       // bits, it is already ready.
5576       if (NumSignBits > DestBits-MidBits)
5577         return Op;
5578     } else if (OpBits < DestBits) {
5579       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5580       // bits, just sext from i32.
5581       if (NumSignBits > OpBits-MidBits)
5582         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5583     } else {
5584       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5585       // bits, just truncate to i32.
5586       if (NumSignBits > OpBits-MidBits)
5587         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5588     }
5589
5590     // fold (sext (truncate x)) -> (sextinreg x).
5591     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5592                                                  N0.getValueType())) {
5593       if (OpBits < DestBits)
5594         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5595       else if (OpBits > DestBits)
5596         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5597       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5598                          DAG.getValueType(N0.getValueType()));
5599     }
5600   }
5601
5602   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5603   // Only generate vector extloads when 1) they're legal, and 2) they are
5604   // deemed desirable by the target.
5605   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5606       ((!LegalOperations && !VT.isVector() &&
5607         !cast<LoadSDNode>(N0)->isVolatile()) ||
5608        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5609     bool DoXform = true;
5610     SmallVector<SDNode*, 4> SetCCs;
5611     if (!N0.hasOneUse())
5612       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5613     if (VT.isVector())
5614       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5615     if (DoXform) {
5616       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5617       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5618                                        LN0->getChain(),
5619                                        LN0->getBasePtr(), N0.getValueType(),
5620                                        LN0->getMemOperand());
5621       CombineTo(N, ExtLoad);
5622       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5623                                   N0.getValueType(), ExtLoad);
5624       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5625       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5626                       ISD::SIGN_EXTEND);
5627       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5628     }
5629   }
5630
5631   // fold (sext (load x)) to multiple smaller sextloads.
5632   // Only on illegal but splittable vectors.
5633   if (SDValue ExtLoad = CombineExtLoad(N))
5634     return ExtLoad;
5635
5636   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5637   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5638   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5639       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5640     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5641     EVT MemVT = LN0->getMemoryVT();
5642     if ((!LegalOperations && !LN0->isVolatile()) ||
5643         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5644       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5645                                        LN0->getChain(),
5646                                        LN0->getBasePtr(), MemVT,
5647                                        LN0->getMemOperand());
5648       CombineTo(N, ExtLoad);
5649       CombineTo(N0.getNode(),
5650                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5651                             N0.getValueType(), ExtLoad),
5652                 ExtLoad.getValue(1));
5653       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5654     }
5655   }
5656
5657   // fold (sext (and/or/xor (load x), cst)) ->
5658   //      (and/or/xor (sextload x), (sext cst))
5659   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5660        N0.getOpcode() == ISD::XOR) &&
5661       isa<LoadSDNode>(N0.getOperand(0)) &&
5662       N0.getOperand(1).getOpcode() == ISD::Constant &&
5663       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5664       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5665     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5666     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5667       bool DoXform = true;
5668       SmallVector<SDNode*, 4> SetCCs;
5669       if (!N0.hasOneUse())
5670         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5671                                           SetCCs, TLI);
5672       if (DoXform) {
5673         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5674                                          LN0->getChain(), LN0->getBasePtr(),
5675                                          LN0->getMemoryVT(),
5676                                          LN0->getMemOperand());
5677         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5678         Mask = Mask.sext(VT.getSizeInBits());
5679         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5680                                   ExtLoad, DAG.getConstant(Mask, VT));
5681         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5682                                     SDLoc(N0.getOperand(0)),
5683                                     N0.getOperand(0).getValueType(), ExtLoad);
5684         CombineTo(N, And);
5685         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5686         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5687                         ISD::SIGN_EXTEND);
5688         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5689       }
5690     }
5691   }
5692
5693   if (N0.getOpcode() == ISD::SETCC) {
5694     EVT N0VT = N0.getOperand(0).getValueType();
5695     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5696     // Only do this before legalize for now.
5697     if (VT.isVector() && !LegalOperations &&
5698         TLI.getBooleanContents(N0VT) ==
5699             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5700       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5701       // of the same size as the compared operands. Only optimize sext(setcc())
5702       // if this is the case.
5703       EVT SVT = getSetCCResultType(N0VT);
5704
5705       // We know that the # elements of the results is the same as the
5706       // # elements of the compare (and the # elements of the compare result
5707       // for that matter).  Check to see that they are the same size.  If so,
5708       // we know that the element size of the sext'd result matches the
5709       // element size of the compare operands.
5710       if (VT.getSizeInBits() == SVT.getSizeInBits())
5711         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5712                              N0.getOperand(1),
5713                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5714
5715       // If the desired elements are smaller or larger than the source
5716       // elements we can use a matching integer vector type and then
5717       // truncate/sign extend
5718       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5719       if (SVT == MatchingVectorType) {
5720         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5721                                N0.getOperand(0), N0.getOperand(1),
5722                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5723         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5724       }
5725     }
5726
5727     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5728     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5729     SDValue NegOne =
5730       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5731     SDValue SCC =
5732       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5733                        NegOne, DAG.getConstant(0, VT),
5734                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5735     if (SCC.getNode()) return SCC;
5736
5737     if (!VT.isVector()) {
5738       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5739       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5740         SDLoc DL(N);
5741         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5742         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5743                                      N0.getOperand(0), N0.getOperand(1), CC);
5744         return DAG.getSelect(DL, VT, SetCC,
5745                              NegOne, DAG.getConstant(0, VT));
5746       }
5747     }
5748   }
5749
5750   // fold (sext x) -> (zext x) if the sign bit is known zero.
5751   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5752       DAG.SignBitIsZero(N0))
5753     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5754
5755   return SDValue();
5756 }
5757
5758 // isTruncateOf - If N is a truncate of some other value, return true, record
5759 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5760 // This function computes KnownZero to avoid a duplicated call to
5761 // computeKnownBits in the caller.
5762 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5763                          APInt &KnownZero) {
5764   APInt KnownOne;
5765   if (N->getOpcode() == ISD::TRUNCATE) {
5766     Op = N->getOperand(0);
5767     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5768     return true;
5769   }
5770
5771   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5772       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5773     return false;
5774
5775   SDValue Op0 = N->getOperand(0);
5776   SDValue Op1 = N->getOperand(1);
5777   assert(Op0.getValueType() == Op1.getValueType());
5778
5779   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5780   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5781   if (COp0 && COp0->isNullValue())
5782     Op = Op1;
5783   else if (COp1 && COp1->isNullValue())
5784     Op = Op0;
5785   else
5786     return false;
5787
5788   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5789
5790   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5791     return false;
5792
5793   return true;
5794 }
5795
5796 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5797   SDValue N0 = N->getOperand(0);
5798   EVT VT = N->getValueType(0);
5799
5800   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5801                                               LegalOperations))
5802     return SDValue(Res, 0);
5803
5804   // fold (zext (zext x)) -> (zext x)
5805   // fold (zext (aext x)) -> (zext x)
5806   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5807     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5808                        N0.getOperand(0));
5809
5810   // fold (zext (truncate x)) -> (zext x) or
5811   //      (zext (truncate x)) -> (truncate x)
5812   // This is valid when the truncated bits of x are already zero.
5813   // FIXME: We should extend this to work for vectors too.
5814   SDValue Op;
5815   APInt KnownZero;
5816   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5817     APInt TruncatedBits =
5818       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5819       APInt(Op.getValueSizeInBits(), 0) :
5820       APInt::getBitsSet(Op.getValueSizeInBits(),
5821                         N0.getValueSizeInBits(),
5822                         std::min(Op.getValueSizeInBits(),
5823                                  VT.getSizeInBits()));
5824     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5825       if (VT.bitsGT(Op.getValueType()))
5826         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5827       if (VT.bitsLT(Op.getValueType()))
5828         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5829
5830       return Op;
5831     }
5832   }
5833
5834   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5835   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5836   if (N0.getOpcode() == ISD::TRUNCATE) {
5837     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5838     if (NarrowLoad.getNode()) {
5839       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5840       if (NarrowLoad.getNode() != N0.getNode()) {
5841         CombineTo(N0.getNode(), NarrowLoad);
5842         // CombineTo deleted the truncate, if needed, but not what's under it.
5843         AddToWorklist(oye);
5844       }
5845       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5846     }
5847   }
5848
5849   // fold (zext (truncate x)) -> (and x, mask)
5850   if (N0.getOpcode() == ISD::TRUNCATE &&
5851       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5852
5853     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5854     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5855     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5856     if (NarrowLoad.getNode()) {
5857       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5858       if (NarrowLoad.getNode() != N0.getNode()) {
5859         CombineTo(N0.getNode(), NarrowLoad);
5860         // CombineTo deleted the truncate, if needed, but not what's under it.
5861         AddToWorklist(oye);
5862       }
5863       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5864     }
5865
5866     SDValue Op = N0.getOperand(0);
5867     if (Op.getValueType().bitsLT(VT)) {
5868       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5869       AddToWorklist(Op.getNode());
5870     } else if (Op.getValueType().bitsGT(VT)) {
5871       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5872       AddToWorklist(Op.getNode());
5873     }
5874     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5875                                   N0.getValueType().getScalarType());
5876   }
5877
5878   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5879   // if either of the casts is not free.
5880   if (N0.getOpcode() == ISD::AND &&
5881       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5882       N0.getOperand(1).getOpcode() == ISD::Constant &&
5883       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5884                            N0.getValueType()) ||
5885        !TLI.isZExtFree(N0.getValueType(), VT))) {
5886     SDValue X = N0.getOperand(0).getOperand(0);
5887     if (X.getValueType().bitsLT(VT)) {
5888       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5889     } else if (X.getValueType().bitsGT(VT)) {
5890       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5891     }
5892     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5893     Mask = Mask.zext(VT.getSizeInBits());
5894     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5895                        X, DAG.getConstant(Mask, VT));
5896   }
5897
5898   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5899   // Only generate vector extloads when 1) they're legal, and 2) they are
5900   // deemed desirable by the target.
5901   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5902       ((!LegalOperations && !VT.isVector() &&
5903         !cast<LoadSDNode>(N0)->isVolatile()) ||
5904        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5905     bool DoXform = true;
5906     SmallVector<SDNode*, 4> SetCCs;
5907     if (!N0.hasOneUse())
5908       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5909     if (VT.isVector())
5910       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5911     if (DoXform) {
5912       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5913       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5914                                        LN0->getChain(),
5915                                        LN0->getBasePtr(), N0.getValueType(),
5916                                        LN0->getMemOperand());
5917       CombineTo(N, ExtLoad);
5918       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5919                                   N0.getValueType(), ExtLoad);
5920       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5921
5922       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5923                       ISD::ZERO_EXTEND);
5924       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5925     }
5926   }
5927
5928   // fold (zext (load x)) to multiple smaller zextloads.
5929   // Only on illegal but splittable vectors.
5930   if (SDValue ExtLoad = CombineExtLoad(N))
5931     return ExtLoad;
5932
5933   // fold (zext (and/or/xor (load x), cst)) ->
5934   //      (and/or/xor (zextload x), (zext cst))
5935   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5936        N0.getOpcode() == ISD::XOR) &&
5937       isa<LoadSDNode>(N0.getOperand(0)) &&
5938       N0.getOperand(1).getOpcode() == ISD::Constant &&
5939       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5940       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5941     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5942     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5943       bool DoXform = true;
5944       SmallVector<SDNode*, 4> SetCCs;
5945       if (!N0.hasOneUse())
5946         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5947                                           SetCCs, TLI);
5948       if (DoXform) {
5949         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5950                                          LN0->getChain(), LN0->getBasePtr(),
5951                                          LN0->getMemoryVT(),
5952                                          LN0->getMemOperand());
5953         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5954         Mask = Mask.zext(VT.getSizeInBits());
5955         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5956                                   ExtLoad, DAG.getConstant(Mask, VT));
5957         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5958                                     SDLoc(N0.getOperand(0)),
5959                                     N0.getOperand(0).getValueType(), ExtLoad);
5960         CombineTo(N, And);
5961         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5962         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5963                         ISD::ZERO_EXTEND);
5964         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5965       }
5966     }
5967   }
5968
5969   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5970   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5971   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5972       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5973     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5974     EVT MemVT = LN0->getMemoryVT();
5975     if ((!LegalOperations && !LN0->isVolatile()) ||
5976         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5977       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5978                                        LN0->getChain(),
5979                                        LN0->getBasePtr(), MemVT,
5980                                        LN0->getMemOperand());
5981       CombineTo(N, ExtLoad);
5982       CombineTo(N0.getNode(),
5983                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5984                             ExtLoad),
5985                 ExtLoad.getValue(1));
5986       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5987     }
5988   }
5989
5990   if (N0.getOpcode() == ISD::SETCC) {
5991     if (!LegalOperations && VT.isVector() &&
5992         N0.getValueType().getVectorElementType() == MVT::i1) {
5993       EVT N0VT = N0.getOperand(0).getValueType();
5994       if (getSetCCResultType(N0VT) == N0.getValueType())
5995         return SDValue();
5996
5997       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5998       // Only do this before legalize for now.
5999       EVT EltVT = VT.getVectorElementType();
6000       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6001                                     DAG.getConstant(1, EltVT));
6002       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6003         // We know that the # elements of the results is the same as the
6004         // # elements of the compare (and the # elements of the compare result
6005         // for that matter).  Check to see that they are the same size.  If so,
6006         // we know that the element size of the sext'd result matches the
6007         // element size of the compare operands.
6008         return DAG.getNode(ISD::AND, SDLoc(N), VT,
6009                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6010                                          N0.getOperand(1),
6011                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6012                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
6013                                        OneOps));
6014
6015       // If the desired elements are smaller or larger than the source
6016       // elements we can use a matching integer vector type and then
6017       // truncate/sign extend
6018       EVT MatchingElementType =
6019         EVT::getIntegerVT(*DAG.getContext(),
6020                           N0VT.getScalarType().getSizeInBits());
6021       EVT MatchingVectorType =
6022         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6023                          N0VT.getVectorNumElements());
6024       SDValue VsetCC =
6025         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6026                       N0.getOperand(1),
6027                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6028       return DAG.getNode(ISD::AND, SDLoc(N), VT,
6029                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
6030                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
6031     }
6032
6033     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6034     SDValue SCC =
6035       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6036                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6037                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6038     if (SCC.getNode()) return SCC;
6039   }
6040
6041   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6042   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6043       isa<ConstantSDNode>(N0.getOperand(1)) &&
6044       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6045       N0.hasOneUse()) {
6046     SDValue ShAmt = N0.getOperand(1);
6047     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6048     if (N0.getOpcode() == ISD::SHL) {
6049       SDValue InnerZExt = N0.getOperand(0);
6050       // If the original shl may be shifting out bits, do not perform this
6051       // transformation.
6052       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6053         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6054       if (ShAmtVal > KnownZeroBits)
6055         return SDValue();
6056     }
6057
6058     SDLoc DL(N);
6059
6060     // Ensure that the shift amount is wide enough for the shifted value.
6061     if (VT.getSizeInBits() >= 256)
6062       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6063
6064     return DAG.getNode(N0.getOpcode(), DL, VT,
6065                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6066                        ShAmt);
6067   }
6068
6069   return SDValue();
6070 }
6071
6072 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6073   SDValue N0 = N->getOperand(0);
6074   EVT VT = N->getValueType(0);
6075
6076   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6077                                               LegalOperations))
6078     return SDValue(Res, 0);
6079
6080   // fold (aext (aext x)) -> (aext x)
6081   // fold (aext (zext x)) -> (zext x)
6082   // fold (aext (sext x)) -> (sext x)
6083   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6084       N0.getOpcode() == ISD::ZERO_EXTEND ||
6085       N0.getOpcode() == ISD::SIGN_EXTEND)
6086     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6087
6088   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6089   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6090   if (N0.getOpcode() == ISD::TRUNCATE) {
6091     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6092     if (NarrowLoad.getNode()) {
6093       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6094       if (NarrowLoad.getNode() != N0.getNode()) {
6095         CombineTo(N0.getNode(), NarrowLoad);
6096         // CombineTo deleted the truncate, if needed, but not what's under it.
6097         AddToWorklist(oye);
6098       }
6099       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6100     }
6101   }
6102
6103   // fold (aext (truncate x))
6104   if (N0.getOpcode() == ISD::TRUNCATE) {
6105     SDValue TruncOp = N0.getOperand(0);
6106     if (TruncOp.getValueType() == VT)
6107       return TruncOp; // x iff x size == zext size.
6108     if (TruncOp.getValueType().bitsGT(VT))
6109       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6110     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6111   }
6112
6113   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6114   // if the trunc is not free.
6115   if (N0.getOpcode() == ISD::AND &&
6116       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6117       N0.getOperand(1).getOpcode() == ISD::Constant &&
6118       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6119                           N0.getValueType())) {
6120     SDValue X = N0.getOperand(0).getOperand(0);
6121     if (X.getValueType().bitsLT(VT)) {
6122       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6123     } else if (X.getValueType().bitsGT(VT)) {
6124       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6125     }
6126     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6127     Mask = Mask.zext(VT.getSizeInBits());
6128     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6129                        X, DAG.getConstant(Mask, VT));
6130   }
6131
6132   // fold (aext (load x)) -> (aext (truncate (extload x)))
6133   // None of the supported targets knows how to perform load and any_ext
6134   // on vectors in one instruction.  We only perform this transformation on
6135   // scalars.
6136   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6137       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6138       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6139     bool DoXform = true;
6140     SmallVector<SDNode*, 4> SetCCs;
6141     if (!N0.hasOneUse())
6142       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6143     if (DoXform) {
6144       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6145       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6146                                        LN0->getChain(),
6147                                        LN0->getBasePtr(), N0.getValueType(),
6148                                        LN0->getMemOperand());
6149       CombineTo(N, ExtLoad);
6150       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6151                                   N0.getValueType(), ExtLoad);
6152       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6153       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6154                       ISD::ANY_EXTEND);
6155       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6156     }
6157   }
6158
6159   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6160   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6161   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6162   if (N0.getOpcode() == ISD::LOAD &&
6163       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6164       N0.hasOneUse()) {
6165     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6166     ISD::LoadExtType ExtType = LN0->getExtensionType();
6167     EVT MemVT = LN0->getMemoryVT();
6168     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6169       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6170                                        VT, LN0->getChain(), LN0->getBasePtr(),
6171                                        MemVT, LN0->getMemOperand());
6172       CombineTo(N, ExtLoad);
6173       CombineTo(N0.getNode(),
6174                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6175                             N0.getValueType(), ExtLoad),
6176                 ExtLoad.getValue(1));
6177       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6178     }
6179   }
6180
6181   if (N0.getOpcode() == ISD::SETCC) {
6182     // For vectors:
6183     // aext(setcc) -> vsetcc
6184     // aext(setcc) -> truncate(vsetcc)
6185     // aext(setcc) -> aext(vsetcc)
6186     // Only do this before legalize for now.
6187     if (VT.isVector() && !LegalOperations) {
6188       EVT N0VT = N0.getOperand(0).getValueType();
6189         // We know that the # elements of the results is the same as the
6190         // # elements of the compare (and the # elements of the compare result
6191         // for that matter).  Check to see that they are the same size.  If so,
6192         // we know that the element size of the sext'd result matches the
6193         // element size of the compare operands.
6194       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6195         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6196                              N0.getOperand(1),
6197                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6198       // If the desired elements are smaller or larger than the source
6199       // elements we can use a matching integer vector type and then
6200       // truncate/any extend
6201       else {
6202         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6203         SDValue VsetCC =
6204           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6205                         N0.getOperand(1),
6206                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6207         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6208       }
6209     }
6210
6211     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6212     SDValue SCC =
6213       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6214                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6215                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6216     if (SCC.getNode())
6217       return SCC;
6218   }
6219
6220   return SDValue();
6221 }
6222
6223 /// See if the specified operand can be simplified with the knowledge that only
6224 /// the bits specified by Mask are used.  If so, return the simpler operand,
6225 /// otherwise return a null SDValue.
6226 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6227   switch (V.getOpcode()) {
6228   default: break;
6229   case ISD::Constant: {
6230     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6231     assert(CV && "Const value should be ConstSDNode.");
6232     const APInt &CVal = CV->getAPIntValue();
6233     APInt NewVal = CVal & Mask;
6234     if (NewVal != CVal)
6235       return DAG.getConstant(NewVal, V.getValueType());
6236     break;
6237   }
6238   case ISD::OR:
6239   case ISD::XOR:
6240     // If the LHS or RHS don't contribute bits to the or, drop them.
6241     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6242       return V.getOperand(1);
6243     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6244       return V.getOperand(0);
6245     break;
6246   case ISD::SRL:
6247     // Only look at single-use SRLs.
6248     if (!V.getNode()->hasOneUse())
6249       break;
6250     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6251       // See if we can recursively simplify the LHS.
6252       unsigned Amt = RHSC->getZExtValue();
6253
6254       // Watch out for shift count overflow though.
6255       if (Amt >= Mask.getBitWidth()) break;
6256       APInt NewMask = Mask << Amt;
6257       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6258       if (SimplifyLHS.getNode())
6259         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6260                            SimplifyLHS, V.getOperand(1));
6261     }
6262   }
6263   return SDValue();
6264 }
6265
6266 /// If the result of a wider load is shifted to right of N  bits and then
6267 /// truncated to a narrower type and where N is a multiple of number of bits of
6268 /// the narrower type, transform it to a narrower load from address + N / num of
6269 /// bits of new type. If the result is to be extended, also fold the extension
6270 /// to form a extending load.
6271 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6272   unsigned Opc = N->getOpcode();
6273
6274   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6275   SDValue N0 = N->getOperand(0);
6276   EVT VT = N->getValueType(0);
6277   EVT ExtVT = VT;
6278
6279   // This transformation isn't valid for vector loads.
6280   if (VT.isVector())
6281     return SDValue();
6282
6283   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6284   // extended to VT.
6285   if (Opc == ISD::SIGN_EXTEND_INREG) {
6286     ExtType = ISD::SEXTLOAD;
6287     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6288   } else if (Opc == ISD::SRL) {
6289     // Another special-case: SRL is basically zero-extending a narrower value.
6290     ExtType = ISD::ZEXTLOAD;
6291     N0 = SDValue(N, 0);
6292     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6293     if (!N01) return SDValue();
6294     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6295                               VT.getSizeInBits() - N01->getZExtValue());
6296   }
6297   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6298     return SDValue();
6299
6300   unsigned EVTBits = ExtVT.getSizeInBits();
6301
6302   // Do not generate loads of non-round integer types since these can
6303   // be expensive (and would be wrong if the type is not byte sized).
6304   if (!ExtVT.isRound())
6305     return SDValue();
6306
6307   unsigned ShAmt = 0;
6308   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6309     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6310       ShAmt = N01->getZExtValue();
6311       // Is the shift amount a multiple of size of VT?
6312       if ((ShAmt & (EVTBits-1)) == 0) {
6313         N0 = N0.getOperand(0);
6314         // Is the load width a multiple of size of VT?
6315         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6316           return SDValue();
6317       }
6318
6319       // At this point, we must have a load or else we can't do the transform.
6320       if (!isa<LoadSDNode>(N0)) return SDValue();
6321
6322       // Because a SRL must be assumed to *need* to zero-extend the high bits
6323       // (as opposed to anyext the high bits), we can't combine the zextload
6324       // lowering of SRL and an sextload.
6325       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6326         return SDValue();
6327
6328       // If the shift amount is larger than the input type then we're not
6329       // accessing any of the loaded bytes.  If the load was a zextload/extload
6330       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6331       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6332         return SDValue();
6333     }
6334   }
6335
6336   // If the load is shifted left (and the result isn't shifted back right),
6337   // we can fold the truncate through the shift.
6338   unsigned ShLeftAmt = 0;
6339   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6340       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6341     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6342       ShLeftAmt = N01->getZExtValue();
6343       N0 = N0.getOperand(0);
6344     }
6345   }
6346
6347   // If we haven't found a load, we can't narrow it.  Don't transform one with
6348   // multiple uses, this would require adding a new load.
6349   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6350     return SDValue();
6351
6352   // Don't change the width of a volatile load.
6353   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6354   if (LN0->isVolatile())
6355     return SDValue();
6356
6357   // Verify that we are actually reducing a load width here.
6358   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6359     return SDValue();
6360
6361   // For the transform to be legal, the load must produce only two values
6362   // (the value loaded and the chain).  Don't transform a pre-increment
6363   // load, for example, which produces an extra value.  Otherwise the
6364   // transformation is not equivalent, and the downstream logic to replace
6365   // uses gets things wrong.
6366   if (LN0->getNumValues() > 2)
6367     return SDValue();
6368
6369   // If the load that we're shrinking is an extload and we're not just
6370   // discarding the extension we can't simply shrink the load. Bail.
6371   // TODO: It would be possible to merge the extensions in some cases.
6372   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6373       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6374     return SDValue();
6375
6376   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6377     return SDValue();
6378
6379   EVT PtrType = N0.getOperand(1).getValueType();
6380
6381   if (PtrType == MVT::Untyped || PtrType.isExtended())
6382     // It's not possible to generate a constant of extended or untyped type.
6383     return SDValue();
6384
6385   // For big endian targets, we need to adjust the offset to the pointer to
6386   // load the correct bytes.
6387   if (TLI.isBigEndian()) {
6388     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6389     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6390     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6391   }
6392
6393   uint64_t PtrOff = ShAmt / 8;
6394   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6395   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6396                                PtrType, LN0->getBasePtr(),
6397                                DAG.getConstant(PtrOff, PtrType));
6398   AddToWorklist(NewPtr.getNode());
6399
6400   SDValue Load;
6401   if (ExtType == ISD::NON_EXTLOAD)
6402     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6403                         LN0->getPointerInfo().getWithOffset(PtrOff),
6404                         LN0->isVolatile(), LN0->isNonTemporal(),
6405                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6406   else
6407     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6408                           LN0->getPointerInfo().getWithOffset(PtrOff),
6409                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6410                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6411
6412   // Replace the old load's chain with the new load's chain.
6413   WorklistRemover DeadNodes(*this);
6414   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6415
6416   // Shift the result left, if we've swallowed a left shift.
6417   SDValue Result = Load;
6418   if (ShLeftAmt != 0) {
6419     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6420     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6421       ShImmTy = VT;
6422     // If the shift amount is as large as the result size (but, presumably,
6423     // no larger than the source) then the useful bits of the result are
6424     // zero; we can't simply return the shortened shift, because the result
6425     // of that operation is undefined.
6426     if (ShLeftAmt >= VT.getSizeInBits())
6427       Result = DAG.getConstant(0, VT);
6428     else
6429       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6430                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6431   }
6432
6433   // Return the new loaded value.
6434   return Result;
6435 }
6436
6437 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6438   SDValue N0 = N->getOperand(0);
6439   SDValue N1 = N->getOperand(1);
6440   EVT VT = N->getValueType(0);
6441   EVT EVT = cast<VTSDNode>(N1)->getVT();
6442   unsigned VTBits = VT.getScalarType().getSizeInBits();
6443   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6444
6445   // fold (sext_in_reg c1) -> c1
6446   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6447     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6448
6449   // If the input is already sign extended, just drop the extension.
6450   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6451     return N0;
6452
6453   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6454   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6455       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6456     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6457                        N0.getOperand(0), N1);
6458
6459   // fold (sext_in_reg (sext x)) -> (sext x)
6460   // fold (sext_in_reg (aext x)) -> (sext x)
6461   // if x is small enough.
6462   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6463     SDValue N00 = N0.getOperand(0);
6464     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6465         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6466       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6467   }
6468
6469   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6470   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6471     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6472
6473   // fold operands of sext_in_reg based on knowledge that the top bits are not
6474   // demanded.
6475   if (SimplifyDemandedBits(SDValue(N, 0)))
6476     return SDValue(N, 0);
6477
6478   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6479   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6480   SDValue NarrowLoad = ReduceLoadWidth(N);
6481   if (NarrowLoad.getNode())
6482     return NarrowLoad;
6483
6484   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6485   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6486   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6487   if (N0.getOpcode() == ISD::SRL) {
6488     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6489       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6490         // We can turn this into an SRA iff the input to the SRL is already sign
6491         // extended enough.
6492         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6493         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6494           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6495                              N0.getOperand(0), N0.getOperand(1));
6496       }
6497   }
6498
6499   // fold (sext_inreg (extload x)) -> (sextload x)
6500   if (ISD::isEXTLoad(N0.getNode()) &&
6501       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6502       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6503       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6504        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6505     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6506     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6507                                      LN0->getChain(),
6508                                      LN0->getBasePtr(), EVT,
6509                                      LN0->getMemOperand());
6510     CombineTo(N, ExtLoad);
6511     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6512     AddToWorklist(ExtLoad.getNode());
6513     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6514   }
6515   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6516   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6517       N0.hasOneUse() &&
6518       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6519       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6520        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6521     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6522     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6523                                      LN0->getChain(),
6524                                      LN0->getBasePtr(), EVT,
6525                                      LN0->getMemOperand());
6526     CombineTo(N, ExtLoad);
6527     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6528     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6529   }
6530
6531   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6532   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6533     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6534                                        N0.getOperand(1), false);
6535     if (BSwap.getNode())
6536       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6537                          BSwap, N1);
6538   }
6539
6540   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6541   // into a build_vector.
6542   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6543     SmallVector<SDValue, 8> Elts;
6544     unsigned NumElts = N0->getNumOperands();
6545     unsigned ShAmt = VTBits - EVTBits;
6546
6547     for (unsigned i = 0; i != NumElts; ++i) {
6548       SDValue Op = N0->getOperand(i);
6549       if (Op->getOpcode() == ISD::UNDEF) {
6550         Elts.push_back(Op);
6551         continue;
6552       }
6553
6554       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6555       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6556       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6557                                      Op.getValueType()));
6558     }
6559
6560     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6561   }
6562
6563   return SDValue();
6564 }
6565
6566 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6567   SDValue N0 = N->getOperand(0);
6568   EVT VT = N->getValueType(0);
6569   bool isLE = TLI.isLittleEndian();
6570
6571   // noop truncate
6572   if (N0.getValueType() == N->getValueType(0))
6573     return N0;
6574   // fold (truncate c1) -> c1
6575   if (isConstantIntBuildVectorOrConstantInt(N0))
6576     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6577   // fold (truncate (truncate x)) -> (truncate x)
6578   if (N0.getOpcode() == ISD::TRUNCATE)
6579     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6580   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6581   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6582       N0.getOpcode() == ISD::SIGN_EXTEND ||
6583       N0.getOpcode() == ISD::ANY_EXTEND) {
6584     if (N0.getOperand(0).getValueType().bitsLT(VT))
6585       // if the source is smaller than the dest, we still need an extend
6586       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6587                          N0.getOperand(0));
6588     if (N0.getOperand(0).getValueType().bitsGT(VT))
6589       // if the source is larger than the dest, than we just need the truncate
6590       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6591     // if the source and dest are the same type, we can drop both the extend
6592     // and the truncate.
6593     return N0.getOperand(0);
6594   }
6595
6596   // Fold extract-and-trunc into a narrow extract. For example:
6597   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6598   //   i32 y = TRUNCATE(i64 x)
6599   //        -- becomes --
6600   //   v16i8 b = BITCAST (v2i64 val)
6601   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6602   //
6603   // Note: We only run this optimization after type legalization (which often
6604   // creates this pattern) and before operation legalization after which
6605   // we need to be more careful about the vector instructions that we generate.
6606   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6607       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6608
6609     EVT VecTy = N0.getOperand(0).getValueType();
6610     EVT ExTy = N0.getValueType();
6611     EVT TrTy = N->getValueType(0);
6612
6613     unsigned NumElem = VecTy.getVectorNumElements();
6614     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6615
6616     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6617     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6618
6619     SDValue EltNo = N0->getOperand(1);
6620     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6621       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6622       EVT IndexTy = TLI.getVectorIdxTy();
6623       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6624
6625       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6626                               NVT, N0.getOperand(0));
6627
6628       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6629                          SDLoc(N), TrTy, V,
6630                          DAG.getConstant(Index, IndexTy));
6631     }
6632   }
6633
6634   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6635   if (N0.getOpcode() == ISD::SELECT) {
6636     EVT SrcVT = N0.getValueType();
6637     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6638         TLI.isTruncateFree(SrcVT, VT)) {
6639       SDLoc SL(N0);
6640       SDValue Cond = N0.getOperand(0);
6641       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6642       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6643       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6644     }
6645   }
6646
6647   // Fold a series of buildvector, bitcast, and truncate if possible.
6648   // For example fold
6649   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6650   //   (2xi32 (buildvector x, y)).
6651   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6652       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6653       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6654       N0.getOperand(0).hasOneUse()) {
6655
6656     SDValue BuildVect = N0.getOperand(0);
6657     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6658     EVT TruncVecEltTy = VT.getVectorElementType();
6659
6660     // Check that the element types match.
6661     if (BuildVectEltTy == TruncVecEltTy) {
6662       // Now we only need to compute the offset of the truncated elements.
6663       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6664       unsigned TruncVecNumElts = VT.getVectorNumElements();
6665       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6666
6667       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6668              "Invalid number of elements");
6669
6670       SmallVector<SDValue, 8> Opnds;
6671       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6672         Opnds.push_back(BuildVect.getOperand(i));
6673
6674       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6675     }
6676   }
6677
6678   // See if we can simplify the input to this truncate through knowledge that
6679   // only the low bits are being used.
6680   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6681   // Currently we only perform this optimization on scalars because vectors
6682   // may have different active low bits.
6683   if (!VT.isVector()) {
6684     SDValue Shorter =
6685       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6686                                                VT.getSizeInBits()));
6687     if (Shorter.getNode())
6688       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6689   }
6690   // fold (truncate (load x)) -> (smaller load x)
6691   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6692   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6693     SDValue Reduced = ReduceLoadWidth(N);
6694     if (Reduced.getNode())
6695       return Reduced;
6696     // Handle the case where the load remains an extending load even
6697     // after truncation.
6698     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6699       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6700       if (!LN0->isVolatile() &&
6701           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6702         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6703                                          VT, LN0->getChain(), LN0->getBasePtr(),
6704                                          LN0->getMemoryVT(),
6705                                          LN0->getMemOperand());
6706         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6707         return NewLoad;
6708       }
6709     }
6710   }
6711   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6712   // where ... are all 'undef'.
6713   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6714     SmallVector<EVT, 8> VTs;
6715     SDValue V;
6716     unsigned Idx = 0;
6717     unsigned NumDefs = 0;
6718
6719     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6720       SDValue X = N0.getOperand(i);
6721       if (X.getOpcode() != ISD::UNDEF) {
6722         V = X;
6723         Idx = i;
6724         NumDefs++;
6725       }
6726       // Stop if more than one members are non-undef.
6727       if (NumDefs > 1)
6728         break;
6729       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6730                                      VT.getVectorElementType(),
6731                                      X.getValueType().getVectorNumElements()));
6732     }
6733
6734     if (NumDefs == 0)
6735       return DAG.getUNDEF(VT);
6736
6737     if (NumDefs == 1) {
6738       assert(V.getNode() && "The single defined operand is empty!");
6739       SmallVector<SDValue, 8> Opnds;
6740       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6741         if (i != Idx) {
6742           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6743           continue;
6744         }
6745         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6746         AddToWorklist(NV.getNode());
6747         Opnds.push_back(NV);
6748       }
6749       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6750     }
6751   }
6752
6753   // Simplify the operands using demanded-bits information.
6754   if (!VT.isVector() &&
6755       SimplifyDemandedBits(SDValue(N, 0)))
6756     return SDValue(N, 0);
6757
6758   return SDValue();
6759 }
6760
6761 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6762   SDValue Elt = N->getOperand(i);
6763   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6764     return Elt.getNode();
6765   return Elt.getOperand(Elt.getResNo()).getNode();
6766 }
6767
6768 /// build_pair (load, load) -> load
6769 /// if load locations are consecutive.
6770 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6771   assert(N->getOpcode() == ISD::BUILD_PAIR);
6772
6773   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6774   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6775   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6776       LD1->getAddressSpace() != LD2->getAddressSpace())
6777     return SDValue();
6778   EVT LD1VT = LD1->getValueType(0);
6779
6780   if (ISD::isNON_EXTLoad(LD2) &&
6781       LD2->hasOneUse() &&
6782       // If both are volatile this would reduce the number of volatile loads.
6783       // If one is volatile it might be ok, but play conservative and bail out.
6784       !LD1->isVolatile() &&
6785       !LD2->isVolatile() &&
6786       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6787     unsigned Align = LD1->getAlignment();
6788     unsigned NewAlign = TLI.getDataLayout()->
6789       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6790
6791     if (NewAlign <= Align &&
6792         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6793       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6794                          LD1->getBasePtr(), LD1->getPointerInfo(),
6795                          false, false, false, Align);
6796   }
6797
6798   return SDValue();
6799 }
6800
6801 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6802   SDValue N0 = N->getOperand(0);
6803   EVT VT = N->getValueType(0);
6804
6805   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6806   // Only do this before legalize, since afterward the target may be depending
6807   // on the bitconvert.
6808   // First check to see if this is all constant.
6809   if (!LegalTypes &&
6810       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6811       VT.isVector()) {
6812     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6813
6814     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6815     assert(!DestEltVT.isVector() &&
6816            "Element type of vector ValueType must not be vector!");
6817     if (isSimple)
6818       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6819   }
6820
6821   // If the input is a constant, let getNode fold it.
6822   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6823     // If we can't allow illegal operations, we need to check that this is just
6824     // a fp -> int or int -> conversion and that the resulting operation will
6825     // be legal.
6826     if (!LegalOperations ||
6827         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6828          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6829         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6830          TLI.isOperationLegal(ISD::Constant, VT)))
6831       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6832   }
6833
6834   // (conv (conv x, t1), t2) -> (conv x, t2)
6835   if (N0.getOpcode() == ISD::BITCAST)
6836     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6837                        N0.getOperand(0));
6838
6839   // fold (conv (load x)) -> (load (conv*)x)
6840   // If the resultant load doesn't need a higher alignment than the original!
6841   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6842       // Do not change the width of a volatile load.
6843       !cast<LoadSDNode>(N0)->isVolatile() &&
6844       // Do not remove the cast if the types differ in endian layout.
6845       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6846       TLI.hasBigEndianPartOrdering(VT) &&
6847       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6848       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6849     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6850     unsigned Align = TLI.getDataLayout()->
6851       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6852     unsigned OrigAlign = LN0->getAlignment();
6853
6854     if (Align <= OrigAlign) {
6855       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6856                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6857                                  LN0->isVolatile(), LN0->isNonTemporal(),
6858                                  LN0->isInvariant(), OrigAlign,
6859                                  LN0->getAAInfo());
6860       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6861       return Load;
6862     }
6863   }
6864
6865   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6866   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6867   // This often reduces constant pool loads.
6868   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6869        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6870       N0.getNode()->hasOneUse() && VT.isInteger() &&
6871       !VT.isVector() && !N0.getValueType().isVector()) {
6872     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6873                                   N0.getOperand(0));
6874     AddToWorklist(NewConv.getNode());
6875
6876     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6877     if (N0.getOpcode() == ISD::FNEG)
6878       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6879                          NewConv, DAG.getConstant(SignBit, VT));
6880     assert(N0.getOpcode() == ISD::FABS);
6881     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6882                        NewConv, DAG.getConstant(~SignBit, VT));
6883   }
6884
6885   // fold (bitconvert (fcopysign cst, x)) ->
6886   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6887   // Note that we don't handle (copysign x, cst) because this can always be
6888   // folded to an fneg or fabs.
6889   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6890       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6891       VT.isInteger() && !VT.isVector()) {
6892     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6893     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6894     if (isTypeLegal(IntXVT)) {
6895       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6896                               IntXVT, N0.getOperand(1));
6897       AddToWorklist(X.getNode());
6898
6899       // If X has a different width than the result/lhs, sext it or truncate it.
6900       unsigned VTWidth = VT.getSizeInBits();
6901       if (OrigXWidth < VTWidth) {
6902         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6903         AddToWorklist(X.getNode());
6904       } else if (OrigXWidth > VTWidth) {
6905         // To get the sign bit in the right place, we have to shift it right
6906         // before truncating.
6907         X = DAG.getNode(ISD::SRL, SDLoc(X),
6908                         X.getValueType(), X,
6909                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6910         AddToWorklist(X.getNode());
6911         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6912         AddToWorklist(X.getNode());
6913       }
6914
6915       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6916       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6917                       X, DAG.getConstant(SignBit, VT));
6918       AddToWorklist(X.getNode());
6919
6920       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6921                                 VT, N0.getOperand(0));
6922       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6923                         Cst, DAG.getConstant(~SignBit, VT));
6924       AddToWorklist(Cst.getNode());
6925
6926       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6927     }
6928   }
6929
6930   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6931   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6932     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6933     if (CombineLD.getNode())
6934       return CombineLD;
6935   }
6936
6937   return SDValue();
6938 }
6939
6940 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6941   EVT VT = N->getValueType(0);
6942   return CombineConsecutiveLoads(N, VT);
6943 }
6944
6945 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6946 /// operands. DstEltVT indicates the destination element value type.
6947 SDValue DAGCombiner::
6948 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6949   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6950
6951   // If this is already the right type, we're done.
6952   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6953
6954   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6955   unsigned DstBitSize = DstEltVT.getSizeInBits();
6956
6957   // If this is a conversion of N elements of one type to N elements of another
6958   // type, convert each element.  This handles FP<->INT cases.
6959   if (SrcBitSize == DstBitSize) {
6960     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6961                               BV->getValueType(0).getVectorNumElements());
6962
6963     // Due to the FP element handling below calling this routine recursively,
6964     // we can end up with a scalar-to-vector node here.
6965     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6966       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6967                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6968                                      DstEltVT, BV->getOperand(0)));
6969
6970     SmallVector<SDValue, 8> Ops;
6971     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6972       SDValue Op = BV->getOperand(i);
6973       // If the vector element type is not legal, the BUILD_VECTOR operands
6974       // are promoted and implicitly truncated.  Make that explicit here.
6975       if (Op.getValueType() != SrcEltVT)
6976         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6977       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6978                                 DstEltVT, Op));
6979       AddToWorklist(Ops.back().getNode());
6980     }
6981     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6982   }
6983
6984   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6985   // handle annoying details of growing/shrinking FP values, we convert them to
6986   // int first.
6987   if (SrcEltVT.isFloatingPoint()) {
6988     // Convert the input float vector to a int vector where the elements are the
6989     // same sizes.
6990     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6991     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6992     SrcEltVT = IntVT;
6993   }
6994
6995   // Now we know the input is an integer vector.  If the output is a FP type,
6996   // convert to integer first, then to FP of the right size.
6997   if (DstEltVT.isFloatingPoint()) {
6998     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6999     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7000
7001     // Next, convert to FP elements of the same size.
7002     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7003   }
7004
7005   // Okay, we know the src/dst types are both integers of differing types.
7006   // Handling growing first.
7007   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7008   if (SrcBitSize < DstBitSize) {
7009     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7010
7011     SmallVector<SDValue, 8> Ops;
7012     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7013          i += NumInputsPerOutput) {
7014       bool isLE = TLI.isLittleEndian();
7015       APInt NewBits = APInt(DstBitSize, 0);
7016       bool EltIsUndef = true;
7017       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7018         // Shift the previously computed bits over.
7019         NewBits <<= SrcBitSize;
7020         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7021         if (Op.getOpcode() == ISD::UNDEF) continue;
7022         EltIsUndef = false;
7023
7024         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7025                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7026       }
7027
7028       if (EltIsUndef)
7029         Ops.push_back(DAG.getUNDEF(DstEltVT));
7030       else
7031         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
7032     }
7033
7034     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7035     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7036   }
7037
7038   // Finally, this must be the case where we are shrinking elements: each input
7039   // turns into multiple outputs.
7040   bool isS2V = ISD::isScalarToVector(BV);
7041   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7042   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7043                             NumOutputsPerInput*BV->getNumOperands());
7044   SmallVector<SDValue, 8> Ops;
7045
7046   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7047     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7048       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7049       continue;
7050     }
7051
7052     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7053                   getAPIntValue().zextOrTrunc(SrcBitSize);
7054
7055     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7056       APInt ThisVal = OpVal.trunc(DstBitSize);
7057       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
7058       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
7059         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
7060         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7061                            Ops[0]);
7062       OpVal = OpVal.lshr(DstBitSize);
7063     }
7064
7065     // For big endian targets, swap the order of the pieces of each element.
7066     if (TLI.isBigEndian())
7067       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7068   }
7069
7070   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7071 }
7072
7073 // Attempt different variants of (fadd (fmul a, b), c) -> fma or fmad
7074 static SDValue performFaddFmulCombines(unsigned FusedOpcode,
7075                                        bool Aggressive,
7076                                        SDNode *N,
7077                                        const TargetLowering &TLI,
7078                                        SelectionDAG &DAG) {
7079   SDValue N0 = N->getOperand(0);
7080   SDValue N1 = N->getOperand(1);
7081   EVT VT = N->getValueType(0);
7082
7083   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7084   if (N0.getOpcode() == ISD::FMUL &&
7085       (Aggressive || N0->hasOneUse())) {
7086     return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7087                        N0.getOperand(0), N0.getOperand(1), N1);
7088   }
7089
7090   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7091   // Note: Commutes FADD operands.
7092   if (N1.getOpcode() == ISD::FMUL &&
7093       (Aggressive || N1->hasOneUse())) {
7094     return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7095                        N1.getOperand(0), N1.getOperand(1), N0);
7096   }
7097
7098   // More folding opportunities when target permits.
7099   if (Aggressive) {
7100     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7101     if (N0.getOpcode() == ISD::FMA &&
7102         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7103       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7104                          N0.getOperand(0), N0.getOperand(1),
7105                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
7106                                      N0.getOperand(2).getOperand(0),
7107                                      N0.getOperand(2).getOperand(1),
7108                                      N1));
7109     }
7110
7111     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7112     if (N1->getOpcode() == ISD::FMA &&
7113         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7114       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7115                          N1.getOperand(0), N1.getOperand(1),
7116                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
7117                                      N1.getOperand(2).getOperand(0),
7118                                      N1.getOperand(2).getOperand(1),
7119                                      N0));
7120     }
7121   }
7122
7123   return SDValue();
7124 }
7125
7126 static SDValue performFsubFmulCombines(unsigned FusedOpcode,
7127                                        bool Aggressive,
7128                                        SDNode *N,
7129                                        const TargetLowering &TLI,
7130                                        SelectionDAG &DAG) {
7131   SDValue N0 = N->getOperand(0);
7132   SDValue N1 = N->getOperand(1);
7133   EVT VT = N->getValueType(0);
7134
7135   SDLoc SL(N);
7136
7137   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7138   if (N0.getOpcode() == ISD::FMUL &&
7139       (Aggressive || N0->hasOneUse())) {
7140     return DAG.getNode(FusedOpcode, SL, VT,
7141                        N0.getOperand(0), N0.getOperand(1),
7142                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7143   }
7144
7145   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7146   // Note: Commutes FSUB operands.
7147   if (N1.getOpcode() == ISD::FMUL &&
7148       (Aggressive || N1->hasOneUse()))
7149     return DAG.getNode(FusedOpcode, SL, VT,
7150                        DAG.getNode(ISD::FNEG, SL, VT,
7151                                    N1.getOperand(0)),
7152                        N1.getOperand(1), N0);
7153
7154   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7155   if (N0.getOpcode() == ISD::FNEG &&
7156       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7157       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7158     SDValue N00 = N0.getOperand(0).getOperand(0);
7159     SDValue N01 = N0.getOperand(0).getOperand(1);
7160     return DAG.getNode(FusedOpcode, SL, VT,
7161                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7162                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7163   }
7164
7165   // More folding opportunities when target permits.
7166   if (Aggressive) {
7167     // fold (fsub (fma x, y, (fmul u, v)), z)
7168     //   -> (fma x, y (fma u, v, (fneg z)))
7169     if (N0.getOpcode() == FusedOpcode &&
7170         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7171       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7172                          N0.getOperand(0), N0.getOperand(1),
7173                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
7174                                      N0.getOperand(2).getOperand(0),
7175                                      N0.getOperand(2).getOperand(1),
7176                                      DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7177                                                  N1)));
7178     }
7179
7180     // fold (fsub x, (fma y, z, (fmul u, v)))
7181     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7182     if (N1.getOpcode() == FusedOpcode &&
7183         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7184       SDValue N20 = N1.getOperand(2).getOperand(0);
7185       SDValue N21 = N1.getOperand(2).getOperand(1);
7186       return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7187                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7188                                      N1.getOperand(0)),
7189                          N1.getOperand(1),
7190                          DAG.getNode(FusedOpcode, SDLoc(N), VT,
7191                                      DAG.getNode(ISD::FNEG, SDLoc(N),  VT,
7192                                                  N20),
7193                                      N21, N0));
7194     }
7195   }
7196
7197   return SDValue();
7198 }
7199
7200 SDValue DAGCombiner::visitFADD(SDNode *N) {
7201   SDValue N0 = N->getOperand(0);
7202   SDValue N1 = N->getOperand(1);
7203   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7204   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7205   EVT VT = N->getValueType(0);
7206   const TargetOptions &Options = DAG.getTarget().Options;
7207
7208   // fold vector ops
7209   if (VT.isVector()) {
7210     SDValue FoldedVOp = SimplifyVBinOp(N);
7211     if (FoldedVOp.getNode()) return FoldedVOp;
7212   }
7213
7214   // fold (fadd c1, c2) -> c1 + c2
7215   if (N0CFP && N1CFP)
7216     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
7217
7218   // canonicalize constant to RHS
7219   if (N0CFP && !N1CFP)
7220     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
7221
7222   // fold (fadd A, (fneg B)) -> (fsub A, B)
7223   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7224       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7225     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
7226                        GetNegatedExpression(N1, DAG, LegalOperations));
7227
7228   // fold (fadd (fneg A), B) -> (fsub B, A)
7229   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7230       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7231     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
7232                        GetNegatedExpression(N0, DAG, LegalOperations));
7233
7234   // If 'unsafe math' is enabled, fold lots of things.
7235   if (Options.UnsafeFPMath) {
7236     // No FP constant should be created after legalization as Instruction
7237     // Selection pass has a hard time dealing with FP constants.
7238     bool AllowNewConst = (Level < AfterLegalizeDAG);
7239
7240     // fold (fadd A, 0) -> A
7241     if (N1CFP && N1CFP->getValueAPF().isZero())
7242       return N0;
7243
7244     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7245     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7246         isa<ConstantFPSDNode>(N0.getOperand(1)))
7247       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7248                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
7249                                      N0.getOperand(1), N1));
7250
7251     // If allowed, fold (fadd (fneg x), x) -> 0.0
7252     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7253       return DAG.getConstantFP(0.0, VT);
7254
7255     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7256     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7257       return DAG.getConstantFP(0.0, VT);
7258
7259     // We can fold chains of FADD's of the same value into multiplications.
7260     // This transform is not safe in general because we are reducing the number
7261     // of rounding steps.
7262     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7263       if (N0.getOpcode() == ISD::FMUL) {
7264         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7265         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7266
7267         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7268         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7269           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7270                                        SDValue(CFP01, 0),
7271                                        DAG.getConstantFP(1.0, VT));
7272           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
7273         }
7274
7275         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7276         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7277             N1.getOperand(0) == N1.getOperand(1) &&
7278             N0.getOperand(0) == N1.getOperand(0)) {
7279           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7280                                        SDValue(CFP01, 0),
7281                                        DAG.getConstantFP(2.0, VT));
7282           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7283                              N0.getOperand(0), NewCFP);
7284         }
7285       }
7286
7287       if (N1.getOpcode() == ISD::FMUL) {
7288         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7289         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7290
7291         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7292         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7293           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7294                                        SDValue(CFP11, 0),
7295                                        DAG.getConstantFP(1.0, VT));
7296           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
7297         }
7298
7299         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7300         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7301             N0.getOperand(0) == N0.getOperand(1) &&
7302             N1.getOperand(0) == N0.getOperand(0)) {
7303           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7304                                        SDValue(CFP11, 0),
7305                                        DAG.getConstantFP(2.0, VT));
7306           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
7307         }
7308       }
7309
7310       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7311         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7312         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7313         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7314             (N0.getOperand(0) == N1))
7315           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7316                              N1, DAG.getConstantFP(3.0, VT));
7317       }
7318
7319       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7320         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7321         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7322         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7323             N1.getOperand(0) == N0)
7324           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7325                              N0, DAG.getConstantFP(3.0, VT));
7326       }
7327
7328       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7329       if (AllowNewConst &&
7330           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7331           N0.getOperand(0) == N0.getOperand(1) &&
7332           N1.getOperand(0) == N1.getOperand(1) &&
7333           N0.getOperand(0) == N1.getOperand(0))
7334         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7335                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
7336     }
7337   } // enable-unsafe-fp-math
7338
7339   if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7340     // Assume if there is an fmad instruction that it should be aggressively
7341     // used.
7342     if (SDValue Fused = performFaddFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7343       return Fused;
7344   }
7345
7346   // FADD -> FMA combines:
7347   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7348       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7349       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7350
7351     if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7352       // Don't form FMA if we are preferring FMAD.
7353       if (SDValue Fused
7354           = performFaddFmulCombines(ISD::FMA,
7355                                     TLI.enableAggressiveFMAFusion(VT),
7356                                     N, TLI, DAG)) {
7357         return Fused;
7358       }
7359     }
7360
7361     // When FP_EXTEND nodes are free on the target, and there is an opportunity
7362     // to combine into FMA, arrange such nodes accordingly.
7363     if (TLI.isFPExtFree(VT)) {
7364
7365       // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7366       if (N0.getOpcode() == ISD::FP_EXTEND) {
7367         SDValue N00 = N0.getOperand(0);
7368         if (N00.getOpcode() == ISD::FMUL)
7369           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7370                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7371                                          N00.getOperand(0)),
7372                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7373                                          N00.getOperand(1)), N1);
7374       }
7375
7376       // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
7377       // Note: Commutes FADD operands.
7378       if (N1.getOpcode() == ISD::FP_EXTEND) {
7379         SDValue N10 = N1.getOperand(0);
7380         if (N10.getOpcode() == ISD::FMUL)
7381           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7382                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7383                                          N10.getOperand(0)),
7384                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7385                                          N10.getOperand(1)), N0);
7386       }
7387     }
7388   }
7389
7390   return SDValue();
7391 }
7392
7393 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7394   SDValue N0 = N->getOperand(0);
7395   SDValue N1 = N->getOperand(1);
7396   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7397   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7398   EVT VT = N->getValueType(0);
7399   SDLoc dl(N);
7400   const TargetOptions &Options = DAG.getTarget().Options;
7401
7402   // fold vector ops
7403   if (VT.isVector()) {
7404     SDValue FoldedVOp = SimplifyVBinOp(N);
7405     if (FoldedVOp.getNode()) return FoldedVOp;
7406   }
7407
7408   // fold (fsub c1, c2) -> c1-c2
7409   if (N0CFP && N1CFP)
7410     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
7411
7412   // fold (fsub A, (fneg B)) -> (fadd A, B)
7413   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7414     return DAG.getNode(ISD::FADD, dl, VT, N0,
7415                        GetNegatedExpression(N1, DAG, LegalOperations));
7416
7417   // If 'unsafe math' is enabled, fold lots of things.
7418   if (Options.UnsafeFPMath) {
7419     // (fsub A, 0) -> A
7420     if (N1CFP && N1CFP->getValueAPF().isZero())
7421       return N0;
7422
7423     // (fsub 0, B) -> -B
7424     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7425       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7426         return GetNegatedExpression(N1, DAG, LegalOperations);
7427       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7428         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7429     }
7430
7431     // (fsub x, x) -> 0.0
7432     if (N0 == N1)
7433       return DAG.getConstantFP(0.0f, VT);
7434
7435     // (fsub x, (fadd x, y)) -> (fneg y)
7436     // (fsub x, (fadd y, x)) -> (fneg y)
7437     if (N1.getOpcode() == ISD::FADD) {
7438       SDValue N10 = N1->getOperand(0);
7439       SDValue N11 = N1->getOperand(1);
7440
7441       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7442         return GetNegatedExpression(N11, DAG, LegalOperations);
7443
7444       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7445         return GetNegatedExpression(N10, DAG, LegalOperations);
7446     }
7447   }
7448
7449   if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7450     // Assume if there is an fmad instruction that it should be aggressively
7451     // used.
7452     if (SDValue Fused = performFsubFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7453       return Fused;
7454   }
7455
7456   // FSUB -> FMA combines:
7457   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7458       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7459       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7460
7461     if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7462       // Don't form FMA if we are preferring FMAD.
7463
7464       if (SDValue Fused
7465           = performFsubFmulCombines(ISD::FMA,
7466                                     TLI.enableAggressiveFMAFusion(VT),
7467                                     N, TLI, DAG)) {
7468         return Fused;
7469       }
7470     }
7471
7472     // When FP_EXTEND nodes are free on the target, and there is an opportunity
7473     // to combine into FMA, arrange such nodes accordingly.
7474     if (TLI.isFPExtFree(VT)) {
7475       // fold (fsub (fpext (fmul x, y)), z)
7476       //   -> (fma (fpext x), (fpext y), (fneg z))
7477       if (N0.getOpcode() == ISD::FP_EXTEND) {
7478         SDValue N00 = N0.getOperand(0);
7479         if (N00.getOpcode() == ISD::FMUL)
7480           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7481                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7482                                          N00.getOperand(0)),
7483                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7484                                          N00.getOperand(1)),
7485                              DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7486       }
7487
7488       // fold (fsub x, (fpext (fmul y, z)))
7489       //   -> (fma (fneg (fpext y)), (fpext z), x)
7490       // Note: Commutes FSUB operands.
7491       if (N1.getOpcode() == ISD::FP_EXTEND) {
7492         SDValue N10 = N1.getOperand(0);
7493         if (N10.getOpcode() == ISD::FMUL)
7494           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7495                              DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7496                                          DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7497                                                      VT, N10.getOperand(0))),
7498                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7499                                          N10.getOperand(1)),
7500                              N0);
7501       }
7502
7503       // fold (fsub (fpext (fneg (fmul, x, y))), z)
7504       //   -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7505       if (N0.getOpcode() == ISD::FP_EXTEND) {
7506         SDValue N00 = N0.getOperand(0);
7507         if (N00.getOpcode() == ISD::FNEG) {
7508           SDValue N000 = N00.getOperand(0);
7509           if (N000.getOpcode() == ISD::FMUL) {
7510             return DAG.getNode(ISD::FMA, dl, VT,
7511                                DAG.getNode(ISD::FNEG, dl, VT,
7512                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7513                                                        VT, N000.getOperand(0))),
7514                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7515                                            N000.getOperand(1)),
7516                                DAG.getNode(ISD::FNEG, dl, VT, N1));
7517           }
7518         }
7519       }
7520
7521       // fold (fsub (fneg (fpext (fmul, x, y))), z)
7522       //   -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7523       if (N0.getOpcode() == ISD::FNEG) {
7524         SDValue N00 = N0.getOperand(0);
7525         if (N00.getOpcode() == ISD::FP_EXTEND) {
7526           SDValue N000 = N00.getOperand(0);
7527           if (N000.getOpcode() == ISD::FMUL) {
7528             return DAG.getNode(ISD::FMA, dl, VT,
7529                                DAG.getNode(ISD::FNEG, dl, VT,
7530                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7531                                            VT, N000.getOperand(0))),
7532                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7533                                            N000.getOperand(1)),
7534                                DAG.getNode(ISD::FNEG, dl, VT, N1));
7535           }
7536         }
7537       }
7538     }
7539   }
7540
7541   return SDValue();
7542 }
7543
7544 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7545   SDValue N0 = N->getOperand(0);
7546   SDValue N1 = N->getOperand(1);
7547   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7548   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7549   EVT VT = N->getValueType(0);
7550   const TargetOptions &Options = DAG.getTarget().Options;
7551
7552   // fold vector ops
7553   if (VT.isVector()) {
7554     // This just handles C1 * C2 for vectors. Other vector folds are below.
7555     SDValue FoldedVOp = SimplifyVBinOp(N);
7556     if (FoldedVOp.getNode())
7557       return FoldedVOp;
7558     // Canonicalize vector constant to RHS.
7559     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7560         N1.getOpcode() != ISD::BUILD_VECTOR)
7561       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7562         if (BV0->isConstant())
7563           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7564   }
7565
7566   // fold (fmul c1, c2) -> c1*c2
7567   if (N0CFP && N1CFP)
7568     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7569
7570   // canonicalize constant to RHS
7571   if (N0CFP && !N1CFP)
7572     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7573
7574   // fold (fmul A, 1.0) -> A
7575   if (N1CFP && N1CFP->isExactlyValue(1.0))
7576     return N0;
7577
7578   if (Options.UnsafeFPMath) {
7579     // fold (fmul A, 0) -> 0
7580     if (N1CFP && N1CFP->getValueAPF().isZero())
7581       return N1;
7582
7583     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7584     if (N0.getOpcode() == ISD::FMUL) {
7585       // Fold scalars or any vector constants (not just splats).
7586       // This fold is done in general by InstCombine, but extra fmul insts
7587       // may have been generated during lowering.
7588       SDValue N00 = N0.getOperand(0);
7589       SDValue N01 = N0.getOperand(1);
7590       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7591       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
7592       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7593       
7594       // Check 1: Make sure that the first operand of the inner multiply is NOT
7595       // a constant. Otherwise, we may induce infinite looping.
7596       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7597         // Check 2: Make sure that the second operand of the inner multiply and
7598         // the second operand of the outer multiply are constants.
7599         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7600             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7601           SDLoc SL(N);
7602           SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7603           return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7604         }
7605       }
7606     }
7607
7608     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7609     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7610     // during an early run of DAGCombiner can prevent folding with fmuls
7611     // inserted during lowering.
7612     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7613       SDLoc SL(N);
7614       const SDValue Two = DAG.getConstantFP(2.0, VT);
7615       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7616       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7617     }
7618   }
7619
7620   // fold (fmul X, 2.0) -> (fadd X, X)
7621   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7622     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7623
7624   // fold (fmul X, -1.0) -> (fneg X)
7625   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7626     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7627       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7628
7629   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7630   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7631     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7632       // Both can be negated for free, check to see if at least one is cheaper
7633       // negated.
7634       if (LHSNeg == 2 || RHSNeg == 2)
7635         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7636                            GetNegatedExpression(N0, DAG, LegalOperations),
7637                            GetNegatedExpression(N1, DAG, LegalOperations));
7638     }
7639   }
7640
7641   return SDValue();
7642 }
7643
7644 SDValue DAGCombiner::visitFMA(SDNode *N) {
7645   SDValue N0 = N->getOperand(0);
7646   SDValue N1 = N->getOperand(1);
7647   SDValue N2 = N->getOperand(2);
7648   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7649   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7650   EVT VT = N->getValueType(0);
7651   SDLoc dl(N);
7652   const TargetOptions &Options = DAG.getTarget().Options;
7653
7654   // Constant fold FMA.
7655   if (isa<ConstantFPSDNode>(N0) &&
7656       isa<ConstantFPSDNode>(N1) &&
7657       isa<ConstantFPSDNode>(N2)) {
7658     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7659   }
7660
7661   if (Options.UnsafeFPMath) {
7662     if (N0CFP && N0CFP->isZero())
7663       return N2;
7664     if (N1CFP && N1CFP->isZero())
7665       return N2;
7666   }
7667   if (N0CFP && N0CFP->isExactlyValue(1.0))
7668     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7669   if (N1CFP && N1CFP->isExactlyValue(1.0))
7670     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7671
7672   // Canonicalize (fma c, x, y) -> (fma x, c, y)
7673   if (N0CFP && !N1CFP)
7674     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7675
7676   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7677   if (Options.UnsafeFPMath && N1CFP &&
7678       N2.getOpcode() == ISD::FMUL &&
7679       N0 == N2.getOperand(0) &&
7680       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7681     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7682                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7683   }
7684
7685
7686   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7687   if (Options.UnsafeFPMath &&
7688       N0.getOpcode() == ISD::FMUL && N1CFP &&
7689       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7690     return DAG.getNode(ISD::FMA, dl, VT,
7691                        N0.getOperand(0),
7692                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7693                        N2);
7694   }
7695
7696   // (fma x, 1, y) -> (fadd x, y)
7697   // (fma x, -1, y) -> (fadd (fneg x), y)
7698   if (N1CFP) {
7699     if (N1CFP->isExactlyValue(1.0))
7700       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7701
7702     if (N1CFP->isExactlyValue(-1.0) &&
7703         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7704       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7705       AddToWorklist(RHSNeg.getNode());
7706       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7707     }
7708   }
7709
7710   // (fma x, c, x) -> (fmul x, (c+1))
7711   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7712     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7713                        DAG.getNode(ISD::FADD, dl, VT,
7714                                    N1, DAG.getConstantFP(1.0, VT)));
7715
7716   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7717   if (Options.UnsafeFPMath && N1CFP &&
7718       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7719     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7720                        DAG.getNode(ISD::FADD, dl, VT,
7721                                    N1, DAG.getConstantFP(-1.0, VT)));
7722
7723
7724   return SDValue();
7725 }
7726
7727 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7728   SDValue N0 = N->getOperand(0);
7729   SDValue N1 = N->getOperand(1);
7730   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7731   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7732   EVT VT = N->getValueType(0);
7733   SDLoc DL(N);
7734   const TargetOptions &Options = DAG.getTarget().Options;
7735
7736   // fold vector ops
7737   if (VT.isVector()) {
7738     SDValue FoldedVOp = SimplifyVBinOp(N);
7739     if (FoldedVOp.getNode()) return FoldedVOp;
7740   }
7741
7742   // fold (fdiv c1, c2) -> c1/c2
7743   if (N0CFP && N1CFP)
7744     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7745
7746   if (Options.UnsafeFPMath) {
7747     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7748     if (N1CFP) {
7749       // Compute the reciprocal 1.0 / c2.
7750       APFloat N1APF = N1CFP->getValueAPF();
7751       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7752       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7753       // Only do the transform if the reciprocal is a legal fp immediate that
7754       // isn't too nasty (eg NaN, denormal, ...).
7755       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7756           (!LegalOperations ||
7757            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7758            // backend)... we should handle this gracefully after Legalize.
7759            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7760            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7761            TLI.isFPImmLegal(Recip, VT)))
7762         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7763                            DAG.getConstantFP(Recip, VT));
7764     }
7765
7766     // If this FDIV is part of a reciprocal square root, it may be folded
7767     // into a target-specific square root estimate instruction.
7768     if (N1.getOpcode() == ISD::FSQRT) {
7769       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7770         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7771       }
7772     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7773                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7774       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7775         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7776         AddToWorklist(RV.getNode());
7777         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7778       }
7779     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7780                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7781       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7782         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7783         AddToWorklist(RV.getNode());
7784         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7785       }
7786     } else if (N1.getOpcode() == ISD::FMUL) {
7787       // Look through an FMUL. Even though this won't remove the FDIV directly,
7788       // it's still worthwhile to get rid of the FSQRT if possible.
7789       SDValue SqrtOp;
7790       SDValue OtherOp;
7791       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7792         SqrtOp = N1.getOperand(0);
7793         OtherOp = N1.getOperand(1);
7794       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7795         SqrtOp = N1.getOperand(1);
7796         OtherOp = N1.getOperand(0);
7797       }
7798       if (SqrtOp.getNode()) {
7799         // We found a FSQRT, so try to make this fold:
7800         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7801         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7802           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7803           AddToWorklist(RV.getNode());
7804           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7805         }
7806       }
7807     }
7808
7809     // Fold into a reciprocal estimate and multiply instead of a real divide.
7810     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7811       AddToWorklist(RV.getNode());
7812       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7813     }
7814   }
7815
7816   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7817   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7818     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7819       // Both can be negated for free, check to see if at least one is cheaper
7820       // negated.
7821       if (LHSNeg == 2 || RHSNeg == 2)
7822         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7823                            GetNegatedExpression(N0, DAG, LegalOperations),
7824                            GetNegatedExpression(N1, DAG, LegalOperations));
7825     }
7826   }
7827
7828   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7829   // reciprocal.
7830   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7831   // Notice that this is not always beneficial. One reason is different target
7832   // may have different costs for FDIV and FMUL, so sometimes the cost of two
7833   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7834   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7835   if (Options.UnsafeFPMath) {
7836     // Skip if current node is a reciprocal.
7837     if (N0CFP && N0CFP->isExactlyValue(1.0))
7838       return SDValue();
7839
7840     SmallVector<SDNode *, 4> Users;
7841     // Find all FDIV users of the same divisor.
7842     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7843                               UE = N1.getNode()->use_end();
7844          UI != UE; ++UI) {
7845       SDNode *User = UI.getUse().getUser();
7846       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7847         Users.push_back(User);
7848     }
7849
7850     if (TLI.combineRepeatedFPDivisors(Users.size())) {
7851       SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7852       SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7853
7854       // Dividend / Divisor -> Dividend * Reciprocal
7855       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7856         if ((*I)->getOperand(0) != FPOne) {
7857           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7858                                         (*I)->getOperand(0), Reciprocal);
7859           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7860         }
7861       }
7862       return SDValue();
7863     }
7864   }
7865
7866   return SDValue();
7867 }
7868
7869 SDValue DAGCombiner::visitFREM(SDNode *N) {
7870   SDValue N0 = N->getOperand(0);
7871   SDValue N1 = N->getOperand(1);
7872   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7873   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7874   EVT VT = N->getValueType(0);
7875
7876   // fold (frem c1, c2) -> fmod(c1,c2)
7877   if (N0CFP && N1CFP)
7878     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7879
7880   return SDValue();
7881 }
7882
7883 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7884   if (DAG.getTarget().Options.UnsafeFPMath &&
7885       !TLI.isFsqrtCheap()) {
7886     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7887     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7888       EVT VT = RV.getValueType();
7889       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7890       AddToWorklist(RV.getNode());
7891
7892       // Unfortunately, RV is now NaN if the input was exactly 0.
7893       // Select out this case and force the answer to 0.
7894       SDValue Zero = DAG.getConstantFP(0.0, VT);
7895       SDValue ZeroCmp =
7896         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7897                      N->getOperand(0), Zero, ISD::SETEQ);
7898       AddToWorklist(ZeroCmp.getNode());
7899       AddToWorklist(RV.getNode());
7900
7901       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7902                        SDLoc(N), VT, ZeroCmp, Zero, RV);
7903       return RV;
7904     }
7905   }
7906   return SDValue();
7907 }
7908
7909 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7910   SDValue N0 = N->getOperand(0);
7911   SDValue N1 = N->getOperand(1);
7912   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7913   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7914   EVT VT = N->getValueType(0);
7915
7916   if (N0CFP && N1CFP)  // Constant fold
7917     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7918
7919   if (N1CFP) {
7920     const APFloat& V = N1CFP->getValueAPF();
7921     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7922     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7923     if (!V.isNegative()) {
7924       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7925         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7926     } else {
7927       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7928         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7929                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7930     }
7931   }
7932
7933   // copysign(fabs(x), y) -> copysign(x, y)
7934   // copysign(fneg(x), y) -> copysign(x, y)
7935   // copysign(copysign(x,z), y) -> copysign(x, y)
7936   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7937       N0.getOpcode() == ISD::FCOPYSIGN)
7938     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7939                        N0.getOperand(0), N1);
7940
7941   // copysign(x, abs(y)) -> abs(x)
7942   if (N1.getOpcode() == ISD::FABS)
7943     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7944
7945   // copysign(x, copysign(y,z)) -> copysign(x, z)
7946   if (N1.getOpcode() == ISD::FCOPYSIGN)
7947     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7948                        N0, N1.getOperand(1));
7949
7950   // copysign(x, fp_extend(y)) -> copysign(x, y)
7951   // copysign(x, fp_round(y)) -> copysign(x, y)
7952   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7953     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7954                        N0, N1.getOperand(0));
7955
7956   return SDValue();
7957 }
7958
7959 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7960   SDValue N0 = N->getOperand(0);
7961   EVT VT = N->getValueType(0);
7962   EVT OpVT = N0.getValueType();
7963
7964   // fold (sint_to_fp c1) -> c1fp
7965   if (isConstantIntBuildVectorOrConstantInt(N0) &&
7966       // ...but only if the target supports immediate floating-point values
7967       (!LegalOperations ||
7968        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7969     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7970
7971   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7972   // but UINT_TO_FP is legal on this target, try to convert.
7973   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7974       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7975     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7976     if (DAG.SignBitIsZero(N0))
7977       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7978   }
7979
7980   // The next optimizations are desirable only if SELECT_CC can be lowered.
7981   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7982     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7983     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7984         !VT.isVector() &&
7985         (!LegalOperations ||
7986          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7987       SDValue Ops[] =
7988         { N0.getOperand(0), N0.getOperand(1),
7989           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7990           N0.getOperand(2) };
7991       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7992     }
7993
7994     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7995     //      (select_cc x, y, 1.0, 0.0,, cc)
7996     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7997         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7998         (!LegalOperations ||
7999          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8000       SDValue Ops[] =
8001         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8002           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
8003           N0.getOperand(0).getOperand(2) };
8004       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
8005     }
8006   }
8007
8008   return SDValue();
8009 }
8010
8011 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8012   SDValue N0 = N->getOperand(0);
8013   EVT VT = N->getValueType(0);
8014   EVT OpVT = N0.getValueType();
8015
8016   // fold (uint_to_fp c1) -> c1fp
8017   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8018       // ...but only if the target supports immediate floating-point values
8019       (!LegalOperations ||
8020        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8021     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8022
8023   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8024   // but SINT_TO_FP is legal on this target, try to convert.
8025   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8026       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8027     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8028     if (DAG.SignBitIsZero(N0))
8029       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8030   }
8031
8032   // The next optimizations are desirable only if SELECT_CC can be lowered.
8033   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8034     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8035
8036     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8037         (!LegalOperations ||
8038          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8039       SDValue Ops[] =
8040         { N0.getOperand(0), N0.getOperand(1),
8041           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
8042           N0.getOperand(2) };
8043       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
8044     }
8045   }
8046
8047   return SDValue();
8048 }
8049
8050 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8051 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8052   SDValue N0 = N->getOperand(0);
8053   EVT VT = N->getValueType(0);
8054
8055   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8056     return SDValue();
8057
8058   SDValue Src = N0.getOperand(0);
8059   EVT SrcVT = Src.getValueType();
8060   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8061   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8062
8063   // We can safely assume the conversion won't overflow the output range,
8064   // because (for example) (uint8_t)18293.f is undefined behavior.
8065
8066   // Since we can assume the conversion won't overflow, our decision as to
8067   // whether the input will fit in the float should depend on the minimum
8068   // of the input range and output range.
8069
8070   // This means this is also safe for a signed input and unsigned output, since
8071   // a negative input would lead to undefined behavior.
8072   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8073   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8074   unsigned ActualSize = std::min(InputSize, OutputSize);
8075   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8076
8077   // We can only fold away the float conversion if the input range can be
8078   // represented exactly in the float range.
8079   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8080     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8081       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8082                                                        : ISD::ZERO_EXTEND;
8083       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8084     }
8085     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8086       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8087     if (SrcVT == VT)
8088       return Src;
8089     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8090   }
8091   return SDValue();
8092 }
8093
8094 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8095   SDValue N0 = N->getOperand(0);
8096   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8097   EVT VT = N->getValueType(0);
8098
8099   // fold (fp_to_sint c1fp) -> c1
8100   if (N0CFP)
8101     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8102
8103   return FoldIntToFPToInt(N, DAG);
8104 }
8105
8106 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8107   SDValue N0 = N->getOperand(0);
8108   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8109   EVT VT = N->getValueType(0);
8110
8111   // fold (fp_to_uint c1fp) -> c1
8112   if (N0CFP)
8113     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8114
8115   return FoldIntToFPToInt(N, DAG);
8116 }
8117
8118 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8119   SDValue N0 = N->getOperand(0);
8120   SDValue N1 = N->getOperand(1);
8121   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8122   EVT VT = N->getValueType(0);
8123
8124   // fold (fp_round c1fp) -> c1fp
8125   if (N0CFP)
8126     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8127
8128   // fold (fp_round (fp_extend x)) -> x
8129   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8130     return N0.getOperand(0);
8131
8132   // fold (fp_round (fp_round x)) -> (fp_round x)
8133   if (N0.getOpcode() == ISD::FP_ROUND) {
8134     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8135     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8136     // If the first fp_round isn't a value preserving truncation, it might
8137     // introduce a tie in the second fp_round, that wouldn't occur in the
8138     // single-step fp_round we want to fold to.
8139     // In other words, double rounding isn't the same as rounding.
8140     // Also, this is a value preserving truncation iff both fp_round's are.
8141     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc)
8142       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
8143                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc));
8144   }
8145
8146   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8147   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8148     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8149                               N0.getOperand(0), N1);
8150     AddToWorklist(Tmp.getNode());
8151     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8152                        Tmp, N0.getOperand(1));
8153   }
8154
8155   return SDValue();
8156 }
8157
8158 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8159   SDValue N0 = N->getOperand(0);
8160   EVT VT = N->getValueType(0);
8161   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8162   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8163
8164   // fold (fp_round_inreg c1fp) -> c1fp
8165   if (N0CFP && isTypeLegal(EVT)) {
8166     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
8167     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
8168   }
8169
8170   return SDValue();
8171 }
8172
8173 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8174   SDValue N0 = N->getOperand(0);
8175   EVT VT = N->getValueType(0);
8176
8177   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8178   if (N->hasOneUse() &&
8179       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8180     return SDValue();
8181
8182   // fold (fp_extend c1fp) -> c1fp
8183   if (isConstantFPBuildVectorOrConstantFP(N0))
8184     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8185
8186   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8187   // value of X.
8188   if (N0.getOpcode() == ISD::FP_ROUND
8189       && N0.getNode()->getConstantOperandVal(1) == 1) {
8190     SDValue In = N0.getOperand(0);
8191     if (In.getValueType() == VT) return In;
8192     if (VT.bitsLT(In.getValueType()))
8193       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8194                          In, N0.getOperand(1));
8195     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8196   }
8197
8198   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8199   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8200        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8201     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8202     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8203                                      LN0->getChain(),
8204                                      LN0->getBasePtr(), N0.getValueType(),
8205                                      LN0->getMemOperand());
8206     CombineTo(N, ExtLoad);
8207     CombineTo(N0.getNode(),
8208               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8209                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
8210               ExtLoad.getValue(1));
8211     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8212   }
8213
8214   return SDValue();
8215 }
8216
8217 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8218   SDValue N0 = N->getOperand(0);
8219   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8220   EVT VT = N->getValueType(0);
8221
8222   // fold (fceil c1) -> fceil(c1)
8223   if (N0CFP)
8224     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8225
8226   return SDValue();
8227 }
8228
8229 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8230   SDValue N0 = N->getOperand(0);
8231   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8232   EVT VT = N->getValueType(0);
8233
8234   // fold (ftrunc c1) -> ftrunc(c1)
8235   if (N0CFP)
8236     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8237
8238   return SDValue();
8239 }
8240
8241 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8242   SDValue N0 = N->getOperand(0);
8243   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8244   EVT VT = N->getValueType(0);
8245
8246   // fold (ffloor c1) -> ffloor(c1)
8247   if (N0CFP)
8248     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8249
8250   return SDValue();
8251 }
8252
8253 // FIXME: FNEG and FABS have a lot in common; refactor.
8254 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8255   SDValue N0 = N->getOperand(0);
8256   EVT VT = N->getValueType(0);
8257
8258   // Constant fold FNEG.
8259   if (isConstantFPBuildVectorOrConstantFP(N0))
8260     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8261
8262   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8263                          &DAG.getTarget().Options))
8264     return GetNegatedExpression(N0, DAG, LegalOperations);
8265
8266   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8267   // constant pool values.
8268   if (!TLI.isFNegFree(VT) &&
8269       N0.getOpcode() == ISD::BITCAST &&
8270       N0.getNode()->hasOneUse()) {
8271     SDValue Int = N0.getOperand(0);
8272     EVT IntVT = Int.getValueType();
8273     if (IntVT.isInteger() && !IntVT.isVector()) {
8274       APInt SignMask;
8275       if (N0.getValueType().isVector()) {
8276         // For a vector, get a mask such as 0x80... per scalar element
8277         // and splat it.
8278         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8279         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8280       } else {
8281         // For a scalar, just generate 0x80...
8282         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8283       }
8284       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
8285                         DAG.getConstant(SignMask, IntVT));
8286       AddToWorklist(Int.getNode());
8287       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8288     }
8289   }
8290
8291   // (fneg (fmul c, x)) -> (fmul -c, x)
8292   if (N0.getOpcode() == ISD::FMUL) {
8293     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8294     if (CFP1) {
8295       APFloat CVal = CFP1->getValueAPF();
8296       CVal.changeSign();
8297       if (Level >= AfterLegalizeDAG &&
8298           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8299            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8300         return DAG.getNode(
8301             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8302             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8303     }
8304   }
8305
8306   return SDValue();
8307 }
8308
8309 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8310   SDValue N0 = N->getOperand(0);
8311   SDValue N1 = N->getOperand(1);
8312   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8313   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8314
8315   if (N0CFP && N1CFP) {
8316     const APFloat &C0 = N0CFP->getValueAPF();
8317     const APFloat &C1 = N1CFP->getValueAPF();
8318     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
8319   }
8320
8321   if (N0CFP) {
8322     EVT VT = N->getValueType(0);
8323     // Canonicalize to constant on RHS.
8324     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8325   }
8326
8327   return SDValue();
8328 }
8329
8330 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8331   SDValue N0 = N->getOperand(0);
8332   SDValue N1 = N->getOperand(1);
8333   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8334   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8335
8336   if (N0CFP && N1CFP) {
8337     const APFloat &C0 = N0CFP->getValueAPF();
8338     const APFloat &C1 = N1CFP->getValueAPF();
8339     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
8340   }
8341
8342   if (N0CFP) {
8343     EVT VT = N->getValueType(0);
8344     // Canonicalize to constant on RHS.
8345     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8346   }
8347
8348   return SDValue();
8349 }
8350
8351 SDValue DAGCombiner::visitFABS(SDNode *N) {
8352   SDValue N0 = N->getOperand(0);
8353   EVT VT = N->getValueType(0);
8354
8355   // fold (fabs c1) -> fabs(c1)
8356   if (isConstantFPBuildVectorOrConstantFP(N0))
8357     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8358
8359   // fold (fabs (fabs x)) -> (fabs x)
8360   if (N0.getOpcode() == ISD::FABS)
8361     return N->getOperand(0);
8362
8363   // fold (fabs (fneg x)) -> (fabs x)
8364   // fold (fabs (fcopysign x, y)) -> (fabs x)
8365   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8366     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8367
8368   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8369   // constant pool values.
8370   if (!TLI.isFAbsFree(VT) &&
8371       N0.getOpcode() == ISD::BITCAST &&
8372       N0.getNode()->hasOneUse()) {
8373     SDValue Int = N0.getOperand(0);
8374     EVT IntVT = Int.getValueType();
8375     if (IntVT.isInteger() && !IntVT.isVector()) {
8376       APInt SignMask;
8377       if (N0.getValueType().isVector()) {
8378         // For a vector, get a mask such as 0x7f... per scalar element
8379         // and splat it.
8380         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8381         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8382       } else {
8383         // For a scalar, just generate 0x7f...
8384         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8385       }
8386       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
8387                         DAG.getConstant(SignMask, IntVT));
8388       AddToWorklist(Int.getNode());
8389       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8390     }
8391   }
8392
8393   return SDValue();
8394 }
8395
8396 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8397   SDValue Chain = N->getOperand(0);
8398   SDValue N1 = N->getOperand(1);
8399   SDValue N2 = N->getOperand(2);
8400
8401   // If N is a constant we could fold this into a fallthrough or unconditional
8402   // branch. However that doesn't happen very often in normal code, because
8403   // Instcombine/SimplifyCFG should have handled the available opportunities.
8404   // If we did this folding here, it would be necessary to update the
8405   // MachineBasicBlock CFG, which is awkward.
8406
8407   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8408   // on the target.
8409   if (N1.getOpcode() == ISD::SETCC &&
8410       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8411                                    N1.getOperand(0).getValueType())) {
8412     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8413                        Chain, N1.getOperand(2),
8414                        N1.getOperand(0), N1.getOperand(1), N2);
8415   }
8416
8417   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8418       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8419        (N1.getOperand(0).hasOneUse() &&
8420         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8421     SDNode *Trunc = nullptr;
8422     if (N1.getOpcode() == ISD::TRUNCATE) {
8423       // Look pass the truncate.
8424       Trunc = N1.getNode();
8425       N1 = N1.getOperand(0);
8426     }
8427
8428     // Match this pattern so that we can generate simpler code:
8429     //
8430     //   %a = ...
8431     //   %b = and i32 %a, 2
8432     //   %c = srl i32 %b, 1
8433     //   brcond i32 %c ...
8434     //
8435     // into
8436     //
8437     //   %a = ...
8438     //   %b = and i32 %a, 2
8439     //   %c = setcc eq %b, 0
8440     //   brcond %c ...
8441     //
8442     // This applies only when the AND constant value has one bit set and the
8443     // SRL constant is equal to the log2 of the AND constant. The back-end is
8444     // smart enough to convert the result into a TEST/JMP sequence.
8445     SDValue Op0 = N1.getOperand(0);
8446     SDValue Op1 = N1.getOperand(1);
8447
8448     if (Op0.getOpcode() == ISD::AND &&
8449         Op1.getOpcode() == ISD::Constant) {
8450       SDValue AndOp1 = Op0.getOperand(1);
8451
8452       if (AndOp1.getOpcode() == ISD::Constant) {
8453         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8454
8455         if (AndConst.isPowerOf2() &&
8456             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8457           SDValue SetCC =
8458             DAG.getSetCC(SDLoc(N),
8459                          getSetCCResultType(Op0.getValueType()),
8460                          Op0, DAG.getConstant(0, Op0.getValueType()),
8461                          ISD::SETNE);
8462
8463           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8464                                           MVT::Other, Chain, SetCC, N2);
8465           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8466           // will convert it back to (X & C1) >> C2.
8467           CombineTo(N, NewBRCond, false);
8468           // Truncate is dead.
8469           if (Trunc)
8470             deleteAndRecombine(Trunc);
8471           // Replace the uses of SRL with SETCC
8472           WorklistRemover DeadNodes(*this);
8473           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8474           deleteAndRecombine(N1.getNode());
8475           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8476         }
8477       }
8478     }
8479
8480     if (Trunc)
8481       // Restore N1 if the above transformation doesn't match.
8482       N1 = N->getOperand(1);
8483   }
8484
8485   // Transform br(xor(x, y)) -> br(x != y)
8486   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8487   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8488     SDNode *TheXor = N1.getNode();
8489     SDValue Op0 = TheXor->getOperand(0);
8490     SDValue Op1 = TheXor->getOperand(1);
8491     if (Op0.getOpcode() == Op1.getOpcode()) {
8492       // Avoid missing important xor optimizations.
8493       SDValue Tmp = visitXOR(TheXor);
8494       if (Tmp.getNode()) {
8495         if (Tmp.getNode() != TheXor) {
8496           DEBUG(dbgs() << "\nReplacing.8 ";
8497                 TheXor->dump(&DAG);
8498                 dbgs() << "\nWith: ";
8499                 Tmp.getNode()->dump(&DAG);
8500                 dbgs() << '\n');
8501           WorklistRemover DeadNodes(*this);
8502           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8503           deleteAndRecombine(TheXor);
8504           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8505                              MVT::Other, Chain, Tmp, N2);
8506         }
8507
8508         // visitXOR has changed XOR's operands or replaced the XOR completely,
8509         // bail out.
8510         return SDValue(N, 0);
8511       }
8512     }
8513
8514     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8515       bool Equal = false;
8516       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8517         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8518             Op0.getOpcode() == ISD::XOR) {
8519           TheXor = Op0.getNode();
8520           Equal = true;
8521         }
8522
8523       EVT SetCCVT = N1.getValueType();
8524       if (LegalTypes)
8525         SetCCVT = getSetCCResultType(SetCCVT);
8526       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8527                                    SetCCVT,
8528                                    Op0, Op1,
8529                                    Equal ? ISD::SETEQ : ISD::SETNE);
8530       // Replace the uses of XOR with SETCC
8531       WorklistRemover DeadNodes(*this);
8532       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8533       deleteAndRecombine(N1.getNode());
8534       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8535                          MVT::Other, Chain, SetCC, N2);
8536     }
8537   }
8538
8539   return SDValue();
8540 }
8541
8542 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8543 //
8544 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8545   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8546   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8547
8548   // If N is a constant we could fold this into a fallthrough or unconditional
8549   // branch. However that doesn't happen very often in normal code, because
8550   // Instcombine/SimplifyCFG should have handled the available opportunities.
8551   // If we did this folding here, it would be necessary to update the
8552   // MachineBasicBlock CFG, which is awkward.
8553
8554   // Use SimplifySetCC to simplify SETCC's.
8555   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8556                                CondLHS, CondRHS, CC->get(), SDLoc(N),
8557                                false);
8558   if (Simp.getNode()) AddToWorklist(Simp.getNode());
8559
8560   // fold to a simpler setcc
8561   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8562     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8563                        N->getOperand(0), Simp.getOperand(2),
8564                        Simp.getOperand(0), Simp.getOperand(1),
8565                        N->getOperand(4));
8566
8567   return SDValue();
8568 }
8569
8570 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8571 /// and that N may be folded in the load / store addressing mode.
8572 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8573                                     SelectionDAG &DAG,
8574                                     const TargetLowering &TLI) {
8575   EVT VT;
8576   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
8577     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8578       return false;
8579     VT = Use->getValueType(0);
8580   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
8581     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8582       return false;
8583     VT = ST->getValue().getValueType();
8584   } else
8585     return false;
8586
8587   TargetLowering::AddrMode AM;
8588   if (N->getOpcode() == ISD::ADD) {
8589     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8590     if (Offset)
8591       // [reg +/- imm]
8592       AM.BaseOffs = Offset->getSExtValue();
8593     else
8594       // [reg +/- reg]
8595       AM.Scale = 1;
8596   } else if (N->getOpcode() == ISD::SUB) {
8597     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8598     if (Offset)
8599       // [reg +/- imm]
8600       AM.BaseOffs = -Offset->getSExtValue();
8601     else
8602       // [reg +/- reg]
8603       AM.Scale = 1;
8604   } else
8605     return false;
8606
8607   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8608 }
8609
8610 /// Try turning a load/store into a pre-indexed load/store when the base
8611 /// pointer is an add or subtract and it has other uses besides the load/store.
8612 /// After the transformation, the new indexed load/store has effectively folded
8613 /// the add/subtract in and all of its other uses are redirected to the
8614 /// new load/store.
8615 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8616   if (Level < AfterLegalizeDAG)
8617     return false;
8618
8619   bool isLoad = true;
8620   SDValue Ptr;
8621   EVT VT;
8622   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8623     if (LD->isIndexed())
8624       return false;
8625     VT = LD->getMemoryVT();
8626     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8627         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8628       return false;
8629     Ptr = LD->getBasePtr();
8630   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8631     if (ST->isIndexed())
8632       return false;
8633     VT = ST->getMemoryVT();
8634     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8635         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8636       return false;
8637     Ptr = ST->getBasePtr();
8638     isLoad = false;
8639   } else {
8640     return false;
8641   }
8642
8643   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8644   // out.  There is no reason to make this a preinc/predec.
8645   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8646       Ptr.getNode()->hasOneUse())
8647     return false;
8648
8649   // Ask the target to do addressing mode selection.
8650   SDValue BasePtr;
8651   SDValue Offset;
8652   ISD::MemIndexedMode AM = ISD::UNINDEXED;
8653   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8654     return false;
8655
8656   // Backends without true r+i pre-indexed forms may need to pass a
8657   // constant base with a variable offset so that constant coercion
8658   // will work with the patterns in canonical form.
8659   bool Swapped = false;
8660   if (isa<ConstantSDNode>(BasePtr)) {
8661     std::swap(BasePtr, Offset);
8662     Swapped = true;
8663   }
8664
8665   // Don't create a indexed load / store with zero offset.
8666   if (isa<ConstantSDNode>(Offset) &&
8667       cast<ConstantSDNode>(Offset)->isNullValue())
8668     return false;
8669
8670   // Try turning it into a pre-indexed load / store except when:
8671   // 1) The new base ptr is a frame index.
8672   // 2) If N is a store and the new base ptr is either the same as or is a
8673   //    predecessor of the value being stored.
8674   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8675   //    that would create a cycle.
8676   // 4) All uses are load / store ops that use it as old base ptr.
8677
8678   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
8679   // (plus the implicit offset) to a register to preinc anyway.
8680   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8681     return false;
8682
8683   // Check #2.
8684   if (!isLoad) {
8685     SDValue Val = cast<StoreSDNode>(N)->getValue();
8686     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8687       return false;
8688   }
8689
8690   // If the offset is a constant, there may be other adds of constants that
8691   // can be folded with this one. We should do this to avoid having to keep
8692   // a copy of the original base pointer.
8693   SmallVector<SDNode *, 16> OtherUses;
8694   if (isa<ConstantSDNode>(Offset))
8695     for (SDNode *Use : BasePtr.getNode()->uses()) {
8696       if (Use == Ptr.getNode())
8697         continue;
8698
8699       if (Use->isPredecessorOf(N))
8700         continue;
8701
8702       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8703         OtherUses.clear();
8704         break;
8705       }
8706
8707       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8708       if (Op1.getNode() == BasePtr.getNode())
8709         std::swap(Op0, Op1);
8710       assert(Op0.getNode() == BasePtr.getNode() &&
8711              "Use of ADD/SUB but not an operand");
8712
8713       if (!isa<ConstantSDNode>(Op1)) {
8714         OtherUses.clear();
8715         break;
8716       }
8717
8718       // FIXME: In some cases, we can be smarter about this.
8719       if (Op1.getValueType() != Offset.getValueType()) {
8720         OtherUses.clear();
8721         break;
8722       }
8723
8724       OtherUses.push_back(Use);
8725     }
8726
8727   if (Swapped)
8728     std::swap(BasePtr, Offset);
8729
8730   // Now check for #3 and #4.
8731   bool RealUse = false;
8732
8733   // Caches for hasPredecessorHelper
8734   SmallPtrSet<const SDNode *, 32> Visited;
8735   SmallVector<const SDNode *, 16> Worklist;
8736
8737   for (SDNode *Use : Ptr.getNode()->uses()) {
8738     if (Use == N)
8739       continue;
8740     if (N->hasPredecessorHelper(Use, Visited, Worklist))
8741       return false;
8742
8743     // If Ptr may be folded in addressing mode of other use, then it's
8744     // not profitable to do this transformation.
8745     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8746       RealUse = true;
8747   }
8748
8749   if (!RealUse)
8750     return false;
8751
8752   SDValue Result;
8753   if (isLoad)
8754     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8755                                 BasePtr, Offset, AM);
8756   else
8757     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8758                                  BasePtr, Offset, AM);
8759   ++PreIndexedNodes;
8760   ++NodesCombined;
8761   DEBUG(dbgs() << "\nReplacing.4 ";
8762         N->dump(&DAG);
8763         dbgs() << "\nWith: ";
8764         Result.getNode()->dump(&DAG);
8765         dbgs() << '\n');
8766   WorklistRemover DeadNodes(*this);
8767   if (isLoad) {
8768     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8769     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8770   } else {
8771     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8772   }
8773
8774   // Finally, since the node is now dead, remove it from the graph.
8775   deleteAndRecombine(N);
8776
8777   if (Swapped)
8778     std::swap(BasePtr, Offset);
8779
8780   // Replace other uses of BasePtr that can be updated to use Ptr
8781   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8782     unsigned OffsetIdx = 1;
8783     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8784       OffsetIdx = 0;
8785     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8786            BasePtr.getNode() && "Expected BasePtr operand");
8787
8788     // We need to replace ptr0 in the following expression:
8789     //   x0 * offset0 + y0 * ptr0 = t0
8790     // knowing that
8791     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8792     //
8793     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8794     // indexed load/store and the expresion that needs to be re-written.
8795     //
8796     // Therefore, we have:
8797     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8798
8799     ConstantSDNode *CN =
8800       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8801     int X0, X1, Y0, Y1;
8802     APInt Offset0 = CN->getAPIntValue();
8803     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8804
8805     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8806     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8807     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8808     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8809
8810     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8811
8812     APInt CNV = Offset0;
8813     if (X0 < 0) CNV = -CNV;
8814     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8815     else CNV = CNV - Offset1;
8816
8817     // We can now generate the new expression.
8818     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8819     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8820
8821     SDValue NewUse = DAG.getNode(Opcode,
8822                                  SDLoc(OtherUses[i]),
8823                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8824     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8825     deleteAndRecombine(OtherUses[i]);
8826   }
8827
8828   // Replace the uses of Ptr with uses of the updated base value.
8829   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8830   deleteAndRecombine(Ptr.getNode());
8831
8832   return true;
8833 }
8834
8835 /// Try to combine a load/store with a add/sub of the base pointer node into a
8836 /// post-indexed load/store. The transformation folded the add/subtract into the
8837 /// new indexed load/store effectively and all of its uses are redirected to the
8838 /// new load/store.
8839 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8840   if (Level < AfterLegalizeDAG)
8841     return false;
8842
8843   bool isLoad = true;
8844   SDValue Ptr;
8845   EVT VT;
8846   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8847     if (LD->isIndexed())
8848       return false;
8849     VT = LD->getMemoryVT();
8850     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8851         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8852       return false;
8853     Ptr = LD->getBasePtr();
8854   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8855     if (ST->isIndexed())
8856       return false;
8857     VT = ST->getMemoryVT();
8858     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8859         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8860       return false;
8861     Ptr = ST->getBasePtr();
8862     isLoad = false;
8863   } else {
8864     return false;
8865   }
8866
8867   if (Ptr.getNode()->hasOneUse())
8868     return false;
8869
8870   for (SDNode *Op : Ptr.getNode()->uses()) {
8871     if (Op == N ||
8872         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8873       continue;
8874
8875     SDValue BasePtr;
8876     SDValue Offset;
8877     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8878     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8879       // Don't create a indexed load / store with zero offset.
8880       if (isa<ConstantSDNode>(Offset) &&
8881           cast<ConstantSDNode>(Offset)->isNullValue())
8882         continue;
8883
8884       // Try turning it into a post-indexed load / store except when
8885       // 1) All uses are load / store ops that use it as base ptr (and
8886       //    it may be folded as addressing mmode).
8887       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8888       //    nor a successor of N. Otherwise, if Op is folded that would
8889       //    create a cycle.
8890
8891       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8892         continue;
8893
8894       // Check for #1.
8895       bool TryNext = false;
8896       for (SDNode *Use : BasePtr.getNode()->uses()) {
8897         if (Use == Ptr.getNode())
8898           continue;
8899
8900         // If all the uses are load / store addresses, then don't do the
8901         // transformation.
8902         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8903           bool RealUse = false;
8904           for (SDNode *UseUse : Use->uses()) {
8905             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8906               RealUse = true;
8907           }
8908
8909           if (!RealUse) {
8910             TryNext = true;
8911             break;
8912           }
8913         }
8914       }
8915
8916       if (TryNext)
8917         continue;
8918
8919       // Check for #2
8920       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8921         SDValue Result = isLoad
8922           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8923                                BasePtr, Offset, AM)
8924           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8925                                 BasePtr, Offset, AM);
8926         ++PostIndexedNodes;
8927         ++NodesCombined;
8928         DEBUG(dbgs() << "\nReplacing.5 ";
8929               N->dump(&DAG);
8930               dbgs() << "\nWith: ";
8931               Result.getNode()->dump(&DAG);
8932               dbgs() << '\n');
8933         WorklistRemover DeadNodes(*this);
8934         if (isLoad) {
8935           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8936           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8937         } else {
8938           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8939         }
8940
8941         // Finally, since the node is now dead, remove it from the graph.
8942         deleteAndRecombine(N);
8943
8944         // Replace the uses of Use with uses of the updated base value.
8945         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8946                                       Result.getValue(isLoad ? 1 : 0));
8947         deleteAndRecombine(Op);
8948         return true;
8949       }
8950     }
8951   }
8952
8953   return false;
8954 }
8955
8956 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8957 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8958   ISD::MemIndexedMode AM = LD->getAddressingMode();
8959   assert(AM != ISD::UNINDEXED);
8960   SDValue BP = LD->getOperand(1);
8961   SDValue Inc = LD->getOperand(2);
8962
8963   // Some backends use TargetConstants for load offsets, but don't expect
8964   // TargetConstants in general ADD nodes. We can convert these constants into
8965   // regular Constants (if the constant is not opaque).
8966   assert((Inc.getOpcode() != ISD::TargetConstant ||
8967           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8968          "Cannot split out indexing using opaque target constants");
8969   if (Inc.getOpcode() == ISD::TargetConstant) {
8970     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8971     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8972                           ConstInc->getValueType(0));
8973   }
8974
8975   unsigned Opc =
8976       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8977   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8978 }
8979
8980 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8981   LoadSDNode *LD  = cast<LoadSDNode>(N);
8982   SDValue Chain = LD->getChain();
8983   SDValue Ptr   = LD->getBasePtr();
8984
8985   // If load is not volatile and there are no uses of the loaded value (and
8986   // the updated indexed value in case of indexed loads), change uses of the
8987   // chain value into uses of the chain input (i.e. delete the dead load).
8988   if (!LD->isVolatile()) {
8989     if (N->getValueType(1) == MVT::Other) {
8990       // Unindexed loads.
8991       if (!N->hasAnyUseOfValue(0)) {
8992         // It's not safe to use the two value CombineTo variant here. e.g.
8993         // v1, chain2 = load chain1, loc
8994         // v2, chain3 = load chain2, loc
8995         // v3         = add v2, c
8996         // Now we replace use of chain2 with chain1.  This makes the second load
8997         // isomorphic to the one we are deleting, and thus makes this load live.
8998         DEBUG(dbgs() << "\nReplacing.6 ";
8999               N->dump(&DAG);
9000               dbgs() << "\nWith chain: ";
9001               Chain.getNode()->dump(&DAG);
9002               dbgs() << "\n");
9003         WorklistRemover DeadNodes(*this);
9004         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9005
9006         if (N->use_empty())
9007           deleteAndRecombine(N);
9008
9009         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9010       }
9011     } else {
9012       // Indexed loads.
9013       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9014
9015       // If this load has an opaque TargetConstant offset, then we cannot split
9016       // the indexing into an add/sub directly (that TargetConstant may not be
9017       // valid for a different type of node, and we cannot convert an opaque
9018       // target constant into a regular constant).
9019       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9020                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9021
9022       if (!N->hasAnyUseOfValue(0) &&
9023           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9024         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9025         SDValue Index;
9026         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9027           Index = SplitIndexingFromLoad(LD);
9028           // Try to fold the base pointer arithmetic into subsequent loads and
9029           // stores.
9030           AddUsersToWorklist(N);
9031         } else
9032           Index = DAG.getUNDEF(N->getValueType(1));
9033         DEBUG(dbgs() << "\nReplacing.7 ";
9034               N->dump(&DAG);
9035               dbgs() << "\nWith: ";
9036               Undef.getNode()->dump(&DAG);
9037               dbgs() << " and 2 other values\n");
9038         WorklistRemover DeadNodes(*this);
9039         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9040         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9041         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9042         deleteAndRecombine(N);
9043         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9044       }
9045     }
9046   }
9047
9048   // If this load is directly stored, replace the load value with the stored
9049   // value.
9050   // TODO: Handle store large -> read small portion.
9051   // TODO: Handle TRUNCSTORE/LOADEXT
9052   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9053     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9054       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9055       if (PrevST->getBasePtr() == Ptr &&
9056           PrevST->getValue().getValueType() == N->getValueType(0))
9057       return CombineTo(N, Chain.getOperand(1), Chain);
9058     }
9059   }
9060
9061   // Try to infer better alignment information than the load already has.
9062   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9063     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9064       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9065         SDValue NewLoad =
9066                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9067                               LD->getValueType(0),
9068                               Chain, Ptr, LD->getPointerInfo(),
9069                               LD->getMemoryVT(),
9070                               LD->isVolatile(), LD->isNonTemporal(),
9071                               LD->isInvariant(), Align, LD->getAAInfo());
9072         if (NewLoad.getNode() != N)
9073           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9074       }
9075     }
9076   }
9077
9078   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9079                                                   : DAG.getSubtarget().useAA();
9080 #ifndef NDEBUG
9081   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9082       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9083     UseAA = false;
9084 #endif
9085   if (UseAA && LD->isUnindexed()) {
9086     // Walk up chain skipping non-aliasing memory nodes.
9087     SDValue BetterChain = FindBetterChain(N, Chain);
9088
9089     // If there is a better chain.
9090     if (Chain != BetterChain) {
9091       SDValue ReplLoad;
9092
9093       // Replace the chain to void dependency.
9094       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9095         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9096                                BetterChain, Ptr, LD->getMemOperand());
9097       } else {
9098         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9099                                   LD->getValueType(0),
9100                                   BetterChain, Ptr, LD->getMemoryVT(),
9101                                   LD->getMemOperand());
9102       }
9103
9104       // Create token factor to keep old chain connected.
9105       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9106                                   MVT::Other, Chain, ReplLoad.getValue(1));
9107
9108       // Make sure the new and old chains are cleaned up.
9109       AddToWorklist(Token.getNode());
9110
9111       // Replace uses with load result and token factor. Don't add users
9112       // to work list.
9113       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9114     }
9115   }
9116
9117   // Try transforming N to an indexed load.
9118   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9119     return SDValue(N, 0);
9120
9121   // Try to slice up N to more direct loads if the slices are mapped to
9122   // different register banks or pairing can take place.
9123   if (SliceUpLoad(N))
9124     return SDValue(N, 0);
9125
9126   return SDValue();
9127 }
9128
9129 namespace {
9130 /// \brief Helper structure used to slice a load in smaller loads.
9131 /// Basically a slice is obtained from the following sequence:
9132 /// Origin = load Ty1, Base
9133 /// Shift = srl Ty1 Origin, CstTy Amount
9134 /// Inst = trunc Shift to Ty2
9135 ///
9136 /// Then, it will be rewriten into:
9137 /// Slice = load SliceTy, Base + SliceOffset
9138 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9139 ///
9140 /// SliceTy is deduced from the number of bits that are actually used to
9141 /// build Inst.
9142 struct LoadedSlice {
9143   /// \brief Helper structure used to compute the cost of a slice.
9144   struct Cost {
9145     /// Are we optimizing for code size.
9146     bool ForCodeSize;
9147     /// Various cost.
9148     unsigned Loads;
9149     unsigned Truncates;
9150     unsigned CrossRegisterBanksCopies;
9151     unsigned ZExts;
9152     unsigned Shift;
9153
9154     Cost(bool ForCodeSize = false)
9155         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9156           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9157
9158     /// \brief Get the cost of one isolated slice.
9159     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9160         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9161           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9162       EVT TruncType = LS.Inst->getValueType(0);
9163       EVT LoadedType = LS.getLoadedType();
9164       if (TruncType != LoadedType &&
9165           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9166         ZExts = 1;
9167     }
9168
9169     /// \brief Account for slicing gain in the current cost.
9170     /// Slicing provide a few gains like removing a shift or a
9171     /// truncate. This method allows to grow the cost of the original
9172     /// load with the gain from this slice.
9173     void addSliceGain(const LoadedSlice &LS) {
9174       // Each slice saves a truncate.
9175       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9176       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9177                               LS.Inst->getOperand(0).getValueType()))
9178         ++Truncates;
9179       // If there is a shift amount, this slice gets rid of it.
9180       if (LS.Shift)
9181         ++Shift;
9182       // If this slice can merge a cross register bank copy, account for it.
9183       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9184         ++CrossRegisterBanksCopies;
9185     }
9186
9187     Cost &operator+=(const Cost &RHS) {
9188       Loads += RHS.Loads;
9189       Truncates += RHS.Truncates;
9190       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9191       ZExts += RHS.ZExts;
9192       Shift += RHS.Shift;
9193       return *this;
9194     }
9195
9196     bool operator==(const Cost &RHS) const {
9197       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9198              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9199              ZExts == RHS.ZExts && Shift == RHS.Shift;
9200     }
9201
9202     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9203
9204     bool operator<(const Cost &RHS) const {
9205       // Assume cross register banks copies are as expensive as loads.
9206       // FIXME: Do we want some more target hooks?
9207       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9208       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9209       // Unless we are optimizing for code size, consider the
9210       // expensive operation first.
9211       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9212         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9213       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9214              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9215     }
9216
9217     bool operator>(const Cost &RHS) const { return RHS < *this; }
9218
9219     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9220
9221     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9222   };
9223   // The last instruction that represent the slice. This should be a
9224   // truncate instruction.
9225   SDNode *Inst;
9226   // The original load instruction.
9227   LoadSDNode *Origin;
9228   // The right shift amount in bits from the original load.
9229   unsigned Shift;
9230   // The DAG from which Origin came from.
9231   // This is used to get some contextual information about legal types, etc.
9232   SelectionDAG *DAG;
9233
9234   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9235               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9236       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9237
9238   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9239   /// \return Result is \p BitWidth and has used bits set to 1 and
9240   ///         not used bits set to 0.
9241   APInt getUsedBits() const {
9242     // Reproduce the trunc(lshr) sequence:
9243     // - Start from the truncated value.
9244     // - Zero extend to the desired bit width.
9245     // - Shift left.
9246     assert(Origin && "No original load to compare against.");
9247     unsigned BitWidth = Origin->getValueSizeInBits(0);
9248     assert(Inst && "This slice is not bound to an instruction");
9249     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9250            "Extracted slice is bigger than the whole type!");
9251     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9252     UsedBits.setAllBits();
9253     UsedBits = UsedBits.zext(BitWidth);
9254     UsedBits <<= Shift;
9255     return UsedBits;
9256   }
9257
9258   /// \brief Get the size of the slice to be loaded in bytes.
9259   unsigned getLoadedSize() const {
9260     unsigned SliceSize = getUsedBits().countPopulation();
9261     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9262     return SliceSize / 8;
9263   }
9264
9265   /// \brief Get the type that will be loaded for this slice.
9266   /// Note: This may not be the final type for the slice.
9267   EVT getLoadedType() const {
9268     assert(DAG && "Missing context");
9269     LLVMContext &Ctxt = *DAG->getContext();
9270     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9271   }
9272
9273   /// \brief Get the alignment of the load used for this slice.
9274   unsigned getAlignment() const {
9275     unsigned Alignment = Origin->getAlignment();
9276     unsigned Offset = getOffsetFromBase();
9277     if (Offset != 0)
9278       Alignment = MinAlign(Alignment, Alignment + Offset);
9279     return Alignment;
9280   }
9281
9282   /// \brief Check if this slice can be rewritten with legal operations.
9283   bool isLegal() const {
9284     // An invalid slice is not legal.
9285     if (!Origin || !Inst || !DAG)
9286       return false;
9287
9288     // Offsets are for indexed load only, we do not handle that.
9289     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9290       return false;
9291
9292     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9293
9294     // Check that the type is legal.
9295     EVT SliceType = getLoadedType();
9296     if (!TLI.isTypeLegal(SliceType))
9297       return false;
9298
9299     // Check that the load is legal for this type.
9300     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9301       return false;
9302
9303     // Check that the offset can be computed.
9304     // 1. Check its type.
9305     EVT PtrType = Origin->getBasePtr().getValueType();
9306     if (PtrType == MVT::Untyped || PtrType.isExtended())
9307       return false;
9308
9309     // 2. Check that it fits in the immediate.
9310     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9311       return false;
9312
9313     // 3. Check that the computation is legal.
9314     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9315       return false;
9316
9317     // Check that the zext is legal if it needs one.
9318     EVT TruncateType = Inst->getValueType(0);
9319     if (TruncateType != SliceType &&
9320         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9321       return false;
9322
9323     return true;
9324   }
9325
9326   /// \brief Get the offset in bytes of this slice in the original chunk of
9327   /// bits.
9328   /// \pre DAG != nullptr.
9329   uint64_t getOffsetFromBase() const {
9330     assert(DAG && "Missing context.");
9331     bool IsBigEndian =
9332         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9333     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9334     uint64_t Offset = Shift / 8;
9335     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9336     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9337            "The size of the original loaded type is not a multiple of a"
9338            " byte.");
9339     // If Offset is bigger than TySizeInBytes, it means we are loading all
9340     // zeros. This should have been optimized before in the process.
9341     assert(TySizeInBytes > Offset &&
9342            "Invalid shift amount for given loaded size");
9343     if (IsBigEndian)
9344       Offset = TySizeInBytes - Offset - getLoadedSize();
9345     return Offset;
9346   }
9347
9348   /// \brief Generate the sequence of instructions to load the slice
9349   /// represented by this object and redirect the uses of this slice to
9350   /// this new sequence of instructions.
9351   /// \pre this->Inst && this->Origin are valid Instructions and this
9352   /// object passed the legal check: LoadedSlice::isLegal returned true.
9353   /// \return The last instruction of the sequence used to load the slice.
9354   SDValue loadSlice() const {
9355     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9356     const SDValue &OldBaseAddr = Origin->getBasePtr();
9357     SDValue BaseAddr = OldBaseAddr;
9358     // Get the offset in that chunk of bytes w.r.t. the endianess.
9359     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9360     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9361     if (Offset) {
9362       // BaseAddr = BaseAddr + Offset.
9363       EVT ArithType = BaseAddr.getValueType();
9364       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9365                               DAG->getConstant(Offset, ArithType));
9366     }
9367
9368     // Create the type of the loaded slice according to its size.
9369     EVT SliceType = getLoadedType();
9370
9371     // Create the load for the slice.
9372     SDValue LastInst = DAG->getLoad(
9373         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9374         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9375         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9376     // If the final type is not the same as the loaded type, this means that
9377     // we have to pad with zero. Create a zero extend for that.
9378     EVT FinalType = Inst->getValueType(0);
9379     if (SliceType != FinalType)
9380       LastInst =
9381           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9382     return LastInst;
9383   }
9384
9385   /// \brief Check if this slice can be merged with an expensive cross register
9386   /// bank copy. E.g.,
9387   /// i = load i32
9388   /// f = bitcast i32 i to float
9389   bool canMergeExpensiveCrossRegisterBankCopy() const {
9390     if (!Inst || !Inst->hasOneUse())
9391       return false;
9392     SDNode *Use = *Inst->use_begin();
9393     if (Use->getOpcode() != ISD::BITCAST)
9394       return false;
9395     assert(DAG && "Missing context");
9396     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9397     EVT ResVT = Use->getValueType(0);
9398     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9399     const TargetRegisterClass *ArgRC =
9400         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9401     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9402       return false;
9403
9404     // At this point, we know that we perform a cross-register-bank copy.
9405     // Check if it is expensive.
9406     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9407     // Assume bitcasts are cheap, unless both register classes do not
9408     // explicitly share a common sub class.
9409     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9410       return false;
9411
9412     // Check if it will be merged with the load.
9413     // 1. Check the alignment constraint.
9414     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9415         ResVT.getTypeForEVT(*DAG->getContext()));
9416
9417     if (RequiredAlignment > getAlignment())
9418       return false;
9419
9420     // 2. Check that the load is a legal operation for that type.
9421     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9422       return false;
9423
9424     // 3. Check that we do not have a zext in the way.
9425     if (Inst->getValueType(0) != getLoadedType())
9426       return false;
9427
9428     return true;
9429   }
9430 };
9431 }
9432
9433 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9434 /// \p UsedBits looks like 0..0 1..1 0..0.
9435 static bool areUsedBitsDense(const APInt &UsedBits) {
9436   // If all the bits are one, this is dense!
9437   if (UsedBits.isAllOnesValue())
9438     return true;
9439
9440   // Get rid of the unused bits on the right.
9441   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9442   // Get rid of the unused bits on the left.
9443   if (NarrowedUsedBits.countLeadingZeros())
9444     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9445   // Check that the chunk of bits is completely used.
9446   return NarrowedUsedBits.isAllOnesValue();
9447 }
9448
9449 /// \brief Check whether or not \p First and \p Second are next to each other
9450 /// in memory. This means that there is no hole between the bits loaded
9451 /// by \p First and the bits loaded by \p Second.
9452 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9453                                      const LoadedSlice &Second) {
9454   assert(First.Origin == Second.Origin && First.Origin &&
9455          "Unable to match different memory origins.");
9456   APInt UsedBits = First.getUsedBits();
9457   assert((UsedBits & Second.getUsedBits()) == 0 &&
9458          "Slices are not supposed to overlap.");
9459   UsedBits |= Second.getUsedBits();
9460   return areUsedBitsDense(UsedBits);
9461 }
9462
9463 /// \brief Adjust the \p GlobalLSCost according to the target
9464 /// paring capabilities and the layout of the slices.
9465 /// \pre \p GlobalLSCost should account for at least as many loads as
9466 /// there is in the slices in \p LoadedSlices.
9467 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9468                                  LoadedSlice::Cost &GlobalLSCost) {
9469   unsigned NumberOfSlices = LoadedSlices.size();
9470   // If there is less than 2 elements, no pairing is possible.
9471   if (NumberOfSlices < 2)
9472     return;
9473
9474   // Sort the slices so that elements that are likely to be next to each
9475   // other in memory are next to each other in the list.
9476   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9477             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9478     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9479     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9480   });
9481   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9482   // First (resp. Second) is the first (resp. Second) potentially candidate
9483   // to be placed in a paired load.
9484   const LoadedSlice *First = nullptr;
9485   const LoadedSlice *Second = nullptr;
9486   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9487                 // Set the beginning of the pair.
9488                                                            First = Second) {
9489
9490     Second = &LoadedSlices[CurrSlice];
9491
9492     // If First is NULL, it means we start a new pair.
9493     // Get to the next slice.
9494     if (!First)
9495       continue;
9496
9497     EVT LoadedType = First->getLoadedType();
9498
9499     // If the types of the slices are different, we cannot pair them.
9500     if (LoadedType != Second->getLoadedType())
9501       continue;
9502
9503     // Check if the target supplies paired loads for this type.
9504     unsigned RequiredAlignment = 0;
9505     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9506       // move to the next pair, this type is hopeless.
9507       Second = nullptr;
9508       continue;
9509     }
9510     // Check if we meet the alignment requirement.
9511     if (RequiredAlignment > First->getAlignment())
9512       continue;
9513
9514     // Check that both loads are next to each other in memory.
9515     if (!areSlicesNextToEachOther(*First, *Second))
9516       continue;
9517
9518     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9519     --GlobalLSCost.Loads;
9520     // Move to the next pair.
9521     Second = nullptr;
9522   }
9523 }
9524
9525 /// \brief Check the profitability of all involved LoadedSlice.
9526 /// Currently, it is considered profitable if there is exactly two
9527 /// involved slices (1) which are (2) next to each other in memory, and
9528 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9529 ///
9530 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9531 /// the elements themselves.
9532 ///
9533 /// FIXME: When the cost model will be mature enough, we can relax
9534 /// constraints (1) and (2).
9535 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9536                                 const APInt &UsedBits, bool ForCodeSize) {
9537   unsigned NumberOfSlices = LoadedSlices.size();
9538   if (StressLoadSlicing)
9539     return NumberOfSlices > 1;
9540
9541   // Check (1).
9542   if (NumberOfSlices != 2)
9543     return false;
9544
9545   // Check (2).
9546   if (!areUsedBitsDense(UsedBits))
9547     return false;
9548
9549   // Check (3).
9550   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9551   // The original code has one big load.
9552   OrigCost.Loads = 1;
9553   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9554     const LoadedSlice &LS = LoadedSlices[CurrSlice];
9555     // Accumulate the cost of all the slices.
9556     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9557     GlobalSlicingCost += SliceCost;
9558
9559     // Account as cost in the original configuration the gain obtained
9560     // with the current slices.
9561     OrigCost.addSliceGain(LS);
9562   }
9563
9564   // If the target supports paired load, adjust the cost accordingly.
9565   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9566   return OrigCost > GlobalSlicingCost;
9567 }
9568
9569 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9570 /// operations, split it in the various pieces being extracted.
9571 ///
9572 /// This sort of thing is introduced by SROA.
9573 /// This slicing takes care not to insert overlapping loads.
9574 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9575 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9576   if (Level < AfterLegalizeDAG)
9577     return false;
9578
9579   LoadSDNode *LD = cast<LoadSDNode>(N);
9580   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9581       !LD->getValueType(0).isInteger())
9582     return false;
9583
9584   // Keep track of already used bits to detect overlapping values.
9585   // In that case, we will just abort the transformation.
9586   APInt UsedBits(LD->getValueSizeInBits(0), 0);
9587
9588   SmallVector<LoadedSlice, 4> LoadedSlices;
9589
9590   // Check if this load is used as several smaller chunks of bits.
9591   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9592   // of computation for each trunc.
9593   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9594        UI != UIEnd; ++UI) {
9595     // Skip the uses of the chain.
9596     if (UI.getUse().getResNo() != 0)
9597       continue;
9598
9599     SDNode *User = *UI;
9600     unsigned Shift = 0;
9601
9602     // Check if this is a trunc(lshr).
9603     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9604         isa<ConstantSDNode>(User->getOperand(1))) {
9605       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9606       User = *User->use_begin();
9607     }
9608
9609     // At this point, User is a Truncate, iff we encountered, trunc or
9610     // trunc(lshr).
9611     if (User->getOpcode() != ISD::TRUNCATE)
9612       return false;
9613
9614     // The width of the type must be a power of 2 and greater than 8-bits.
9615     // Otherwise the load cannot be represented in LLVM IR.
9616     // Moreover, if we shifted with a non-8-bits multiple, the slice
9617     // will be across several bytes. We do not support that.
9618     unsigned Width = User->getValueSizeInBits(0);
9619     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9620       return 0;
9621
9622     // Build the slice for this chain of computations.
9623     LoadedSlice LS(User, LD, Shift, &DAG);
9624     APInt CurrentUsedBits = LS.getUsedBits();
9625
9626     // Check if this slice overlaps with another.
9627     if ((CurrentUsedBits & UsedBits) != 0)
9628       return false;
9629     // Update the bits used globally.
9630     UsedBits |= CurrentUsedBits;
9631
9632     // Check if the new slice would be legal.
9633     if (!LS.isLegal())
9634       return false;
9635
9636     // Record the slice.
9637     LoadedSlices.push_back(LS);
9638   }
9639
9640   // Abort slicing if it does not seem to be profitable.
9641   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9642     return false;
9643
9644   ++SlicedLoads;
9645
9646   // Rewrite each chain to use an independent load.
9647   // By construction, each chain can be represented by a unique load.
9648
9649   // Prepare the argument for the new token factor for all the slices.
9650   SmallVector<SDValue, 8> ArgChains;
9651   for (SmallVectorImpl<LoadedSlice>::const_iterator
9652            LSIt = LoadedSlices.begin(),
9653            LSItEnd = LoadedSlices.end();
9654        LSIt != LSItEnd; ++LSIt) {
9655     SDValue SliceInst = LSIt->loadSlice();
9656     CombineTo(LSIt->Inst, SliceInst, true);
9657     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9658       SliceInst = SliceInst.getOperand(0);
9659     assert(SliceInst->getOpcode() == ISD::LOAD &&
9660            "It takes more than a zext to get to the loaded slice!!");
9661     ArgChains.push_back(SliceInst.getValue(1));
9662   }
9663
9664   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9665                               ArgChains);
9666   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9667   return true;
9668 }
9669
9670 /// Check to see if V is (and load (ptr), imm), where the load is having
9671 /// specific bytes cleared out.  If so, return the byte size being masked out
9672 /// and the shift amount.
9673 static std::pair<unsigned, unsigned>
9674 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9675   std::pair<unsigned, unsigned> Result(0, 0);
9676
9677   // Check for the structure we're looking for.
9678   if (V->getOpcode() != ISD::AND ||
9679       !isa<ConstantSDNode>(V->getOperand(1)) ||
9680       !ISD::isNormalLoad(V->getOperand(0).getNode()))
9681     return Result;
9682
9683   // Check the chain and pointer.
9684   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9685   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
9686
9687   // The store should be chained directly to the load or be an operand of a
9688   // tokenfactor.
9689   if (LD == Chain.getNode())
9690     ; // ok.
9691   else if (Chain->getOpcode() != ISD::TokenFactor)
9692     return Result; // Fail.
9693   else {
9694     bool isOk = false;
9695     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9696       if (Chain->getOperand(i).getNode() == LD) {
9697         isOk = true;
9698         break;
9699       }
9700     if (!isOk) return Result;
9701   }
9702
9703   // This only handles simple types.
9704   if (V.getValueType() != MVT::i16 &&
9705       V.getValueType() != MVT::i32 &&
9706       V.getValueType() != MVT::i64)
9707     return Result;
9708
9709   // Check the constant mask.  Invert it so that the bits being masked out are
9710   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
9711   // follow the sign bit for uniformity.
9712   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9713   unsigned NotMaskLZ = countLeadingZeros(NotMask);
9714   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
9715   unsigned NotMaskTZ = countTrailingZeros(NotMask);
9716   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
9717   if (NotMaskLZ == 64) return Result;  // All zero mask.
9718
9719   // See if we have a continuous run of bits.  If so, we have 0*1+0*
9720   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
9721     return Result;
9722
9723   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9724   if (V.getValueType() != MVT::i64 && NotMaskLZ)
9725     NotMaskLZ -= 64-V.getValueSizeInBits();
9726
9727   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9728   switch (MaskedBytes) {
9729   case 1:
9730   case 2:
9731   case 4: break;
9732   default: return Result; // All one mask, or 5-byte mask.
9733   }
9734
9735   // Verify that the first bit starts at a multiple of mask so that the access
9736   // is aligned the same as the access width.
9737   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9738
9739   Result.first = MaskedBytes;
9740   Result.second = NotMaskTZ/8;
9741   return Result;
9742 }
9743
9744
9745 /// Check to see if IVal is something that provides a value as specified by
9746 /// MaskInfo. If so, replace the specified store with a narrower store of
9747 /// truncated IVal.
9748 static SDNode *
9749 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9750                                 SDValue IVal, StoreSDNode *St,
9751                                 DAGCombiner *DC) {
9752   unsigned NumBytes = MaskInfo.first;
9753   unsigned ByteShift = MaskInfo.second;
9754   SelectionDAG &DAG = DC->getDAG();
9755
9756   // Check to see if IVal is all zeros in the part being masked in by the 'or'
9757   // that uses this.  If not, this is not a replacement.
9758   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9759                                   ByteShift*8, (ByteShift+NumBytes)*8);
9760   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9761
9762   // Check that it is legal on the target to do this.  It is legal if the new
9763   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9764   // legalization.
9765   MVT VT = MVT::getIntegerVT(NumBytes*8);
9766   if (!DC->isTypeLegal(VT))
9767     return nullptr;
9768
9769   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
9770   // shifted by ByteShift and truncated down to NumBytes.
9771   if (ByteShift)
9772     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9773                        DAG.getConstant(ByteShift*8,
9774                                     DC->getShiftAmountTy(IVal.getValueType())));
9775
9776   // Figure out the offset for the store and the alignment of the access.
9777   unsigned StOffset;
9778   unsigned NewAlign = St->getAlignment();
9779
9780   if (DAG.getTargetLoweringInfo().isLittleEndian())
9781     StOffset = ByteShift;
9782   else
9783     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9784
9785   SDValue Ptr = St->getBasePtr();
9786   if (StOffset) {
9787     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9788                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9789     NewAlign = MinAlign(NewAlign, StOffset);
9790   }
9791
9792   // Truncate down to the new size.
9793   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9794
9795   ++OpsNarrowed;
9796   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9797                       St->getPointerInfo().getWithOffset(StOffset),
9798                       false, false, NewAlign).getNode();
9799 }
9800
9801
9802 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9803 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9804 /// narrowing the load and store if it would end up being a win for performance
9805 /// or code size.
9806 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9807   StoreSDNode *ST  = cast<StoreSDNode>(N);
9808   if (ST->isVolatile())
9809     return SDValue();
9810
9811   SDValue Chain = ST->getChain();
9812   SDValue Value = ST->getValue();
9813   SDValue Ptr   = ST->getBasePtr();
9814   EVT VT = Value.getValueType();
9815
9816   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9817     return SDValue();
9818
9819   unsigned Opc = Value.getOpcode();
9820
9821   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9822   // is a byte mask indicating a consecutive number of bytes, check to see if
9823   // Y is known to provide just those bytes.  If so, we try to replace the
9824   // load + replace + store sequence with a single (narrower) store, which makes
9825   // the load dead.
9826   if (Opc == ISD::OR) {
9827     std::pair<unsigned, unsigned> MaskedLoad;
9828     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9829     if (MaskedLoad.first)
9830       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9831                                                   Value.getOperand(1), ST,this))
9832         return SDValue(NewST, 0);
9833
9834     // Or is commutative, so try swapping X and Y.
9835     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9836     if (MaskedLoad.first)
9837       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9838                                                   Value.getOperand(0), ST,this))
9839         return SDValue(NewST, 0);
9840   }
9841
9842   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9843       Value.getOperand(1).getOpcode() != ISD::Constant)
9844     return SDValue();
9845
9846   SDValue N0 = Value.getOperand(0);
9847   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9848       Chain == SDValue(N0.getNode(), 1)) {
9849     LoadSDNode *LD = cast<LoadSDNode>(N0);
9850     if (LD->getBasePtr() != Ptr ||
9851         LD->getPointerInfo().getAddrSpace() !=
9852         ST->getPointerInfo().getAddrSpace())
9853       return SDValue();
9854
9855     // Find the type to narrow it the load / op / store to.
9856     SDValue N1 = Value.getOperand(1);
9857     unsigned BitWidth = N1.getValueSizeInBits();
9858     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9859     if (Opc == ISD::AND)
9860       Imm ^= APInt::getAllOnesValue(BitWidth);
9861     if (Imm == 0 || Imm.isAllOnesValue())
9862       return SDValue();
9863     unsigned ShAmt = Imm.countTrailingZeros();
9864     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9865     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9866     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9867     // The narrowing should be profitable, the load/store operation should be
9868     // legal (or custom) and the store size should be equal to the NewVT width.
9869     while (NewBW < BitWidth &&
9870            (NewVT.getStoreSizeInBits() != NewBW ||
9871             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
9872             !TLI.isNarrowingProfitable(VT, NewVT))) {
9873       NewBW = NextPowerOf2(NewBW);
9874       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9875     }
9876     if (NewBW >= BitWidth)
9877       return SDValue();
9878
9879     // If the lsb changed does not start at the type bitwidth boundary,
9880     // start at the previous one.
9881     if (ShAmt % NewBW)
9882       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9883     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9884                                    std::min(BitWidth, ShAmt + NewBW));
9885     if ((Imm & Mask) == Imm) {
9886       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9887       if (Opc == ISD::AND)
9888         NewImm ^= APInt::getAllOnesValue(NewBW);
9889       uint64_t PtrOff = ShAmt / 8;
9890       // For big endian targets, we need to adjust the offset to the pointer to
9891       // load the correct bytes.
9892       if (TLI.isBigEndian())
9893         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9894
9895       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9896       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9897       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9898         return SDValue();
9899
9900       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9901                                    Ptr.getValueType(), Ptr,
9902                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9903       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9904                                   LD->getChain(), NewPtr,
9905                                   LD->getPointerInfo().getWithOffset(PtrOff),
9906                                   LD->isVolatile(), LD->isNonTemporal(),
9907                                   LD->isInvariant(), NewAlign,
9908                                   LD->getAAInfo());
9909       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9910                                    DAG.getConstant(NewImm, NewVT));
9911       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9912                                    NewVal, NewPtr,
9913                                    ST->getPointerInfo().getWithOffset(PtrOff),
9914                                    false, false, NewAlign);
9915
9916       AddToWorklist(NewPtr.getNode());
9917       AddToWorklist(NewLD.getNode());
9918       AddToWorklist(NewVal.getNode());
9919       WorklistRemover DeadNodes(*this);
9920       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9921       ++OpsNarrowed;
9922       return NewST;
9923     }
9924   }
9925
9926   return SDValue();
9927 }
9928
9929 /// For a given floating point load / store pair, if the load value isn't used
9930 /// by any other operations, then consider transforming the pair to integer
9931 /// load / store operations if the target deems the transformation profitable.
9932 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9933   StoreSDNode *ST  = cast<StoreSDNode>(N);
9934   SDValue Chain = ST->getChain();
9935   SDValue Value = ST->getValue();
9936   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9937       Value.hasOneUse() &&
9938       Chain == SDValue(Value.getNode(), 1)) {
9939     LoadSDNode *LD = cast<LoadSDNode>(Value);
9940     EVT VT = LD->getMemoryVT();
9941     if (!VT.isFloatingPoint() ||
9942         VT != ST->getMemoryVT() ||
9943         LD->isNonTemporal() ||
9944         ST->isNonTemporal() ||
9945         LD->getPointerInfo().getAddrSpace() != 0 ||
9946         ST->getPointerInfo().getAddrSpace() != 0)
9947       return SDValue();
9948
9949     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9950     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9951         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9952         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9953         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9954       return SDValue();
9955
9956     unsigned LDAlign = LD->getAlignment();
9957     unsigned STAlign = ST->getAlignment();
9958     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9959     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9960     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9961       return SDValue();
9962
9963     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9964                                 LD->getChain(), LD->getBasePtr(),
9965                                 LD->getPointerInfo(),
9966                                 false, false, false, LDAlign);
9967
9968     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9969                                  NewLD, ST->getBasePtr(),
9970                                  ST->getPointerInfo(),
9971                                  false, false, STAlign);
9972
9973     AddToWorklist(NewLD.getNode());
9974     AddToWorklist(NewST.getNode());
9975     WorklistRemover DeadNodes(*this);
9976     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9977     ++LdStFP2Int;
9978     return NewST;
9979   }
9980
9981   return SDValue();
9982 }
9983
9984 namespace {
9985 /// Helper struct to parse and store a memory address as base + index + offset.
9986 /// We ignore sign extensions when it is safe to do so.
9987 /// The following two expressions are not equivalent. To differentiate we need
9988 /// to store whether there was a sign extension involved in the index
9989 /// computation.
9990 ///  (load (i64 add (i64 copyfromreg %c)
9991 ///                 (i64 signextend (add (i8 load %index)
9992 ///                                      (i8 1))))
9993 /// vs
9994 ///
9995 /// (load (i64 add (i64 copyfromreg %c)
9996 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9997 ///                                         (i32 1)))))
9998 struct BaseIndexOffset {
9999   SDValue Base;
10000   SDValue Index;
10001   int64_t Offset;
10002   bool IsIndexSignExt;
10003
10004   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10005
10006   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10007                   bool IsIndexSignExt) :
10008     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10009
10010   bool equalBaseIndex(const BaseIndexOffset &Other) {
10011     return Other.Base == Base && Other.Index == Index &&
10012       Other.IsIndexSignExt == IsIndexSignExt;
10013   }
10014
10015   /// Parses tree in Ptr for base, index, offset addresses.
10016   static BaseIndexOffset match(SDValue Ptr) {
10017     bool IsIndexSignExt = false;
10018
10019     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10020     // instruction, then it could be just the BASE or everything else we don't
10021     // know how to handle. Just use Ptr as BASE and give up.
10022     if (Ptr->getOpcode() != ISD::ADD)
10023       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10024
10025     // We know that we have at least an ADD instruction. Try to pattern match
10026     // the simple case of BASE + OFFSET.
10027     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10028       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10029       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10030                               IsIndexSignExt);
10031     }
10032
10033     // Inside a loop the current BASE pointer is calculated using an ADD and a
10034     // MUL instruction. In this case Ptr is the actual BASE pointer.
10035     // (i64 add (i64 %array_ptr)
10036     //          (i64 mul (i64 %induction_var)
10037     //                   (i64 %element_size)))
10038     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10039       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10040
10041     // Look at Base + Index + Offset cases.
10042     SDValue Base = Ptr->getOperand(0);
10043     SDValue IndexOffset = Ptr->getOperand(1);
10044
10045     // Skip signextends.
10046     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10047       IndexOffset = IndexOffset->getOperand(0);
10048       IsIndexSignExt = true;
10049     }
10050
10051     // Either the case of Base + Index (no offset) or something else.
10052     if (IndexOffset->getOpcode() != ISD::ADD)
10053       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10054
10055     // Now we have the case of Base + Index + offset.
10056     SDValue Index = IndexOffset->getOperand(0);
10057     SDValue Offset = IndexOffset->getOperand(1);
10058
10059     if (!isa<ConstantSDNode>(Offset))
10060       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10061
10062     // Ignore signextends.
10063     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10064       Index = Index->getOperand(0);
10065       IsIndexSignExt = true;
10066     } else IsIndexSignExt = false;
10067
10068     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10069     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10070   }
10071 };
10072 } // namespace
10073
10074 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10075                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10076                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10077   // Make sure we have something to merge.
10078   if (NumElem < 2)
10079     return false;
10080
10081   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10082   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10083   unsigned EarliestNodeUsed = 0;
10084
10085   for (unsigned i=0; i < NumElem; ++i) {
10086     // Find a chain for the new wide-store operand. Notice that some
10087     // of the store nodes that we found may not be selected for inclusion
10088     // in the wide store. The chain we use needs to be the chain of the
10089     // earliest store node which is *used* and replaced by the wide store.
10090     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10091       EarliestNodeUsed = i;
10092   }
10093
10094   // The earliest Node in the DAG.
10095   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10096   SDLoc DL(StoreNodes[0].MemNode);
10097
10098   SDValue StoredVal;
10099   if (UseVector) {
10100     // Find a legal type for the vector store.
10101     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10102     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10103     if (IsConstantSrc) {
10104       // A vector store with a constant source implies that the constant is
10105       // zero; we only handle merging stores of constant zeros because the zero
10106       // can be materialized without a load.
10107       // It may be beneficial to loosen this restriction to allow non-zero
10108       // store merging.
10109       StoredVal = DAG.getConstant(0, Ty);
10110     } else {
10111       SmallVector<SDValue, 8> Ops;
10112       for (unsigned i = 0; i < NumElem ; ++i) {
10113         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10114         SDValue Val = St->getValue();
10115         // All of the operands of a BUILD_VECTOR must have the same type.
10116         if (Val.getValueType() != MemVT)
10117           return false;
10118         Ops.push_back(Val);
10119       }
10120
10121       // Build the extracted vector elements back into a vector.
10122       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10123     }
10124   } else {
10125     // We should always use a vector store when merging extracted vector
10126     // elements, so this path implies a store of constants.
10127     assert(IsConstantSrc && "Merged vector elements should use vector store");
10128
10129     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10130     APInt StoreInt(StoreBW, 0);
10131
10132     // Construct a single integer constant which is made of the smaller
10133     // constant inputs.
10134     bool IsLE = TLI.isLittleEndian();
10135     for (unsigned i = 0; i < NumElem ; ++i) {
10136       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10137       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10138       SDValue Val = St->getValue();
10139       StoreInt <<= ElementSizeBytes*8;
10140       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10141         StoreInt |= C->getAPIntValue().zext(StoreBW);
10142       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10143         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10144       } else {
10145         llvm_unreachable("Invalid constant element type");
10146       }
10147     }
10148
10149     // Create the new Load and Store operations.
10150     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10151     StoredVal = DAG.getConstant(StoreInt, StoreTy);
10152   }
10153
10154   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
10155                                   FirstInChain->getBasePtr(),
10156                                   FirstInChain->getPointerInfo(),
10157                                   false, false,
10158                                   FirstInChain->getAlignment());
10159
10160   // Replace the first store with the new store
10161   CombineTo(EarliestOp, NewStore);
10162   // Erase all other stores.
10163   for (unsigned i = 0; i < NumElem ; ++i) {
10164     if (StoreNodes[i].MemNode == EarliestOp)
10165       continue;
10166     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10167     // ReplaceAllUsesWith will replace all uses that existed when it was
10168     // called, but graph optimizations may cause new ones to appear. For
10169     // example, the case in pr14333 looks like
10170     //
10171     //  St's chain -> St -> another store -> X
10172     //
10173     // And the only difference from St to the other store is the chain.
10174     // When we change it's chain to be St's chain they become identical,
10175     // get CSEed and the net result is that X is now a use of St.
10176     // Since we know that St is redundant, just iterate.
10177     while (!St->use_empty())
10178       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10179     deleteAndRecombine(St);
10180   }
10181
10182   return true;
10183 }
10184
10185 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10186   if (OptLevel == CodeGenOpt::None)
10187     return false;
10188
10189   EVT MemVT = St->getMemoryVT();
10190   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10191   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10192       Attribute::NoImplicitFloat);
10193
10194   // Don't merge vectors into wider inputs.
10195   if (MemVT.isVector() || !MemVT.isSimple())
10196     return false;
10197
10198   // Perform an early exit check. Do not bother looking at stored values that
10199   // are not constants, loads, or extracted vector elements.
10200   SDValue StoredVal = St->getValue();
10201   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10202   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10203                        isa<ConstantFPSDNode>(StoredVal);
10204   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10205
10206   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10207     return false;
10208
10209   // Only look at ends of store sequences.
10210   SDValue Chain = SDValue(St, 0);
10211   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10212     return false;
10213
10214   // This holds the base pointer, index, and the offset in bytes from the base
10215   // pointer.
10216   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10217
10218   // We must have a base and an offset.
10219   if (!BasePtr.Base.getNode())
10220     return false;
10221
10222   // Do not handle stores to undef base pointers.
10223   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10224     return false;
10225
10226   // Save the LoadSDNodes that we find in the chain.
10227   // We need to make sure that these nodes do not interfere with
10228   // any of the store nodes.
10229   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10230
10231   // Save the StoreSDNodes that we find in the chain.
10232   SmallVector<MemOpLink, 8> StoreNodes;
10233
10234   // Walk up the chain and look for nodes with offsets from the same
10235   // base pointer. Stop when reaching an instruction with a different kind
10236   // or instruction which has a different base pointer.
10237   unsigned Seq = 0;
10238   StoreSDNode *Index = St;
10239   while (Index) {
10240     // If the chain has more than one use, then we can't reorder the mem ops.
10241     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10242       break;
10243
10244     // Find the base pointer and offset for this memory node.
10245     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10246
10247     // Check that the base pointer is the same as the original one.
10248     if (!Ptr.equalBaseIndex(BasePtr))
10249       break;
10250
10251     // Check that the alignment is the same.
10252     if (Index->getAlignment() != St->getAlignment())
10253       break;
10254
10255     // The memory operands must not be volatile.
10256     if (Index->isVolatile() || Index->isIndexed())
10257       break;
10258
10259     // No truncation.
10260     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10261       if (St->isTruncatingStore())
10262         break;
10263
10264     // The stored memory type must be the same.
10265     if (Index->getMemoryVT() != MemVT)
10266       break;
10267
10268     // We do not allow unaligned stores because we want to prevent overriding
10269     // stores.
10270     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10271       break;
10272
10273     // We found a potential memory operand to merge.
10274     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10275
10276     // Find the next memory operand in the chain. If the next operand in the
10277     // chain is a store then move up and continue the scan with the next
10278     // memory operand. If the next operand is a load save it and use alias
10279     // information to check if it interferes with anything.
10280     SDNode *NextInChain = Index->getChain().getNode();
10281     while (1) {
10282       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10283         // We found a store node. Use it for the next iteration.
10284         Index = STn;
10285         break;
10286       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10287         if (Ldn->isVolatile()) {
10288           Index = nullptr;
10289           break;
10290         }
10291
10292         // Save the load node for later. Continue the scan.
10293         AliasLoadNodes.push_back(Ldn);
10294         NextInChain = Ldn->getChain().getNode();
10295         continue;
10296       } else {
10297         Index = nullptr;
10298         break;
10299       }
10300     }
10301   }
10302
10303   // Check if there is anything to merge.
10304   if (StoreNodes.size() < 2)
10305     return false;
10306
10307   // Sort the memory operands according to their distance from the base pointer.
10308   std::sort(StoreNodes.begin(), StoreNodes.end(),
10309             [](MemOpLink LHS, MemOpLink RHS) {
10310     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10311            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10312             LHS.SequenceNum > RHS.SequenceNum);
10313   });
10314
10315   // Scan the memory operations on the chain and find the first non-consecutive
10316   // store memory address.
10317   unsigned LastConsecutiveStore = 0;
10318   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10319   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10320
10321     // Check that the addresses are consecutive starting from the second
10322     // element in the list of stores.
10323     if (i > 0) {
10324       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10325       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10326         break;
10327     }
10328
10329     bool Alias = false;
10330     // Check if this store interferes with any of the loads that we found.
10331     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10332       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10333         Alias = true;
10334         break;
10335       }
10336     // We found a load that alias with this store. Stop the sequence.
10337     if (Alias)
10338       break;
10339
10340     // Mark this node as useful.
10341     LastConsecutiveStore = i;
10342   }
10343
10344   // The node with the lowest store address.
10345   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10346
10347   // Store the constants into memory as one consecutive store.
10348   if (IsConstantSrc) {
10349     unsigned LastLegalType = 0;
10350     unsigned LastLegalVectorType = 0;
10351     bool NonZero = false;
10352     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10353       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10354       SDValue StoredVal = St->getValue();
10355
10356       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10357         NonZero |= !C->isNullValue();
10358       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10359         NonZero |= !C->getConstantFPValue()->isNullValue();
10360       } else {
10361         // Non-constant.
10362         break;
10363       }
10364
10365       // Find a legal type for the constant store.
10366       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10367       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10368       if (TLI.isTypeLegal(StoreTy))
10369         LastLegalType = i+1;
10370       // Or check whether a truncstore is legal.
10371       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10372                TargetLowering::TypePromoteInteger) {
10373         EVT LegalizedStoredValueTy =
10374           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10375         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10376           LastLegalType = i+1;
10377       }
10378
10379       // Find a legal type for the vector store.
10380       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10381       if (TLI.isTypeLegal(Ty))
10382         LastLegalVectorType = i + 1;
10383     }
10384
10385     // We only use vectors if the constant is known to be zero and the
10386     // function is not marked with the noimplicitfloat attribute.
10387     if (NonZero || NoVectors)
10388       LastLegalVectorType = 0;
10389
10390     // Check if we found a legal integer type to store.
10391     if (LastLegalType == 0 && LastLegalVectorType == 0)
10392       return false;
10393
10394     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10395     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10396
10397     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10398                                            true, UseVector);
10399   }
10400
10401   // When extracting multiple vector elements, try to store them
10402   // in one vector store rather than a sequence of scalar stores.
10403   if (IsExtractVecEltSrc) {
10404     unsigned NumElem = 0;
10405     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10406       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10407       SDValue StoredVal = St->getValue();
10408       // This restriction could be loosened.
10409       // Bail out if any stored values are not elements extracted from a vector.
10410       // It should be possible to handle mixed sources, but load sources need
10411       // more careful handling (see the block of code below that handles
10412       // consecutive loads).
10413       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10414         return false;
10415
10416       // Find a legal type for the vector store.
10417       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10418       if (TLI.isTypeLegal(Ty))
10419         NumElem = i + 1;
10420     }
10421
10422     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10423                                            false, true);
10424   }
10425
10426   // Below we handle the case of multiple consecutive stores that
10427   // come from multiple consecutive loads. We merge them into a single
10428   // wide load and a single wide store.
10429
10430   // Look for load nodes which are used by the stored values.
10431   SmallVector<MemOpLink, 8> LoadNodes;
10432
10433   // Find acceptable loads. Loads need to have the same chain (token factor),
10434   // must not be zext, volatile, indexed, and they must be consecutive.
10435   BaseIndexOffset LdBasePtr;
10436   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10437     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10438     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10439     if (!Ld) break;
10440
10441     // Loads must only have one use.
10442     if (!Ld->hasNUsesOfValue(1, 0))
10443       break;
10444
10445     // Check that the alignment is the same as the stores.
10446     if (Ld->getAlignment() != St->getAlignment())
10447       break;
10448
10449     // The memory operands must not be volatile.
10450     if (Ld->isVolatile() || Ld->isIndexed())
10451       break;
10452
10453     // We do not accept ext loads.
10454     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10455       break;
10456
10457     // The stored memory type must be the same.
10458     if (Ld->getMemoryVT() != MemVT)
10459       break;
10460
10461     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10462     // If this is not the first ptr that we check.
10463     if (LdBasePtr.Base.getNode()) {
10464       // The base ptr must be the same.
10465       if (!LdPtr.equalBaseIndex(LdBasePtr))
10466         break;
10467     } else {
10468       // Check that all other base pointers are the same as this one.
10469       LdBasePtr = LdPtr;
10470     }
10471
10472     // We found a potential memory operand to merge.
10473     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10474   }
10475
10476   if (LoadNodes.size() < 2)
10477     return false;
10478
10479   // If we have load/store pair instructions and we only have two values,
10480   // don't bother.
10481   unsigned RequiredAlignment;
10482   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10483       St->getAlignment() >= RequiredAlignment)
10484     return false;
10485
10486   // Scan the memory operations on the chain and find the first non-consecutive
10487   // load memory address. These variables hold the index in the store node
10488   // array.
10489   unsigned LastConsecutiveLoad = 0;
10490   // This variable refers to the size and not index in the array.
10491   unsigned LastLegalVectorType = 0;
10492   unsigned LastLegalIntegerType = 0;
10493   StartAddress = LoadNodes[0].OffsetFromBase;
10494   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10495   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10496     // All loads much share the same chain.
10497     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10498       break;
10499
10500     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10501     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10502       break;
10503     LastConsecutiveLoad = i;
10504
10505     // Find a legal type for the vector store.
10506     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10507     if (TLI.isTypeLegal(StoreTy))
10508       LastLegalVectorType = i + 1;
10509
10510     // Find a legal type for the integer store.
10511     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10512     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10513     if (TLI.isTypeLegal(StoreTy))
10514       LastLegalIntegerType = i + 1;
10515     // Or check whether a truncstore and extload is legal.
10516     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10517              TargetLowering::TypePromoteInteger) {
10518       EVT LegalizedStoredValueTy =
10519         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10520       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10521           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10522           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10523           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10524         LastLegalIntegerType = i+1;
10525     }
10526   }
10527
10528   // Only use vector types if the vector type is larger than the integer type.
10529   // If they are the same, use integers.
10530   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10531   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10532
10533   // We add +1 here because the LastXXX variables refer to location while
10534   // the NumElem refers to array/index size.
10535   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10536   NumElem = std::min(LastLegalType, NumElem);
10537
10538   if (NumElem < 2)
10539     return false;
10540
10541   // The earliest Node in the DAG.
10542   unsigned EarliestNodeUsed = 0;
10543   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10544   for (unsigned i=1; i<NumElem; ++i) {
10545     // Find a chain for the new wide-store operand. Notice that some
10546     // of the store nodes that we found may not be selected for inclusion
10547     // in the wide store. The chain we use needs to be the chain of the
10548     // earliest store node which is *used* and replaced by the wide store.
10549     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10550       EarliestNodeUsed = i;
10551   }
10552
10553   // Find if it is better to use vectors or integers to load and store
10554   // to memory.
10555   EVT JointMemOpVT;
10556   if (UseVectorTy) {
10557     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10558   } else {
10559     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10560     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10561   }
10562
10563   SDLoc LoadDL(LoadNodes[0].MemNode);
10564   SDLoc StoreDL(StoreNodes[0].MemNode);
10565
10566   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10567   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10568                                 FirstLoad->getChain(),
10569                                 FirstLoad->getBasePtr(),
10570                                 FirstLoad->getPointerInfo(),
10571                                 false, false, false,
10572                                 FirstLoad->getAlignment());
10573
10574   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10575                                   FirstInChain->getBasePtr(),
10576                                   FirstInChain->getPointerInfo(), false, false,
10577                                   FirstInChain->getAlignment());
10578
10579   // Replace one of the loads with the new load.
10580   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10581   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10582                                 SDValue(NewLoad.getNode(), 1));
10583
10584   // Remove the rest of the load chains.
10585   for (unsigned i = 1; i < NumElem ; ++i) {
10586     // Replace all chain users of the old load nodes with the chain of the new
10587     // load node.
10588     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10589     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10590   }
10591
10592   // Replace the first store with the new store.
10593   CombineTo(EarliestOp, NewStore);
10594   // Erase all other stores.
10595   for (unsigned i = 0; i < NumElem ; ++i) {
10596     // Remove all Store nodes.
10597     if (StoreNodes[i].MemNode == EarliestOp)
10598       continue;
10599     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10600     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10601     deleteAndRecombine(St);
10602   }
10603
10604   return true;
10605 }
10606
10607 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10608   StoreSDNode *ST  = cast<StoreSDNode>(N);
10609   SDValue Chain = ST->getChain();
10610   SDValue Value = ST->getValue();
10611   SDValue Ptr   = ST->getBasePtr();
10612
10613   // If this is a store of a bit convert, store the input value if the
10614   // resultant store does not need a higher alignment than the original.
10615   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10616       ST->isUnindexed()) {
10617     unsigned OrigAlign = ST->getAlignment();
10618     EVT SVT = Value.getOperand(0).getValueType();
10619     unsigned Align = TLI.getDataLayout()->
10620       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10621     if (Align <= OrigAlign &&
10622         ((!LegalOperations && !ST->isVolatile()) ||
10623          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10624       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10625                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
10626                           ST->isNonTemporal(), OrigAlign,
10627                           ST->getAAInfo());
10628   }
10629
10630   // Turn 'store undef, Ptr' -> nothing.
10631   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10632     return Chain;
10633
10634   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10635   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10636     // NOTE: If the original store is volatile, this transform must not increase
10637     // the number of stores.  For example, on x86-32 an f64 can be stored in one
10638     // processor operation but an i64 (which is not legal) requires two.  So the
10639     // transform should not be done in this case.
10640     if (Value.getOpcode() != ISD::TargetConstantFP) {
10641       SDValue Tmp;
10642       switch (CFP->getSimpleValueType(0).SimpleTy) {
10643       default: llvm_unreachable("Unknown FP type");
10644       case MVT::f16:    // We don't do this for these yet.
10645       case MVT::f80:
10646       case MVT::f128:
10647       case MVT::ppcf128:
10648         break;
10649       case MVT::f32:
10650         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10651             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10652           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10653                               bitcastToAPInt().getZExtValue(), MVT::i32);
10654           return DAG.getStore(Chain, SDLoc(N), Tmp,
10655                               Ptr, ST->getMemOperand());
10656         }
10657         break;
10658       case MVT::f64:
10659         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10660              !ST->isVolatile()) ||
10661             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10662           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10663                                 getZExtValue(), MVT::i64);
10664           return DAG.getStore(Chain, SDLoc(N), Tmp,
10665                               Ptr, ST->getMemOperand());
10666         }
10667
10668         if (!ST->isVolatile() &&
10669             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10670           // Many FP stores are not made apparent until after legalize, e.g. for
10671           // argument passing.  Since this is so common, custom legalize the
10672           // 64-bit integer store into two 32-bit stores.
10673           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10674           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10675           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10676           if (TLI.isBigEndian()) std::swap(Lo, Hi);
10677
10678           unsigned Alignment = ST->getAlignment();
10679           bool isVolatile = ST->isVolatile();
10680           bool isNonTemporal = ST->isNonTemporal();
10681           AAMDNodes AAInfo = ST->getAAInfo();
10682
10683           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10684                                      Ptr, ST->getPointerInfo(),
10685                                      isVolatile, isNonTemporal,
10686                                      ST->getAlignment(), AAInfo);
10687           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10688                             DAG.getConstant(4, Ptr.getValueType()));
10689           Alignment = MinAlign(Alignment, 4U);
10690           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10691                                      Ptr, ST->getPointerInfo().getWithOffset(4),
10692                                      isVolatile, isNonTemporal,
10693                                      Alignment, AAInfo);
10694           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10695                              St0, St1);
10696         }
10697
10698         break;
10699       }
10700     }
10701   }
10702
10703   // Try to infer better alignment information than the store already has.
10704   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10705     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10706       if (Align > ST->getAlignment()) {
10707         SDValue NewStore =
10708                DAG.getTruncStore(Chain, SDLoc(N), Value,
10709                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10710                                  ST->isVolatile(), ST->isNonTemporal(), Align,
10711                                  ST->getAAInfo());
10712         if (NewStore.getNode() != N)
10713           return CombineTo(ST, NewStore, true);
10714       }
10715     }
10716   }
10717
10718   // Try transforming a pair floating point load / store ops to integer
10719   // load / store ops.
10720   SDValue NewST = TransformFPLoadStorePair(N);
10721   if (NewST.getNode())
10722     return NewST;
10723
10724   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10725                                                   : DAG.getSubtarget().useAA();
10726 #ifndef NDEBUG
10727   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10728       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10729     UseAA = false;
10730 #endif
10731   if (UseAA && ST->isUnindexed()) {
10732     // Walk up chain skipping non-aliasing memory nodes.
10733     SDValue BetterChain = FindBetterChain(N, Chain);
10734
10735     // If there is a better chain.
10736     if (Chain != BetterChain) {
10737       SDValue ReplStore;
10738
10739       // Replace the chain to avoid dependency.
10740       if (ST->isTruncatingStore()) {
10741         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10742                                       ST->getMemoryVT(), ST->getMemOperand());
10743       } else {
10744         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10745                                  ST->getMemOperand());
10746       }
10747
10748       // Create token to keep both nodes around.
10749       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10750                                   MVT::Other, Chain, ReplStore);
10751
10752       // Make sure the new and old chains are cleaned up.
10753       AddToWorklist(Token.getNode());
10754
10755       // Don't add users to work list.
10756       return CombineTo(N, Token, false);
10757     }
10758   }
10759
10760   // Try transforming N to an indexed store.
10761   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10762     return SDValue(N, 0);
10763
10764   // FIXME: is there such a thing as a truncating indexed store?
10765   if (ST->isTruncatingStore() && ST->isUnindexed() &&
10766       Value.getValueType().isInteger()) {
10767     // See if we can simplify the input to this truncstore with knowledge that
10768     // only the low bits are being used.  For example:
10769     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
10770     SDValue Shorter =
10771       GetDemandedBits(Value,
10772                       APInt::getLowBitsSet(
10773                         Value.getValueType().getScalarType().getSizeInBits(),
10774                         ST->getMemoryVT().getScalarType().getSizeInBits()));
10775     AddToWorklist(Value.getNode());
10776     if (Shorter.getNode())
10777       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10778                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
10779
10780     // Otherwise, see if we can simplify the operation with
10781     // SimplifyDemandedBits, which only works if the value has a single use.
10782     if (SimplifyDemandedBits(Value,
10783                         APInt::getLowBitsSet(
10784                           Value.getValueType().getScalarType().getSizeInBits(),
10785                           ST->getMemoryVT().getScalarType().getSizeInBits())))
10786       return SDValue(N, 0);
10787   }
10788
10789   // If this is a load followed by a store to the same location, then the store
10790   // is dead/noop.
10791   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10792     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10793         ST->isUnindexed() && !ST->isVolatile() &&
10794         // There can't be any side effects between the load and store, such as
10795         // a call or store.
10796         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10797       // The store is dead, remove it.
10798       return Chain;
10799     }
10800   }
10801
10802   // If this is a store followed by a store with the same value to the same
10803   // location, then the store is dead/noop.
10804   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10805     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10806         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10807         ST1->isUnindexed() && !ST1->isVolatile()) {
10808       // The store is dead, remove it.
10809       return Chain;
10810     }
10811   }
10812
10813   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10814   // truncating store.  We can do this even if this is already a truncstore.
10815   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10816       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10817       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10818                             ST->getMemoryVT())) {
10819     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10820                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
10821   }
10822
10823   // Only perform this optimization before the types are legal, because we
10824   // don't want to perform this optimization on every DAGCombine invocation.
10825   if (!LegalTypes) {
10826     bool EverChanged = false;
10827
10828     do {
10829       // There can be multiple store sequences on the same chain.
10830       // Keep trying to merge store sequences until we are unable to do so
10831       // or until we merge the last store on the chain.
10832       bool Changed = MergeConsecutiveStores(ST);
10833       EverChanged |= Changed;
10834       if (!Changed) break;
10835     } while (ST->getOpcode() != ISD::DELETED_NODE);
10836
10837     if (EverChanged)
10838       return SDValue(N, 0);
10839   }
10840
10841   return ReduceLoadOpStoreWidth(N);
10842 }
10843
10844 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10845   SDValue InVec = N->getOperand(0);
10846   SDValue InVal = N->getOperand(1);
10847   SDValue EltNo = N->getOperand(2);
10848   SDLoc dl(N);
10849
10850   // If the inserted element is an UNDEF, just use the input vector.
10851   if (InVal.getOpcode() == ISD::UNDEF)
10852     return InVec;
10853
10854   EVT VT = InVec.getValueType();
10855
10856   // If we can't generate a legal BUILD_VECTOR, exit
10857   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10858     return SDValue();
10859
10860   // Check that we know which element is being inserted
10861   if (!isa<ConstantSDNode>(EltNo))
10862     return SDValue();
10863   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10864
10865   // Canonicalize insert_vector_elt dag nodes.
10866   // Example:
10867   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10868   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10869   //
10870   // Do this only if the child insert_vector node has one use; also
10871   // do this only if indices are both constants and Idx1 < Idx0.
10872   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10873       && isa<ConstantSDNode>(InVec.getOperand(2))) {
10874     unsigned OtherElt =
10875       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10876     if (Elt < OtherElt) {
10877       // Swap nodes.
10878       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10879                                   InVec.getOperand(0), InVal, EltNo);
10880       AddToWorklist(NewOp.getNode());
10881       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10882                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10883     }
10884   }
10885
10886   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10887   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
10888   // vector elements.
10889   SmallVector<SDValue, 8> Ops;
10890   // Do not combine these two vectors if the output vector will not replace
10891   // the input vector.
10892   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10893     Ops.append(InVec.getNode()->op_begin(),
10894                InVec.getNode()->op_end());
10895   } else if (InVec.getOpcode() == ISD::UNDEF) {
10896     unsigned NElts = VT.getVectorNumElements();
10897     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10898   } else {
10899     return SDValue();
10900   }
10901
10902   // Insert the element
10903   if (Elt < Ops.size()) {
10904     // All the operands of BUILD_VECTOR must have the same type;
10905     // we enforce that here.
10906     EVT OpVT = Ops[0].getValueType();
10907     if (InVal.getValueType() != OpVT)
10908       InVal = OpVT.bitsGT(InVal.getValueType()) ?
10909                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10910                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10911     Ops[Elt] = InVal;
10912   }
10913
10914   // Return the new vector
10915   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10916 }
10917
10918 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10919     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10920   EVT ResultVT = EVE->getValueType(0);
10921   EVT VecEltVT = InVecVT.getVectorElementType();
10922   unsigned Align = OriginalLoad->getAlignment();
10923   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10924       VecEltVT.getTypeForEVT(*DAG.getContext()));
10925
10926   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10927     return SDValue();
10928
10929   Align = NewAlign;
10930
10931   SDValue NewPtr = OriginalLoad->getBasePtr();
10932   SDValue Offset;
10933   EVT PtrType = NewPtr.getValueType();
10934   MachinePointerInfo MPI;
10935   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10936     int Elt = ConstEltNo->getZExtValue();
10937     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10938     if (TLI.isBigEndian())
10939       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10940     Offset = DAG.getConstant(PtrOff, PtrType);
10941     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10942   } else {
10943     Offset = DAG.getNode(
10944         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10945         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10946     if (TLI.isBigEndian())
10947       Offset = DAG.getNode(
10948           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10949           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10950     MPI = OriginalLoad->getPointerInfo();
10951   }
10952   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10953
10954   // The replacement we need to do here is a little tricky: we need to
10955   // replace an extractelement of a load with a load.
10956   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10957   // Note that this replacement assumes that the extractvalue is the only
10958   // use of the load; that's okay because we don't want to perform this
10959   // transformation in other cases anyway.
10960   SDValue Load;
10961   SDValue Chain;
10962   if (ResultVT.bitsGT(VecEltVT)) {
10963     // If the result type of vextract is wider than the load, then issue an
10964     // extending load instead.
10965     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10966                                                   VecEltVT)
10967                                    ? ISD::ZEXTLOAD
10968                                    : ISD::EXTLOAD;
10969     Load = DAG.getExtLoad(
10970         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10971         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10972         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10973     Chain = Load.getValue(1);
10974   } else {
10975     Load = DAG.getLoad(
10976         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10977         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10978         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10979     Chain = Load.getValue(1);
10980     if (ResultVT.bitsLT(VecEltVT))
10981       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10982     else
10983       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10984   }
10985   WorklistRemover DeadNodes(*this);
10986   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10987   SDValue To[] = { Load, Chain };
10988   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10989   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10990   // worklist explicitly as well.
10991   AddToWorklist(Load.getNode());
10992   AddUsersToWorklist(Load.getNode()); // Add users too
10993   // Make sure to revisit this node to clean it up; it will usually be dead.
10994   AddToWorklist(EVE);
10995   ++OpsNarrowed;
10996   return SDValue(EVE, 0);
10997 }
10998
10999 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11000   // (vextract (scalar_to_vector val, 0) -> val
11001   SDValue InVec = N->getOperand(0);
11002   EVT VT = InVec.getValueType();
11003   EVT NVT = N->getValueType(0);
11004
11005   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11006     // Check if the result type doesn't match the inserted element type. A
11007     // SCALAR_TO_VECTOR may truncate the inserted element and the
11008     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11009     SDValue InOp = InVec.getOperand(0);
11010     if (InOp.getValueType() != NVT) {
11011       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11012       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11013     }
11014     return InOp;
11015   }
11016
11017   SDValue EltNo = N->getOperand(1);
11018   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11019
11020   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11021   // We only perform this optimization before the op legalization phase because
11022   // we may introduce new vector instructions which are not backed by TD
11023   // patterns. For example on AVX, extracting elements from a wide vector
11024   // without using extract_subvector. However, if we can find an underlying
11025   // scalar value, then we can always use that.
11026   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11027       && ConstEltNo) {
11028     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11029     int NumElem = VT.getVectorNumElements();
11030     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11031     // Find the new index to extract from.
11032     int OrigElt = SVOp->getMaskElt(Elt);
11033
11034     // Extracting an undef index is undef.
11035     if (OrigElt == -1)
11036       return DAG.getUNDEF(NVT);
11037
11038     // Select the right vector half to extract from.
11039     SDValue SVInVec;
11040     if (OrigElt < NumElem) {
11041       SVInVec = InVec->getOperand(0);
11042     } else {
11043       SVInVec = InVec->getOperand(1);
11044       OrigElt -= NumElem;
11045     }
11046
11047     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11048       SDValue InOp = SVInVec.getOperand(OrigElt);
11049       if (InOp.getValueType() != NVT) {
11050         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11051         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11052       }
11053
11054       return InOp;
11055     }
11056
11057     // FIXME: We should handle recursing on other vector shuffles and
11058     // scalar_to_vector here as well.
11059
11060     if (!LegalOperations) {
11061       EVT IndexTy = TLI.getVectorIdxTy();
11062       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
11063                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
11064     }
11065   }
11066
11067   bool BCNumEltsChanged = false;
11068   EVT ExtVT = VT.getVectorElementType();
11069   EVT LVT = ExtVT;
11070
11071   // If the result of load has to be truncated, then it's not necessarily
11072   // profitable.
11073   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11074     return SDValue();
11075
11076   if (InVec.getOpcode() == ISD::BITCAST) {
11077     // Don't duplicate a load with other uses.
11078     if (!InVec.hasOneUse())
11079       return SDValue();
11080
11081     EVT BCVT = InVec.getOperand(0).getValueType();
11082     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11083       return SDValue();
11084     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11085       BCNumEltsChanged = true;
11086     InVec = InVec.getOperand(0);
11087     ExtVT = BCVT.getVectorElementType();
11088   }
11089
11090   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11091   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11092       ISD::isNormalLoad(InVec.getNode()) &&
11093       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11094     SDValue Index = N->getOperand(1);
11095     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11096       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11097                                                            OrigLoad);
11098   }
11099
11100   // Perform only after legalization to ensure build_vector / vector_shuffle
11101   // optimizations have already been done.
11102   if (!LegalOperations) return SDValue();
11103
11104   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11105   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11106   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11107
11108   if (ConstEltNo) {
11109     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11110
11111     LoadSDNode *LN0 = nullptr;
11112     const ShuffleVectorSDNode *SVN = nullptr;
11113     if (ISD::isNormalLoad(InVec.getNode())) {
11114       LN0 = cast<LoadSDNode>(InVec);
11115     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11116                InVec.getOperand(0).getValueType() == ExtVT &&
11117                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11118       // Don't duplicate a load with other uses.
11119       if (!InVec.hasOneUse())
11120         return SDValue();
11121
11122       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11123     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11124       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11125       // =>
11126       // (load $addr+1*size)
11127
11128       // Don't duplicate a load with other uses.
11129       if (!InVec.hasOneUse())
11130         return SDValue();
11131
11132       // If the bit convert changed the number of elements, it is unsafe
11133       // to examine the mask.
11134       if (BCNumEltsChanged)
11135         return SDValue();
11136
11137       // Select the input vector, guarding against out of range extract vector.
11138       unsigned NumElems = VT.getVectorNumElements();
11139       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11140       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11141
11142       if (InVec.getOpcode() == ISD::BITCAST) {
11143         // Don't duplicate a load with other uses.
11144         if (!InVec.hasOneUse())
11145           return SDValue();
11146
11147         InVec = InVec.getOperand(0);
11148       }
11149       if (ISD::isNormalLoad(InVec.getNode())) {
11150         LN0 = cast<LoadSDNode>(InVec);
11151         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11152         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
11153       }
11154     }
11155
11156     // Make sure we found a non-volatile load and the extractelement is
11157     // the only use.
11158     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11159       return SDValue();
11160
11161     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11162     if (Elt == -1)
11163       return DAG.getUNDEF(LVT);
11164
11165     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11166   }
11167
11168   return SDValue();
11169 }
11170
11171 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11172 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11173   // We perform this optimization post type-legalization because
11174   // the type-legalizer often scalarizes integer-promoted vectors.
11175   // Performing this optimization before may create bit-casts which
11176   // will be type-legalized to complex code sequences.
11177   // We perform this optimization only before the operation legalizer because we
11178   // may introduce illegal operations.
11179   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11180     return SDValue();
11181
11182   unsigned NumInScalars = N->getNumOperands();
11183   SDLoc dl(N);
11184   EVT VT = N->getValueType(0);
11185
11186   // Check to see if this is a BUILD_VECTOR of a bunch of values
11187   // which come from any_extend or zero_extend nodes. If so, we can create
11188   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11189   // optimizations. We do not handle sign-extend because we can't fill the sign
11190   // using shuffles.
11191   EVT SourceType = MVT::Other;
11192   bool AllAnyExt = true;
11193
11194   for (unsigned i = 0; i != NumInScalars; ++i) {
11195     SDValue In = N->getOperand(i);
11196     // Ignore undef inputs.
11197     if (In.getOpcode() == ISD::UNDEF) continue;
11198
11199     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11200     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11201
11202     // Abort if the element is not an extension.
11203     if (!ZeroExt && !AnyExt) {
11204       SourceType = MVT::Other;
11205       break;
11206     }
11207
11208     // The input is a ZeroExt or AnyExt. Check the original type.
11209     EVT InTy = In.getOperand(0).getValueType();
11210
11211     // Check that all of the widened source types are the same.
11212     if (SourceType == MVT::Other)
11213       // First time.
11214       SourceType = InTy;
11215     else if (InTy != SourceType) {
11216       // Multiple income types. Abort.
11217       SourceType = MVT::Other;
11218       break;
11219     }
11220
11221     // Check if all of the extends are ANY_EXTENDs.
11222     AllAnyExt &= AnyExt;
11223   }
11224
11225   // In order to have valid types, all of the inputs must be extended from the
11226   // same source type and all of the inputs must be any or zero extend.
11227   // Scalar sizes must be a power of two.
11228   EVT OutScalarTy = VT.getScalarType();
11229   bool ValidTypes = SourceType != MVT::Other &&
11230                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11231                  isPowerOf2_32(SourceType.getSizeInBits());
11232
11233   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11234   // turn into a single shuffle instruction.
11235   if (!ValidTypes)
11236     return SDValue();
11237
11238   bool isLE = TLI.isLittleEndian();
11239   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11240   assert(ElemRatio > 1 && "Invalid element size ratio");
11241   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11242                                DAG.getConstant(0, SourceType);
11243
11244   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11245   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11246
11247   // Populate the new build_vector
11248   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11249     SDValue Cast = N->getOperand(i);
11250     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11251             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11252             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11253     SDValue In;
11254     if (Cast.getOpcode() == ISD::UNDEF)
11255       In = DAG.getUNDEF(SourceType);
11256     else
11257       In = Cast->getOperand(0);
11258     unsigned Index = isLE ? (i * ElemRatio) :
11259                             (i * ElemRatio + (ElemRatio - 1));
11260
11261     assert(Index < Ops.size() && "Invalid index");
11262     Ops[Index] = In;
11263   }
11264
11265   // The type of the new BUILD_VECTOR node.
11266   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11267   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11268          "Invalid vector size");
11269   // Check if the new vector type is legal.
11270   if (!isTypeLegal(VecVT)) return SDValue();
11271
11272   // Make the new BUILD_VECTOR.
11273   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11274
11275   // The new BUILD_VECTOR node has the potential to be further optimized.
11276   AddToWorklist(BV.getNode());
11277   // Bitcast to the desired type.
11278   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11279 }
11280
11281 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11282   EVT VT = N->getValueType(0);
11283
11284   unsigned NumInScalars = N->getNumOperands();
11285   SDLoc dl(N);
11286
11287   EVT SrcVT = MVT::Other;
11288   unsigned Opcode = ISD::DELETED_NODE;
11289   unsigned NumDefs = 0;
11290
11291   for (unsigned i = 0; i != NumInScalars; ++i) {
11292     SDValue In = N->getOperand(i);
11293     unsigned Opc = In.getOpcode();
11294
11295     if (Opc == ISD::UNDEF)
11296       continue;
11297
11298     // If all scalar values are floats and converted from integers.
11299     if (Opcode == ISD::DELETED_NODE &&
11300         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11301       Opcode = Opc;
11302     }
11303
11304     if (Opc != Opcode)
11305       return SDValue();
11306
11307     EVT InVT = In.getOperand(0).getValueType();
11308
11309     // If all scalar values are typed differently, bail out. It's chosen to
11310     // simplify BUILD_VECTOR of integer types.
11311     if (SrcVT == MVT::Other)
11312       SrcVT = InVT;
11313     if (SrcVT != InVT)
11314       return SDValue();
11315     NumDefs++;
11316   }
11317
11318   // If the vector has just one element defined, it's not worth to fold it into
11319   // a vectorized one.
11320   if (NumDefs < 2)
11321     return SDValue();
11322
11323   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11324          && "Should only handle conversion from integer to float.");
11325   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11326
11327   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11328
11329   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11330     return SDValue();
11331
11332   // Just because the floating-point vector type is legal does not necessarily
11333   // mean that the corresponding integer vector type is.
11334   if (!isTypeLegal(NVT))
11335     return SDValue();
11336
11337   SmallVector<SDValue, 8> Opnds;
11338   for (unsigned i = 0; i != NumInScalars; ++i) {
11339     SDValue In = N->getOperand(i);
11340
11341     if (In.getOpcode() == ISD::UNDEF)
11342       Opnds.push_back(DAG.getUNDEF(SrcVT));
11343     else
11344       Opnds.push_back(In.getOperand(0));
11345   }
11346   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11347   AddToWorklist(BV.getNode());
11348
11349   return DAG.getNode(Opcode, dl, VT, BV);
11350 }
11351
11352 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11353   unsigned NumInScalars = N->getNumOperands();
11354   SDLoc dl(N);
11355   EVT VT = N->getValueType(0);
11356
11357   // A vector built entirely of undefs is undef.
11358   if (ISD::allOperandsUndef(N))
11359     return DAG.getUNDEF(VT);
11360
11361   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11362     return V;
11363
11364   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11365     return V;
11366
11367   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11368   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11369   // at most two distinct vectors, turn this into a shuffle node.
11370
11371   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11372   if (!isTypeLegal(VT))
11373     return SDValue();
11374
11375   // May only combine to shuffle after legalize if shuffle is legal.
11376   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11377     return SDValue();
11378
11379   SDValue VecIn1, VecIn2;
11380   bool UsesZeroVector = false;
11381   for (unsigned i = 0; i != NumInScalars; ++i) {
11382     SDValue Op = N->getOperand(i);
11383     // Ignore undef inputs.
11384     if (Op.getOpcode() == ISD::UNDEF) continue;
11385
11386     // See if we can combine this build_vector into a blend with a zero vector.
11387     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11388         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11389         (Op.getOpcode() == ISD::ConstantFP &&
11390         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11391       UsesZeroVector = true;
11392       continue;
11393     }
11394
11395     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11396     // constant index, bail out.
11397     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11398         !isa<ConstantSDNode>(Op.getOperand(1))) {
11399       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11400       break;
11401     }
11402
11403     // We allow up to two distinct input vectors.
11404     SDValue ExtractedFromVec = Op.getOperand(0);
11405     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11406       continue;
11407
11408     if (!VecIn1.getNode()) {
11409       VecIn1 = ExtractedFromVec;
11410     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11411       VecIn2 = ExtractedFromVec;
11412     } else {
11413       // Too many inputs.
11414       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11415       break;
11416     }
11417   }
11418
11419   // If everything is good, we can make a shuffle operation.
11420   if (VecIn1.getNode()) {
11421     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11422     SmallVector<int, 8> Mask;
11423     for (unsigned i = 0; i != NumInScalars; ++i) {
11424       unsigned Opcode = N->getOperand(i).getOpcode();
11425       if (Opcode == ISD::UNDEF) {
11426         Mask.push_back(-1);
11427         continue;
11428       }
11429
11430       // Operands can also be zero.
11431       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11432         assert(UsesZeroVector &&
11433                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11434                "Unexpected node found!");
11435         Mask.push_back(NumInScalars+i);
11436         continue;
11437       }
11438
11439       // If extracting from the first vector, just use the index directly.
11440       SDValue Extract = N->getOperand(i);
11441       SDValue ExtVal = Extract.getOperand(1);
11442       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11443       if (Extract.getOperand(0) == VecIn1) {
11444         Mask.push_back(ExtIndex);
11445         continue;
11446       }
11447
11448       // Otherwise, use InIdx + InputVecSize
11449       Mask.push_back(InNumElements + ExtIndex);
11450     }
11451
11452     // Avoid introducing illegal shuffles with zero.
11453     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11454       return SDValue();
11455
11456     // We can't generate a shuffle node with mismatched input and output types.
11457     // Attempt to transform a single input vector to the correct type.
11458     if ((VT != VecIn1.getValueType())) {
11459       // If the input vector type has a different base type to the output
11460       // vector type, bail out.
11461       EVT VTElemType = VT.getVectorElementType();
11462       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11463           (VecIn2.getNode() &&
11464            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11465         return SDValue();
11466
11467       // If the input vector is too small, widen it.
11468       // We only support widening of vectors which are half the size of the
11469       // output registers. For example XMM->YMM widening on X86 with AVX.
11470       EVT VecInT = VecIn1.getValueType();
11471       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11472         // If we only have one small input, widen it by adding undef values.
11473         if (!VecIn2.getNode())
11474           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11475                                DAG.getUNDEF(VecIn1.getValueType()));
11476         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11477           // If we have two small inputs of the same type, try to concat them.
11478           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11479           VecIn2 = SDValue(nullptr, 0);
11480         } else
11481           return SDValue();
11482       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11483         // If the input vector is too large, try to split it.
11484         // We don't support having two input vectors that are too large.
11485         // If the zero vector was used, we can not split the vector,
11486         // since we'd need 3 inputs.
11487         if (UsesZeroVector || VecIn2.getNode())
11488           return SDValue();
11489
11490         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11491           return SDValue();
11492
11493         // Try to replace VecIn1 with two extract_subvectors
11494         // No need to update the masks, they should still be correct.
11495         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11496           DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11497         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11498           DAG.getConstant(0, TLI.getVectorIdxTy()));
11499       } else
11500         return SDValue();
11501     }
11502
11503     if (UsesZeroVector)
11504       VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11505                                 DAG.getConstantFP(0.0, VT);
11506     else
11507       // If VecIn2 is unused then change it to undef.
11508       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11509
11510     // Check that we were able to transform all incoming values to the same
11511     // type.
11512     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11513         VecIn1.getValueType() != VT)
11514           return SDValue();
11515
11516     // Return the new VECTOR_SHUFFLE node.
11517     SDValue Ops[2];
11518     Ops[0] = VecIn1;
11519     Ops[1] = VecIn2;
11520     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11521   }
11522
11523   return SDValue();
11524 }
11525
11526 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11527   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11528   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
11529   // inputs come from at most two distinct vectors, turn this into a shuffle
11530   // node.
11531
11532   // If we only have one input vector, we don't need to do any concatenation.
11533   if (N->getNumOperands() == 1)
11534     return N->getOperand(0);
11535
11536   // Check if all of the operands are undefs.
11537   EVT VT = N->getValueType(0);
11538   if (ISD::allOperandsUndef(N))
11539     return DAG.getUNDEF(VT);
11540
11541   // Optimize concat_vectors where one of the vectors is undef.
11542   if (N->getNumOperands() == 2 &&
11543       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11544     SDValue In = N->getOperand(0);
11545     assert(In.getValueType().isVector() && "Must concat vectors");
11546
11547     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11548     if (In->getOpcode() == ISD::BITCAST &&
11549         !In->getOperand(0)->getValueType(0).isVector()) {
11550       SDValue Scalar = In->getOperand(0);
11551       EVT SclTy = Scalar->getValueType(0);
11552
11553       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11554         return SDValue();
11555
11556       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11557                                  VT.getSizeInBits() / SclTy.getSizeInBits());
11558       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11559         return SDValue();
11560
11561       SDLoc dl = SDLoc(N);
11562       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11563       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11564     }
11565   }
11566
11567   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
11568   // We have already tested above for an UNDEF only concatenation.
11569   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11570   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11571   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
11572     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
11573   };
11574   bool AllBuildVectorsOrUndefs =
11575       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
11576   if (AllBuildVectorsOrUndefs) {
11577     SmallVector<SDValue, 8> Opnds;
11578     EVT SVT = VT.getScalarType();
11579
11580     EVT MinVT = SVT;
11581     if (!SVT.isFloatingPoint()) {
11582       // If BUILD_VECTOR are from built from integer, they may have different
11583       // operand types. Get the smallest type and truncate all operands to it.
11584       bool FoundMinVT = false;
11585       for (const SDValue &Op : N->ops())
11586         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11587           EVT OpSVT = Op.getOperand(0)->getValueType(0);
11588           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
11589           FoundMinVT = true;
11590         }
11591       assert(FoundMinVT && "Concat vector type mismatch");
11592     }
11593
11594     for (const SDValue &Op : N->ops()) {
11595       EVT OpVT = Op.getValueType();
11596       unsigned NumElts = OpVT.getVectorNumElements();
11597
11598       if (ISD::UNDEF == Op.getOpcode())
11599         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
11600
11601       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11602         if (SVT.isFloatingPoint()) {
11603           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
11604           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
11605         } else {
11606           for (unsigned i = 0; i != NumElts; ++i)
11607             Opnds.push_back(
11608                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
11609         }
11610       }
11611     }
11612
11613     assert(VT.getVectorNumElements() == Opnds.size() &&
11614            "Concat vector type mismatch");
11615     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11616   }
11617
11618   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11619   // nodes often generate nop CONCAT_VECTOR nodes.
11620   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11621   // place the incoming vectors at the exact same location.
11622   SDValue SingleSource = SDValue();
11623   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11624
11625   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11626     SDValue Op = N->getOperand(i);
11627
11628     if (Op.getOpcode() == ISD::UNDEF)
11629       continue;
11630
11631     // Check if this is the identity extract:
11632     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11633       return SDValue();
11634
11635     // Find the single incoming vector for the extract_subvector.
11636     if (SingleSource.getNode()) {
11637       if (Op.getOperand(0) != SingleSource)
11638         return SDValue();
11639     } else {
11640       SingleSource = Op.getOperand(0);
11641
11642       // Check the source type is the same as the type of the result.
11643       // If not, this concat may extend the vector, so we can not
11644       // optimize it away.
11645       if (SingleSource.getValueType() != N->getValueType(0))
11646         return SDValue();
11647     }
11648
11649     unsigned IdentityIndex = i * PartNumElem;
11650     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11651     // The extract index must be constant.
11652     if (!CS)
11653       return SDValue();
11654
11655     // Check that we are reading from the identity index.
11656     if (CS->getZExtValue() != IdentityIndex)
11657       return SDValue();
11658   }
11659
11660   if (SingleSource.getNode())
11661     return SingleSource;
11662
11663   return SDValue();
11664 }
11665
11666 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11667   EVT NVT = N->getValueType(0);
11668   SDValue V = N->getOperand(0);
11669
11670   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11671     // Combine:
11672     //    (extract_subvec (concat V1, V2, ...), i)
11673     // Into:
11674     //    Vi if possible
11675     // Only operand 0 is checked as 'concat' assumes all inputs of the same
11676     // type.
11677     if (V->getOperand(0).getValueType() != NVT)
11678       return SDValue();
11679     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11680     unsigned NumElems = NVT.getVectorNumElements();
11681     assert((Idx % NumElems) == 0 &&
11682            "IDX in concat is not a multiple of the result vector length.");
11683     return V->getOperand(Idx / NumElems);
11684   }
11685
11686   // Skip bitcasting
11687   if (V->getOpcode() == ISD::BITCAST)
11688     V = V.getOperand(0);
11689
11690   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11691     SDLoc dl(N);
11692     // Handle only simple case where vector being inserted and vector
11693     // being extracted are of same type, and are half size of larger vectors.
11694     EVT BigVT = V->getOperand(0).getValueType();
11695     EVT SmallVT = V->getOperand(1).getValueType();
11696     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11697       return SDValue();
11698
11699     // Only handle cases where both indexes are constants with the same type.
11700     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11701     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11702
11703     if (InsIdx && ExtIdx &&
11704         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11705         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11706       // Combine:
11707       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11708       // Into:
11709       //    indices are equal or bit offsets are equal => V1
11710       //    otherwise => (extract_subvec V1, ExtIdx)
11711       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11712           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11713         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11714       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11715                          DAG.getNode(ISD::BITCAST, dl,
11716                                      N->getOperand(0).getValueType(),
11717                                      V->getOperand(0)), N->getOperand(1));
11718     }
11719   }
11720
11721   return SDValue();
11722 }
11723
11724 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11725                                                  SDValue V, SelectionDAG &DAG) {
11726   SDLoc DL(V);
11727   EVT VT = V.getValueType();
11728
11729   switch (V.getOpcode()) {
11730   default:
11731     return V;
11732
11733   case ISD::CONCAT_VECTORS: {
11734     EVT OpVT = V->getOperand(0).getValueType();
11735     int OpSize = OpVT.getVectorNumElements();
11736     SmallBitVector OpUsedElements(OpSize, false);
11737     bool FoundSimplification = false;
11738     SmallVector<SDValue, 4> NewOps;
11739     NewOps.reserve(V->getNumOperands());
11740     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11741       SDValue Op = V->getOperand(i);
11742       bool OpUsed = false;
11743       for (int j = 0; j < OpSize; ++j)
11744         if (UsedElements[i * OpSize + j]) {
11745           OpUsedElements[j] = true;
11746           OpUsed = true;
11747         }
11748       NewOps.push_back(
11749           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11750                  : DAG.getUNDEF(OpVT));
11751       FoundSimplification |= Op == NewOps.back();
11752       OpUsedElements.reset();
11753     }
11754     if (FoundSimplification)
11755       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11756     return V;
11757   }
11758
11759   case ISD::INSERT_SUBVECTOR: {
11760     SDValue BaseV = V->getOperand(0);
11761     SDValue SubV = V->getOperand(1);
11762     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11763     if (!IdxN)
11764       return V;
11765
11766     int SubSize = SubV.getValueType().getVectorNumElements();
11767     int Idx = IdxN->getZExtValue();
11768     bool SubVectorUsed = false;
11769     SmallBitVector SubUsedElements(SubSize, false);
11770     for (int i = 0; i < SubSize; ++i)
11771       if (UsedElements[i + Idx]) {
11772         SubVectorUsed = true;
11773         SubUsedElements[i] = true;
11774         UsedElements[i + Idx] = false;
11775       }
11776
11777     // Now recurse on both the base and sub vectors.
11778     SDValue SimplifiedSubV =
11779         SubVectorUsed
11780             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11781             : DAG.getUNDEF(SubV.getValueType());
11782     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11783     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11784       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11785                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11786     return V;
11787   }
11788   }
11789 }
11790
11791 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11792                                        SDValue N1, SelectionDAG &DAG) {
11793   EVT VT = SVN->getValueType(0);
11794   int NumElts = VT.getVectorNumElements();
11795   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11796   for (int M : SVN->getMask())
11797     if (M >= 0 && M < NumElts)
11798       N0UsedElements[M] = true;
11799     else if (M >= NumElts)
11800       N1UsedElements[M - NumElts] = true;
11801
11802   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11803   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11804   if (S0 == N0 && S1 == N1)
11805     return SDValue();
11806
11807   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11808 }
11809
11810 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
11811 // or turn a shuffle of a single concat into simpler shuffle then concat.
11812 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11813   EVT VT = N->getValueType(0);
11814   unsigned NumElts = VT.getVectorNumElements();
11815
11816   SDValue N0 = N->getOperand(0);
11817   SDValue N1 = N->getOperand(1);
11818   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11819
11820   SmallVector<SDValue, 4> Ops;
11821   EVT ConcatVT = N0.getOperand(0).getValueType();
11822   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11823   unsigned NumConcats = NumElts / NumElemsPerConcat;
11824
11825   // Special case: shuffle(concat(A,B)) can be more efficiently represented
11826   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
11827   // half vector elements.
11828   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
11829       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
11830                   SVN->getMask().end(), [](int i) { return i == -1; })) {
11831     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
11832                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
11833     N1 = DAG.getUNDEF(ConcatVT);
11834     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
11835   }
11836
11837   // Look at every vector that's inserted. We're looking for exact
11838   // subvector-sized copies from a concatenated vector
11839   for (unsigned I = 0; I != NumConcats; ++I) {
11840     // Make sure we're dealing with a copy.
11841     unsigned Begin = I * NumElemsPerConcat;
11842     bool AllUndef = true, NoUndef = true;
11843     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11844       if (SVN->getMaskElt(J) >= 0)
11845         AllUndef = false;
11846       else
11847         NoUndef = false;
11848     }
11849
11850     if (NoUndef) {
11851       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11852         return SDValue();
11853
11854       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11855         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11856           return SDValue();
11857
11858       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11859       if (FirstElt < N0.getNumOperands())
11860         Ops.push_back(N0.getOperand(FirstElt));
11861       else
11862         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11863
11864     } else if (AllUndef) {
11865       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11866     } else { // Mixed with general masks and undefs, can't do optimization.
11867       return SDValue();
11868     }
11869   }
11870
11871   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11872 }
11873
11874 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11875   EVT VT = N->getValueType(0);
11876   unsigned NumElts = VT.getVectorNumElements();
11877
11878   SDValue N0 = N->getOperand(0);
11879   SDValue N1 = N->getOperand(1);
11880
11881   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11882
11883   // Canonicalize shuffle undef, undef -> undef
11884   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11885     return DAG.getUNDEF(VT);
11886
11887   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11888
11889   // Canonicalize shuffle v, v -> v, undef
11890   if (N0 == N1) {
11891     SmallVector<int, 8> NewMask;
11892     for (unsigned i = 0; i != NumElts; ++i) {
11893       int Idx = SVN->getMaskElt(i);
11894       if (Idx >= (int)NumElts) Idx -= NumElts;
11895       NewMask.push_back(Idx);
11896     }
11897     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11898                                 &NewMask[0]);
11899   }
11900
11901   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
11902   if (N0.getOpcode() == ISD::UNDEF) {
11903     SmallVector<int, 8> NewMask;
11904     for (unsigned i = 0; i != NumElts; ++i) {
11905       int Idx = SVN->getMaskElt(i);
11906       if (Idx >= 0) {
11907         if (Idx >= (int)NumElts)
11908           Idx -= NumElts;
11909         else
11910           Idx = -1; // remove reference to lhs
11911       }
11912       NewMask.push_back(Idx);
11913     }
11914     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11915                                 &NewMask[0]);
11916   }
11917
11918   // Remove references to rhs if it is undef
11919   if (N1.getOpcode() == ISD::UNDEF) {
11920     bool Changed = false;
11921     SmallVector<int, 8> NewMask;
11922     for (unsigned i = 0; i != NumElts; ++i) {
11923       int Idx = SVN->getMaskElt(i);
11924       if (Idx >= (int)NumElts) {
11925         Idx = -1;
11926         Changed = true;
11927       }
11928       NewMask.push_back(Idx);
11929     }
11930     if (Changed)
11931       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11932   }
11933
11934   // If it is a splat, check if the argument vector is another splat or a
11935   // build_vector.
11936   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11937     SDNode *V = N0.getNode();
11938
11939     // If this is a bit convert that changes the element type of the vector but
11940     // not the number of vector elements, look through it.  Be careful not to
11941     // look though conversions that change things like v4f32 to v2f64.
11942     if (V->getOpcode() == ISD::BITCAST) {
11943       SDValue ConvInput = V->getOperand(0);
11944       if (ConvInput.getValueType().isVector() &&
11945           ConvInput.getValueType().getVectorNumElements() == NumElts)
11946         V = ConvInput.getNode();
11947     }
11948
11949     if (V->getOpcode() == ISD::BUILD_VECTOR) {
11950       assert(V->getNumOperands() == NumElts &&
11951              "BUILD_VECTOR has wrong number of operands");
11952       SDValue Base;
11953       bool AllSame = true;
11954       for (unsigned i = 0; i != NumElts; ++i) {
11955         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11956           Base = V->getOperand(i);
11957           break;
11958         }
11959       }
11960       // Splat of <u, u, u, u>, return <u, u, u, u>
11961       if (!Base.getNode())
11962         return N0;
11963       for (unsigned i = 0; i != NumElts; ++i) {
11964         if (V->getOperand(i) != Base) {
11965           AllSame = false;
11966           break;
11967         }
11968       }
11969       // Splat of <x, x, x, x>, return <x, x, x, x>
11970       if (AllSame)
11971         return N0;
11972
11973       // Canonicalize any other splat as a build_vector.
11974       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
11975       if (isa<ConstantSDNode>(Splatted) || isa<ConstantFPSDNode>(Splatted)) {
11976       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
11977       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
11978                                   V->getValueType(0), Ops);
11979
11980       // We may have jumped through bitcasts, so the type of the
11981       // BUILD_VECTOR may not match the type of the shuffle.
11982       if (V->getValueType(0) != VT)
11983         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
11984       return NewBV;
11985       }
11986     }
11987   }
11988
11989   // There are various patterns used to build up a vector from smaller vectors,
11990   // subvectors, or elements. Scan chains of these and replace unused insertions
11991   // or components with undef.
11992   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11993     return S;
11994
11995   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11996       Level < AfterLegalizeVectorOps &&
11997       (N1.getOpcode() == ISD::UNDEF ||
11998       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11999        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12000     SDValue V = partitionShuffleOfConcats(N, DAG);
12001
12002     if (V.getNode())
12003       return V;
12004   }
12005
12006   // If this shuffle only has a single input that is a bitcasted shuffle,
12007   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12008   // back to their original types.
12009   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12010       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12011       TLI.isTypeLegal(VT)) {
12012
12013     // Peek through the bitcast only if there is one user.
12014     SDValue BC0 = N0;
12015     while (BC0.getOpcode() == ISD::BITCAST) {
12016       if (!BC0.hasOneUse())
12017         break;
12018       BC0 = BC0.getOperand(0);
12019     }
12020
12021     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12022       if (Scale == 1)
12023         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12024
12025       SmallVector<int, 8> NewMask;
12026       for (int M : Mask)
12027         for (int s = 0; s != Scale; ++s)
12028           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12029       return NewMask;
12030     };
12031
12032     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12033       EVT SVT = VT.getScalarType();
12034       EVT InnerVT = BC0->getValueType(0);
12035       EVT InnerSVT = InnerVT.getScalarType();
12036
12037       // Determine which shuffle works with the smaller scalar type.
12038       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12039       EVT ScaleSVT = ScaleVT.getScalarType();
12040
12041       if (TLI.isTypeLegal(ScaleVT) &&
12042           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12043           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12044
12045         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12046         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12047
12048         // Scale the shuffle masks to the smaller scalar type.
12049         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12050         SmallVector<int, 8> InnerMask =
12051             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12052         SmallVector<int, 8> OuterMask =
12053             ScaleShuffleMask(SVN->getMask(), OuterScale);
12054
12055         // Merge the shuffle masks.
12056         SmallVector<int, 8> NewMask;
12057         for (int M : OuterMask)
12058           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12059
12060         // Test for shuffle mask legality over both commutations.
12061         SDValue SV0 = BC0->getOperand(0);
12062         SDValue SV1 = BC0->getOperand(1);
12063         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12064         if (!LegalMask) {
12065           std::swap(SV0, SV1);
12066           ShuffleVectorSDNode::commuteMask(NewMask);
12067           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12068         }
12069
12070         if (LegalMask) {
12071           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12072           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12073           return DAG.getNode(
12074               ISD::BITCAST, SDLoc(N), VT,
12075               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12076         }
12077       }
12078     }
12079   }
12080
12081   // Canonicalize shuffles according to rules:
12082   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12083   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12084   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12085   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12086       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12087       TLI.isTypeLegal(VT)) {
12088     // The incoming shuffle must be of the same type as the result of the
12089     // current shuffle.
12090     assert(N1->getOperand(0).getValueType() == VT &&
12091            "Shuffle types don't match");
12092
12093     SDValue SV0 = N1->getOperand(0);
12094     SDValue SV1 = N1->getOperand(1);
12095     bool HasSameOp0 = N0 == SV0;
12096     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12097     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12098       // Commute the operands of this shuffle so that next rule
12099       // will trigger.
12100       return DAG.getCommutedVectorShuffle(*SVN);
12101   }
12102
12103   // Try to fold according to rules:
12104   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12105   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12106   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12107   // Don't try to fold shuffles with illegal type.
12108   // Only fold if this shuffle is the only user of the other shuffle.
12109   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12110       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12111     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12112
12113     // The incoming shuffle must be of the same type as the result of the
12114     // current shuffle.
12115     assert(OtherSV->getOperand(0).getValueType() == VT &&
12116            "Shuffle types don't match");
12117
12118     SDValue SV0, SV1;
12119     SmallVector<int, 4> Mask;
12120     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12121     // operand, and SV1 as the second operand.
12122     for (unsigned i = 0; i != NumElts; ++i) {
12123       int Idx = SVN->getMaskElt(i);
12124       if (Idx < 0) {
12125         // Propagate Undef.
12126         Mask.push_back(Idx);
12127         continue;
12128       }
12129
12130       SDValue CurrentVec;
12131       if (Idx < (int)NumElts) {
12132         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12133         // shuffle mask to identify which vector is actually referenced.
12134         Idx = OtherSV->getMaskElt(Idx);
12135         if (Idx < 0) {
12136           // Propagate Undef.
12137           Mask.push_back(Idx);
12138           continue;
12139         }
12140
12141         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12142                                            : OtherSV->getOperand(1);
12143       } else {
12144         // This shuffle index references an element within N1.
12145         CurrentVec = N1;
12146       }
12147
12148       // Simple case where 'CurrentVec' is UNDEF.
12149       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12150         Mask.push_back(-1);
12151         continue;
12152       }
12153
12154       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12155       // will be the first or second operand of the combined shuffle.
12156       Idx = Idx % NumElts;
12157       if (!SV0.getNode() || SV0 == CurrentVec) {
12158         // Ok. CurrentVec is the left hand side.
12159         // Update the mask accordingly.
12160         SV0 = CurrentVec;
12161         Mask.push_back(Idx);
12162         continue;
12163       }
12164
12165       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12166       if (SV1.getNode() && SV1 != CurrentVec)
12167         return SDValue();
12168
12169       // Ok. CurrentVec is the right hand side.
12170       // Update the mask accordingly.
12171       SV1 = CurrentVec;
12172       Mask.push_back(Idx + NumElts);
12173     }
12174
12175     // Check if all indices in Mask are Undef. In case, propagate Undef.
12176     bool isUndefMask = true;
12177     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12178       isUndefMask &= Mask[i] < 0;
12179
12180     if (isUndefMask)
12181       return DAG.getUNDEF(VT);
12182
12183     if (!SV0.getNode())
12184       SV0 = DAG.getUNDEF(VT);
12185     if (!SV1.getNode())
12186       SV1 = DAG.getUNDEF(VT);
12187
12188     // Avoid introducing shuffles with illegal mask.
12189     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12190       ShuffleVectorSDNode::commuteMask(Mask);
12191
12192       if (!TLI.isShuffleMaskLegal(Mask, VT))
12193         return SDValue();
12194
12195       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12196       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12197       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12198       std::swap(SV0, SV1);
12199     }
12200
12201     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12202     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12203     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12204     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12205   }
12206
12207   return SDValue();
12208 }
12209
12210 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12211   SDValue InVal = N->getOperand(0);
12212   EVT VT = N->getValueType(0);
12213
12214   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12215   // with a VECTOR_SHUFFLE.
12216   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12217     SDValue InVec = InVal->getOperand(0);
12218     SDValue EltNo = InVal->getOperand(1);
12219
12220     // FIXME: We could support implicit truncation if the shuffle can be
12221     // scaled to a smaller vector scalar type.
12222     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12223     if (C0 && VT == InVec.getValueType() &&
12224         VT.getScalarType() == InVal.getValueType()) {
12225       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12226       int Elt = C0->getZExtValue();
12227       NewMask[0] = Elt;
12228
12229       if (TLI.isShuffleMaskLegal(NewMask, VT))
12230         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12231                                     NewMask);
12232     }
12233   }
12234
12235   return SDValue();
12236 }
12237
12238 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12239   SDValue N0 = N->getOperand(0);
12240   SDValue N2 = N->getOperand(2);
12241
12242   // If the input vector is a concatenation, and the insert replaces
12243   // one of the halves, we can optimize into a single concat_vectors.
12244   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12245       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12246     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12247     EVT VT = N->getValueType(0);
12248
12249     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12250     // (concat_vectors Z, Y)
12251     if (InsIdx == 0)
12252       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12253                          N->getOperand(1), N0.getOperand(1));
12254
12255     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12256     // (concat_vectors X, Z)
12257     if (InsIdx == VT.getVectorNumElements()/2)
12258       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12259                          N0.getOperand(0), N->getOperand(1));
12260   }
12261
12262   return SDValue();
12263 }
12264
12265 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12266 /// with the destination vector and a zero vector.
12267 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12268 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12269 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12270   EVT VT = N->getValueType(0);
12271   SDValue LHS = N->getOperand(0);
12272   SDValue RHS = N->getOperand(1);
12273   SDLoc dl(N);
12274
12275   // Make sure we're not running after operation legalization where it 
12276   // may have custom lowered the vector shuffles.
12277   if (LegalOperations)
12278     return SDValue();
12279
12280   if (N->getOpcode() != ISD::AND)
12281     return SDValue();
12282
12283   if (RHS.getOpcode() == ISD::BITCAST)
12284     RHS = RHS.getOperand(0);
12285
12286   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12287     SmallVector<int, 8> Indices;
12288     unsigned NumElts = RHS.getNumOperands();
12289
12290     for (unsigned i = 0; i != NumElts; ++i) {
12291       SDValue Elt = RHS.getOperand(i);
12292       if (!isa<ConstantSDNode>(Elt))
12293         return SDValue();
12294
12295       if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12296         Indices.push_back(i);
12297       else if (cast<ConstantSDNode>(Elt)->isNullValue())
12298         Indices.push_back(NumElts+i);
12299       else
12300         return SDValue();
12301     }
12302
12303     // Let's see if the target supports this vector_shuffle.
12304     EVT RVT = RHS.getValueType();
12305     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12306       return SDValue();
12307
12308     // Return the new VECTOR_SHUFFLE node.
12309     EVT EltVT = RVT.getVectorElementType();
12310     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12311                                    DAG.getConstant(0, EltVT));
12312     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
12313     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12314     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12315     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12316   }
12317
12318   return SDValue();
12319 }
12320
12321 /// Visit a binary vector operation, like ADD.
12322 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12323   assert(N->getValueType(0).isVector() &&
12324          "SimplifyVBinOp only works on vectors!");
12325
12326   SDValue LHS = N->getOperand(0);
12327   SDValue RHS = N->getOperand(1);
12328
12329   if (SDValue Shuffle = XformToShuffleWithZero(N))
12330     return Shuffle;
12331
12332   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12333   // this operation.
12334   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12335       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12336     // Check if both vectors are constants. If not bail out.
12337     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12338           cast<BuildVectorSDNode>(RHS)->isConstant()))
12339       return SDValue();
12340
12341     SmallVector<SDValue, 8> Ops;
12342     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12343       SDValue LHSOp = LHS.getOperand(i);
12344       SDValue RHSOp = RHS.getOperand(i);
12345
12346       // Can't fold divide by zero.
12347       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12348           N->getOpcode() == ISD::FDIV) {
12349         if ((RHSOp.getOpcode() == ISD::Constant &&
12350              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12351             (RHSOp.getOpcode() == ISD::ConstantFP &&
12352              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12353           break;
12354       }
12355
12356       EVT VT = LHSOp.getValueType();
12357       EVT RVT = RHSOp.getValueType();
12358       if (RVT != VT) {
12359         // Integer BUILD_VECTOR operands may have types larger than the element
12360         // size (e.g., when the element type is not legal).  Prior to type
12361         // legalization, the types may not match between the two BUILD_VECTORS.
12362         // Truncate one of the operands to make them match.
12363         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12364           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12365         } else {
12366           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12367           VT = RVT;
12368         }
12369       }
12370       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12371                                    LHSOp, RHSOp);
12372       if (FoldOp.getOpcode() != ISD::UNDEF &&
12373           FoldOp.getOpcode() != ISD::Constant &&
12374           FoldOp.getOpcode() != ISD::ConstantFP)
12375         break;
12376       Ops.push_back(FoldOp);
12377       AddToWorklist(FoldOp.getNode());
12378     }
12379
12380     if (Ops.size() == LHS.getNumOperands())
12381       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12382   }
12383
12384   // Type legalization might introduce new shuffles in the DAG.
12385   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12386   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
12387   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12388       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12389       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12390       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12391     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12392     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12393
12394     if (SVN0->getMask().equals(SVN1->getMask())) {
12395       EVT VT = N->getValueType(0);
12396       SDValue UndefVector = LHS.getOperand(1);
12397       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12398                                      LHS.getOperand(0), RHS.getOperand(0));
12399       AddUsersToWorklist(N);
12400       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12401                                   &SVN0->getMask()[0]);
12402     }
12403   }
12404
12405   return SDValue();
12406 }
12407
12408 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12409                                     SDValue N1, SDValue N2){
12410   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12411
12412   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12413                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
12414
12415   // If we got a simplified select_cc node back from SimplifySelectCC, then
12416   // break it down into a new SETCC node, and a new SELECT node, and then return
12417   // the SELECT node, since we were called with a SELECT node.
12418   if (SCC.getNode()) {
12419     // Check to see if we got a select_cc back (to turn into setcc/select).
12420     // Otherwise, just return whatever node we got back, like fabs.
12421     if (SCC.getOpcode() == ISD::SELECT_CC) {
12422       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12423                                   N0.getValueType(),
12424                                   SCC.getOperand(0), SCC.getOperand(1),
12425                                   SCC.getOperand(4));
12426       AddToWorklist(SETCC.getNode());
12427       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12428                            SCC.getOperand(2), SCC.getOperand(3));
12429     }
12430
12431     return SCC;
12432   }
12433   return SDValue();
12434 }
12435
12436 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12437 /// being selected between, see if we can simplify the select.  Callers of this
12438 /// should assume that TheSelect is deleted if this returns true.  As such, they
12439 /// should return the appropriate thing (e.g. the node) back to the top-level of
12440 /// the DAG combiner loop to avoid it being looked at.
12441 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12442                                     SDValue RHS) {
12443
12444   // Cannot simplify select with vector condition
12445   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12446
12447   // If this is a select from two identical things, try to pull the operation
12448   // through the select.
12449   if (LHS.getOpcode() != RHS.getOpcode() ||
12450       !LHS.hasOneUse() || !RHS.hasOneUse())
12451     return false;
12452
12453   // If this is a load and the token chain is identical, replace the select
12454   // of two loads with a load through a select of the address to load from.
12455   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12456   // constants have been dropped into the constant pool.
12457   if (LHS.getOpcode() == ISD::LOAD) {
12458     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12459     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12460
12461     // Token chains must be identical.
12462     if (LHS.getOperand(0) != RHS.getOperand(0) ||
12463         // Do not let this transformation reduce the number of volatile loads.
12464         LLD->isVolatile() || RLD->isVolatile() ||
12465         // If this is an EXTLOAD, the VT's must match.
12466         LLD->getMemoryVT() != RLD->getMemoryVT() ||
12467         // If this is an EXTLOAD, the kind of extension must match.
12468         (LLD->getExtensionType() != RLD->getExtensionType() &&
12469          // The only exception is if one of the extensions is anyext.
12470          LLD->getExtensionType() != ISD::EXTLOAD &&
12471          RLD->getExtensionType() != ISD::EXTLOAD) ||
12472         // FIXME: this discards src value information.  This is
12473         // over-conservative. It would be beneficial to be able to remember
12474         // both potential memory locations.  Since we are discarding
12475         // src value info, don't do the transformation if the memory
12476         // locations are not in the default address space.
12477         LLD->getPointerInfo().getAddrSpace() != 0 ||
12478         RLD->getPointerInfo().getAddrSpace() != 0 ||
12479         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12480                                       LLD->getBasePtr().getValueType()))
12481       return false;
12482
12483     // Check that the select condition doesn't reach either load.  If so,
12484     // folding this will induce a cycle into the DAG.  If not, this is safe to
12485     // xform, so create a select of the addresses.
12486     SDValue Addr;
12487     if (TheSelect->getOpcode() == ISD::SELECT) {
12488       SDNode *CondNode = TheSelect->getOperand(0).getNode();
12489       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12490           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12491         return false;
12492       // The loads must not depend on one another.
12493       if (LLD->isPredecessorOf(RLD) ||
12494           RLD->isPredecessorOf(LLD))
12495         return false;
12496       Addr = DAG.getSelect(SDLoc(TheSelect),
12497                            LLD->getBasePtr().getValueType(),
12498                            TheSelect->getOperand(0), LLD->getBasePtr(),
12499                            RLD->getBasePtr());
12500     } else {  // Otherwise SELECT_CC
12501       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12502       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12503
12504       if ((LLD->hasAnyUseOfValue(1) &&
12505            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
12506           (RLD->hasAnyUseOfValue(1) &&
12507            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
12508         return false;
12509
12510       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
12511                          LLD->getBasePtr().getValueType(),
12512                          TheSelect->getOperand(0),
12513                          TheSelect->getOperand(1),
12514                          LLD->getBasePtr(), RLD->getBasePtr(),
12515                          TheSelect->getOperand(4));
12516     }
12517
12518     SDValue Load;
12519     // It is safe to replace the two loads if they have different alignments,
12520     // but the new load must be the minimum (most restrictive) alignment of the
12521     // inputs.
12522     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
12523     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
12524     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
12525       Load = DAG.getLoad(TheSelect->getValueType(0),
12526                          SDLoc(TheSelect),
12527                          // FIXME: Discards pointer and AA info.
12528                          LLD->getChain(), Addr, MachinePointerInfo(),
12529                          LLD->isVolatile(), LLD->isNonTemporal(),
12530                          isInvariant, Alignment);
12531     } else {
12532       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12533                             RLD->getExtensionType() : LLD->getExtensionType(),
12534                             SDLoc(TheSelect),
12535                             TheSelect->getValueType(0),
12536                             // FIXME: Discards pointer and AA info.
12537                             LLD->getChain(), Addr, MachinePointerInfo(),
12538                             LLD->getMemoryVT(), LLD->isVolatile(),
12539                             LLD->isNonTemporal(), isInvariant, Alignment);
12540     }
12541
12542     // Users of the select now use the result of the load.
12543     CombineTo(TheSelect, Load);
12544
12545     // Users of the old loads now use the new load's chain.  We know the
12546     // old-load value is dead now.
12547     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12548     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12549     return true;
12550   }
12551
12552   return false;
12553 }
12554
12555 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
12556 /// where 'cond' is the comparison specified by CC.
12557 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
12558                                       SDValue N2, SDValue N3,
12559                                       ISD::CondCode CC, bool NotExtCompare) {
12560   // (x ? y : y) -> y.
12561   if (N2 == N3) return N2;
12562
12563   EVT VT = N2.getValueType();
12564   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12565   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12566   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
12567
12568   // Determine if the condition we're dealing with is constant
12569   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
12570                               N0, N1, CC, DL, false);
12571   if (SCC.getNode()) AddToWorklist(SCC.getNode());
12572   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
12573
12574   // fold select_cc true, x, y -> x
12575   if (SCCC && !SCCC->isNullValue())
12576     return N2;
12577   // fold select_cc false, x, y -> y
12578   if (SCCC && SCCC->isNullValue())
12579     return N3;
12580
12581   // Check to see if we can simplify the select into an fabs node
12582   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12583     // Allow either -0.0 or 0.0
12584     if (CFP->getValueAPF().isZero()) {
12585       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12586       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12587           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12588           N2 == N3.getOperand(0))
12589         return DAG.getNode(ISD::FABS, DL, VT, N0);
12590
12591       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12592       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12593           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12594           N2.getOperand(0) == N3)
12595         return DAG.getNode(ISD::FABS, DL, VT, N3);
12596     }
12597   }
12598
12599   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12600   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12601   // in it.  This is a win when the constant is not otherwise available because
12602   // it replaces two constant pool loads with one.  We only do this if the FP
12603   // type is known to be legal, because if it isn't, then we are before legalize
12604   // types an we want the other legalization to happen first (e.g. to avoid
12605   // messing with soft float) and if the ConstantFP is not legal, because if
12606   // it is legal, we may not need to store the FP constant in a constant pool.
12607   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12608     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12609       if (TLI.isTypeLegal(N2.getValueType()) &&
12610           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
12611                TargetLowering::Legal &&
12612            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12613            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
12614           // If both constants have multiple uses, then we won't need to do an
12615           // extra load, they are likely around in registers for other users.
12616           (TV->hasOneUse() || FV->hasOneUse())) {
12617         Constant *Elts[] = {
12618           const_cast<ConstantFP*>(FV->getConstantFPValue()),
12619           const_cast<ConstantFP*>(TV->getConstantFPValue())
12620         };
12621         Type *FPTy = Elts[0]->getType();
12622         const DataLayout &TD = *TLI.getDataLayout();
12623
12624         // Create a ConstantArray of the two constants.
12625         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
12626         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12627                                             TD.getPrefTypeAlignment(FPTy));
12628         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12629
12630         // Get the offsets to the 0 and 1 element of the array so that we can
12631         // select between them.
12632         SDValue Zero = DAG.getIntPtrConstant(0);
12633         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
12634         SDValue One = DAG.getIntPtrConstant(EltSize);
12635
12636         SDValue Cond = DAG.getSetCC(DL,
12637                                     getSetCCResultType(N0.getValueType()),
12638                                     N0, N1, CC);
12639         AddToWorklist(Cond.getNode());
12640         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12641                                           Cond, One, Zero);
12642         AddToWorklist(CstOffset.getNode());
12643         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
12644                             CstOffset);
12645         AddToWorklist(CPIdx.getNode());
12646         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
12647                            MachinePointerInfo::getConstantPool(), false,
12648                            false, false, Alignment);
12649
12650       }
12651     }
12652
12653   // Check to see if we can perform the "gzip trick", transforming
12654   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
12655   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
12656       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
12657        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
12658     EVT XType = N0.getValueType();
12659     EVT AType = N2.getValueType();
12660     if (XType.bitsGE(AType)) {
12661       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
12662       // single-bit constant.
12663       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12664         unsigned ShCtV = N2C->getAPIntValue().logBase2();
12665         ShCtV = XType.getSizeInBits()-ShCtV-1;
12666         SDValue ShCt = DAG.getConstant(ShCtV,
12667                                        getShiftAmountTy(N0.getValueType()));
12668         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
12669                                     XType, N0, ShCt);
12670         AddToWorklist(Shift.getNode());
12671
12672         if (XType.bitsGT(AType)) {
12673           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12674           AddToWorklist(Shift.getNode());
12675         }
12676
12677         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12678       }
12679
12680       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
12681                                   XType, N0,
12682                                   DAG.getConstant(XType.getSizeInBits()-1,
12683                                          getShiftAmountTy(N0.getValueType())));
12684       AddToWorklist(Shift.getNode());
12685
12686       if (XType.bitsGT(AType)) {
12687         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12688         AddToWorklist(Shift.getNode());
12689       }
12690
12691       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12692     }
12693   }
12694
12695   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12696   // where y is has a single bit set.
12697   // A plaintext description would be, we can turn the SELECT_CC into an AND
12698   // when the condition can be materialized as an all-ones register.  Any
12699   // single bit-test can be materialized as an all-ones register with
12700   // shift-left and shift-right-arith.
12701   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12702       N0->getValueType(0) == VT &&
12703       N1C && N1C->isNullValue() &&
12704       N2C && N2C->isNullValue()) {
12705     SDValue AndLHS = N0->getOperand(0);
12706     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12707     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12708       // Shift the tested bit over the sign bit.
12709       APInt AndMask = ConstAndRHS->getAPIntValue();
12710       SDValue ShlAmt =
12711         DAG.getConstant(AndMask.countLeadingZeros(),
12712                         getShiftAmountTy(AndLHS.getValueType()));
12713       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
12714
12715       // Now arithmetic right shift it all the way over, so the result is either
12716       // all-ones, or zero.
12717       SDValue ShrAmt =
12718         DAG.getConstant(AndMask.getBitWidth()-1,
12719                         getShiftAmountTy(Shl.getValueType()));
12720       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
12721
12722       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12723     }
12724   }
12725
12726   // fold select C, 16, 0 -> shl C, 4
12727   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
12728       TLI.getBooleanContents(N0.getValueType()) ==
12729           TargetLowering::ZeroOrOneBooleanContent) {
12730
12731     // If the caller doesn't want us to simplify this into a zext of a compare,
12732     // don't do it.
12733     if (NotExtCompare && N2C->getAPIntValue() == 1)
12734       return SDValue();
12735
12736     // Get a SetCC of the condition
12737     // NOTE: Don't create a SETCC if it's not legal on this target.
12738     if (!LegalOperations ||
12739         TLI.isOperationLegal(ISD::SETCC,
12740           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
12741       SDValue Temp, SCC;
12742       // cast from setcc result type to select result type
12743       if (LegalTypes) {
12744         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
12745                             N0, N1, CC);
12746         if (N2.getValueType().bitsLT(SCC.getValueType()))
12747           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
12748                                         N2.getValueType());
12749         else
12750           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12751                              N2.getValueType(), SCC);
12752       } else {
12753         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12754         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12755                            N2.getValueType(), SCC);
12756       }
12757
12758       AddToWorklist(SCC.getNode());
12759       AddToWorklist(Temp.getNode());
12760
12761       if (N2C->getAPIntValue() == 1)
12762         return Temp;
12763
12764       // shl setcc result by log2 n2c
12765       return DAG.getNode(
12766           ISD::SHL, DL, N2.getValueType(), Temp,
12767           DAG.getConstant(N2C->getAPIntValue().logBase2(),
12768                           getShiftAmountTy(Temp.getValueType())));
12769     }
12770   }
12771
12772   // Check to see if this is the equivalent of setcc
12773   // FIXME: Turn all of these into setcc if setcc if setcc is legal
12774   // otherwise, go ahead with the folds.
12775   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
12776     EVT XType = N0.getValueType();
12777     if (!LegalOperations ||
12778         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12779       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
12780       if (Res.getValueType() != VT)
12781         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
12782       return Res;
12783     }
12784
12785     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12786     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12787         (!LegalOperations ||
12788          TLI.isOperationLegal(ISD::CTLZ, XType))) {
12789       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12790       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12791                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
12792                                        getShiftAmountTy(Ctlz.getValueType())));
12793     }
12794     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12795     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12796       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12797                                   XType, DAG.getConstant(0, XType), N0);
12798       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12799       return DAG.getNode(ISD::SRL, DL, XType,
12800                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12801                          DAG.getConstant(XType.getSizeInBits()-1,
12802                                          getShiftAmountTy(XType)));
12803     }
12804     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12805     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12806       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12807                                  DAG.getConstant(XType.getSizeInBits()-1,
12808                                          getShiftAmountTy(N0.getValueType())));
12809       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12810     }
12811   }
12812
12813   // Check to see if this is an integer abs.
12814   // select_cc setg[te] X,  0,  X, -X ->
12815   // select_cc setgt    X, -1,  X, -X ->
12816   // select_cc setl[te] X,  0, -X,  X ->
12817   // select_cc setlt    X,  1, -X,  X ->
12818   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12819   if (N1C) {
12820     ConstantSDNode *SubC = nullptr;
12821     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12822          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12823         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12824       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12825     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12826               (N1C->isOne() && CC == ISD::SETLT)) &&
12827              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12828       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12829
12830     EVT XType = N0.getValueType();
12831     if (SubC && SubC->isNullValue() && XType.isInteger()) {
12832       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12833                                   N0,
12834                                   DAG.getConstant(XType.getSizeInBits()-1,
12835                                          getShiftAmountTy(N0.getValueType())));
12836       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12837                                 XType, N0, Shift);
12838       AddToWorklist(Shift.getNode());
12839       AddToWorklist(Add.getNode());
12840       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12841     }
12842   }
12843
12844   return SDValue();
12845 }
12846
12847 /// This is a stub for TargetLowering::SimplifySetCC.
12848 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12849                                    SDValue N1, ISD::CondCode Cond,
12850                                    SDLoc DL, bool foldBooleans) {
12851   TargetLowering::DAGCombinerInfo
12852     DagCombineInfo(DAG, Level, false, this);
12853   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12854 }
12855
12856 /// Given an ISD::SDIV node expressing a divide by constant, return
12857 /// a DAG expression to select that will generate the same value by multiplying
12858 /// by a magic number.
12859 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12860 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12861   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12862   if (!C)
12863     return SDValue();
12864
12865   // Avoid division by zero.
12866   if (!C->getAPIntValue())
12867     return SDValue();
12868
12869   std::vector<SDNode*> Built;
12870   SDValue S =
12871       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12872
12873   for (SDNode *N : Built)
12874     AddToWorklist(N);
12875   return S;
12876 }
12877
12878 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12879 /// DAG expression that will generate the same value by right shifting.
12880 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12881   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12882   if (!C)
12883     return SDValue();
12884
12885   // Avoid division by zero.
12886   if (!C->getAPIntValue())
12887     return SDValue();
12888
12889   std::vector<SDNode *> Built;
12890   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12891
12892   for (SDNode *N : Built)
12893     AddToWorklist(N);
12894   return S;
12895 }
12896
12897 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12898 /// expression that will generate the same value by multiplying by a magic
12899 /// number.
12900 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12901 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12902   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12903   if (!C)
12904     return SDValue();
12905
12906   // Avoid division by zero.
12907   if (!C->getAPIntValue())
12908     return SDValue();
12909
12910   std::vector<SDNode*> Built;
12911   SDValue S =
12912       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12913
12914   for (SDNode *N : Built)
12915     AddToWorklist(N);
12916   return S;
12917 }
12918
12919 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12920   if (Level >= AfterLegalizeDAG)
12921     return SDValue();
12922
12923   // Expose the DAG combiner to the target combiner implementations.
12924   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12925
12926   unsigned Iterations = 0;
12927   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12928     if (Iterations) {
12929       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12930       // For the reciprocal, we need to find the zero of the function:
12931       //   F(X) = A X - 1 [which has a zero at X = 1/A]
12932       //     =>
12933       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12934       //     does not require additional intermediate precision]
12935       EVT VT = Op.getValueType();
12936       SDLoc DL(Op);
12937       SDValue FPOne = DAG.getConstantFP(1.0, VT);
12938
12939       AddToWorklist(Est.getNode());
12940
12941       // Newton iterations: Est = Est + Est (1 - Arg * Est)
12942       for (unsigned i = 0; i < Iterations; ++i) {
12943         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12944         AddToWorklist(NewEst.getNode());
12945
12946         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12947         AddToWorklist(NewEst.getNode());
12948
12949         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12950         AddToWorklist(NewEst.getNode());
12951
12952         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12953         AddToWorklist(Est.getNode());
12954       }
12955     }
12956     return Est;
12957   }
12958
12959   return SDValue();
12960 }
12961
12962 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12963 /// For the reciprocal sqrt, we need to find the zero of the function:
12964 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12965 ///     =>
12966 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12967 /// As a result, we precompute A/2 prior to the iteration loop.
12968 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12969                                           unsigned Iterations) {
12970   EVT VT = Arg.getValueType();
12971   SDLoc DL(Arg);
12972   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12973
12974   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12975   // this entire sequence requires only one FP constant.
12976   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12977   AddToWorklist(HalfArg.getNode());
12978
12979   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12980   AddToWorklist(HalfArg.getNode());
12981
12982   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12983   for (unsigned i = 0; i < Iterations; ++i) {
12984     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12985     AddToWorklist(NewEst.getNode());
12986
12987     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12988     AddToWorklist(NewEst.getNode());
12989
12990     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12991     AddToWorklist(NewEst.getNode());
12992
12993     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12994     AddToWorklist(Est.getNode());
12995   }
12996   return Est;
12997 }
12998
12999 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13000 /// For the reciprocal sqrt, we need to find the zero of the function:
13001 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13002 ///     =>
13003 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13004 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13005                                           unsigned Iterations) {
13006   EVT VT = Arg.getValueType();
13007   SDLoc DL(Arg);
13008   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
13009   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
13010
13011   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13012   for (unsigned i = 0; i < Iterations; ++i) {
13013     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13014     AddToWorklist(HalfEst.getNode());
13015
13016     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13017     AddToWorklist(Est.getNode());
13018
13019     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13020     AddToWorklist(Est.getNode());
13021
13022     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13023     AddToWorklist(Est.getNode());
13024
13025     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13026     AddToWorklist(Est.getNode());
13027   }
13028   return Est;
13029 }
13030
13031 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13032   if (Level >= AfterLegalizeDAG)
13033     return SDValue();
13034
13035   // Expose the DAG combiner to the target combiner implementations.
13036   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13037   unsigned Iterations = 0;
13038   bool UseOneConstNR = false;
13039   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13040     AddToWorklist(Est.getNode());
13041     if (Iterations) {
13042       Est = UseOneConstNR ?
13043         BuildRsqrtNROneConst(Op, Est, Iterations) :
13044         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13045     }
13046     return Est;
13047   }
13048
13049   return SDValue();
13050 }
13051
13052 /// Return true if base is a frame index, which is known not to alias with
13053 /// anything but itself.  Provides base object and offset as results.
13054 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13055                            const GlobalValue *&GV, const void *&CV) {
13056   // Assume it is a primitive operation.
13057   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13058
13059   // If it's an adding a simple constant then integrate the offset.
13060   if (Base.getOpcode() == ISD::ADD) {
13061     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13062       Base = Base.getOperand(0);
13063       Offset += C->getZExtValue();
13064     }
13065   }
13066
13067   // Return the underlying GlobalValue, and update the Offset.  Return false
13068   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13069   // by multiple nodes with different offsets.
13070   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13071     GV = G->getGlobal();
13072     Offset += G->getOffset();
13073     return false;
13074   }
13075
13076   // Return the underlying Constant value, and update the Offset.  Return false
13077   // for ConstantSDNodes since the same constant pool entry may be represented
13078   // by multiple nodes with different offsets.
13079   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13080     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13081                                          : (const void *)C->getConstVal();
13082     Offset += C->getOffset();
13083     return false;
13084   }
13085   // If it's any of the following then it can't alias with anything but itself.
13086   return isa<FrameIndexSDNode>(Base);
13087 }
13088
13089 /// Return true if there is any possibility that the two addresses overlap.
13090 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13091   // If they are the same then they must be aliases.
13092   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13093
13094   // If they are both volatile then they cannot be reordered.
13095   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13096
13097   // Gather base node and offset information.
13098   SDValue Base1, Base2;
13099   int64_t Offset1, Offset2;
13100   const GlobalValue *GV1, *GV2;
13101   const void *CV1, *CV2;
13102   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13103                                       Base1, Offset1, GV1, CV1);
13104   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13105                                       Base2, Offset2, GV2, CV2);
13106
13107   // If they have a same base address then check to see if they overlap.
13108   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13109     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13110              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13111
13112   // It is possible for different frame indices to alias each other, mostly
13113   // when tail call optimization reuses return address slots for arguments.
13114   // To catch this case, look up the actual index of frame indices to compute
13115   // the real alias relationship.
13116   if (isFrameIndex1 && isFrameIndex2) {
13117     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13118     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13119     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13120     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13121              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13122   }
13123
13124   // Otherwise, if we know what the bases are, and they aren't identical, then
13125   // we know they cannot alias.
13126   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13127     return false;
13128
13129   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13130   // compared to the size and offset of the access, we may be able to prove they
13131   // do not alias.  This check is conservative for now to catch cases created by
13132   // splitting vector types.
13133   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13134       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13135       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13136        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13137       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13138     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13139     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13140
13141     // There is no overlap between these relatively aligned accesses of similar
13142     // size, return no alias.
13143     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13144         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13145       return false;
13146   }
13147
13148   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13149                    ? CombinerGlobalAA
13150                    : DAG.getSubtarget().useAA();
13151 #ifndef NDEBUG
13152   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13153       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13154     UseAA = false;
13155 #endif
13156   if (UseAA &&
13157       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13158     // Use alias analysis information.
13159     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13160                                  Op1->getSrcValueOffset());
13161     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13162         Op0->getSrcValueOffset() - MinOffset;
13163     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13164         Op1->getSrcValueOffset() - MinOffset;
13165     AliasAnalysis::AliasResult AAResult =
13166         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13167                                          Overlap1,
13168                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13169                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13170                                          Overlap2,
13171                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13172     if (AAResult == AliasAnalysis::NoAlias)
13173       return false;
13174   }
13175
13176   // Otherwise we have to assume they alias.
13177   return true;
13178 }
13179
13180 /// Walk up chain skipping non-aliasing memory nodes,
13181 /// looking for aliasing nodes and adding them to the Aliases vector.
13182 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13183                                    SmallVectorImpl<SDValue> &Aliases) {
13184   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13185   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13186
13187   // Get alias information for node.
13188   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13189
13190   // Starting off.
13191   Chains.push_back(OriginalChain);
13192   unsigned Depth = 0;
13193
13194   // Look at each chain and determine if it is an alias.  If so, add it to the
13195   // aliases list.  If not, then continue up the chain looking for the next
13196   // candidate.
13197   while (!Chains.empty()) {
13198     SDValue Chain = Chains.back();
13199     Chains.pop_back();
13200
13201     // For TokenFactor nodes, look at each operand and only continue up the
13202     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13203     // find more and revert to original chain since the xform is unlikely to be
13204     // profitable.
13205     //
13206     // FIXME: The depth check could be made to return the last non-aliasing
13207     // chain we found before we hit a tokenfactor rather than the original
13208     // chain.
13209     if (Depth > 6 || Aliases.size() == 2) {
13210       Aliases.clear();
13211       Aliases.push_back(OriginalChain);
13212       return;
13213     }
13214
13215     // Don't bother if we've been before.
13216     if (!Visited.insert(Chain.getNode()).second)
13217       continue;
13218
13219     switch (Chain.getOpcode()) {
13220     case ISD::EntryToken:
13221       // Entry token is ideal chain operand, but handled in FindBetterChain.
13222       break;
13223
13224     case ISD::LOAD:
13225     case ISD::STORE: {
13226       // Get alias information for Chain.
13227       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13228           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13229
13230       // If chain is alias then stop here.
13231       if (!(IsLoad && IsOpLoad) &&
13232           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13233         Aliases.push_back(Chain);
13234       } else {
13235         // Look further up the chain.
13236         Chains.push_back(Chain.getOperand(0));
13237         ++Depth;
13238       }
13239       break;
13240     }
13241
13242     case ISD::TokenFactor:
13243       // We have to check each of the operands of the token factor for "small"
13244       // token factors, so we queue them up.  Adding the operands to the queue
13245       // (stack) in reverse order maintains the original order and increases the
13246       // likelihood that getNode will find a matching token factor (CSE.)
13247       if (Chain.getNumOperands() > 16) {
13248         Aliases.push_back(Chain);
13249         break;
13250       }
13251       for (unsigned n = Chain.getNumOperands(); n;)
13252         Chains.push_back(Chain.getOperand(--n));
13253       ++Depth;
13254       break;
13255
13256     default:
13257       // For all other instructions we will just have to take what we can get.
13258       Aliases.push_back(Chain);
13259       break;
13260     }
13261   }
13262
13263   // We need to be careful here to also search for aliases through the
13264   // value operand of a store, etc. Consider the following situation:
13265   //   Token1 = ...
13266   //   L1 = load Token1, %52
13267   //   S1 = store Token1, L1, %51
13268   //   L2 = load Token1, %52+8
13269   //   S2 = store Token1, L2, %51+8
13270   //   Token2 = Token(S1, S2)
13271   //   L3 = load Token2, %53
13272   //   S3 = store Token2, L3, %52
13273   //   L4 = load Token2, %53+8
13274   //   S4 = store Token2, L4, %52+8
13275   // If we search for aliases of S3 (which loads address %52), and we look
13276   // only through the chain, then we'll miss the trivial dependence on L1
13277   // (which also loads from %52). We then might change all loads and
13278   // stores to use Token1 as their chain operand, which could result in
13279   // copying %53 into %52 before copying %52 into %51 (which should
13280   // happen first).
13281   //
13282   // The problem is, however, that searching for such data dependencies
13283   // can become expensive, and the cost is not directly related to the
13284   // chain depth. Instead, we'll rule out such configurations here by
13285   // insisting that we've visited all chain users (except for users
13286   // of the original chain, which is not necessary). When doing this,
13287   // we need to look through nodes we don't care about (otherwise, things
13288   // like register copies will interfere with trivial cases).
13289
13290   SmallVector<const SDNode *, 16> Worklist;
13291   for (const SDNode *N : Visited)
13292     if (N != OriginalChain.getNode())
13293       Worklist.push_back(N);
13294
13295   while (!Worklist.empty()) {
13296     const SDNode *M = Worklist.pop_back_val();
13297
13298     // We have already visited M, and want to make sure we've visited any uses
13299     // of M that we care about. For uses that we've not visisted, and don't
13300     // care about, queue them to the worklist.
13301
13302     for (SDNode::use_iterator UI = M->use_begin(),
13303          UIE = M->use_end(); UI != UIE; ++UI)
13304       if (UI.getUse().getValueType() == MVT::Other &&
13305           Visited.insert(*UI).second) {
13306         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13307           // We've not visited this use, and we care about it (it could have an
13308           // ordering dependency with the original node).
13309           Aliases.clear();
13310           Aliases.push_back(OriginalChain);
13311           return;
13312         }
13313
13314         // We've not visited this use, but we don't care about it. Mark it as
13315         // visited and enqueue it to the worklist.
13316         Worklist.push_back(*UI);
13317       }
13318   }
13319 }
13320
13321 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13322 /// (aliasing node.)
13323 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13324   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
13325
13326   // Accumulate all the aliases to this node.
13327   GatherAllAliases(N, OldChain, Aliases);
13328
13329   // If no operands then chain to entry token.
13330   if (Aliases.size() == 0)
13331     return DAG.getEntryNode();
13332
13333   // If a single operand then chain to it.  We don't need to revisit it.
13334   if (Aliases.size() == 1)
13335     return Aliases[0];
13336
13337   // Construct a custom tailored token factor.
13338   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13339 }
13340
13341 /// This is the entry point for the file.
13342 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13343                            CodeGenOpt::Level OptLevel) {
13344   /// This is the main entry point to this class.
13345   DAGCombiner(*this, AA, OptLevel).Run(Level);
13346 }