[DAGCombine] Produce better code for constant splats
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAG.cpp
1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
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 implements the SelectionDAG class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "SDNodeDbgValue.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/IR/CallingConv.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/ManagedStatic.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/Mutex.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetIntrinsicInfo.h"
44 #include "llvm/Target/TargetLowering.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetOptions.h"
47 #include "llvm/Target/TargetRegisterInfo.h"
48 #include "llvm/Target/TargetSelectionDAGInfo.h"
49 #include "llvm/Target/TargetSubtargetInfo.h"
50 #include <algorithm>
51 #include <cmath>
52
53 using namespace llvm;
54
55 /// makeVTList - Return an instance of the SDVTList struct initialized with the
56 /// specified members.
57 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
58   SDVTList Res = {VTs, NumVTs};
59   return Res;
60 }
61
62 // Default null implementations of the callbacks.
63 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
64 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
65
66 //===----------------------------------------------------------------------===//
67 //                              ConstantFPSDNode Class
68 //===----------------------------------------------------------------------===//
69
70 /// isExactlyValue - We don't rely on operator== working on double values, as
71 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
72 /// As such, this method can be used to do an exact bit-for-bit comparison of
73 /// two floating point values.
74 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
75   return getValueAPF().bitwiseIsEqual(V);
76 }
77
78 bool ConstantFPSDNode::isValueValidForType(EVT VT,
79                                            const APFloat& Val) {
80   assert(VT.isFloatingPoint() && "Can only convert between FP types");
81
82   // convert modifies in place, so make a copy.
83   APFloat Val2 = APFloat(Val);
84   bool losesInfo;
85   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
86                       APFloat::rmNearestTiesToEven,
87                       &losesInfo);
88   return !losesInfo;
89 }
90
91 //===----------------------------------------------------------------------===//
92 //                              ISD Namespace
93 //===----------------------------------------------------------------------===//
94
95 /// isBuildVectorAllOnes - Return true if the specified node is a
96 /// BUILD_VECTOR where all of the elements are ~0 or undef.
97 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
98   // Look through a bit convert.
99   while (N->getOpcode() == ISD::BITCAST)
100     N = N->getOperand(0).getNode();
101
102   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
103
104   unsigned i = 0, e = N->getNumOperands();
105
106   // Skip over all of the undef values.
107   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
108     ++i;
109
110   // Do not accept an all-undef vector.
111   if (i == e) return false;
112
113   // Do not accept build_vectors that aren't all constants or which have non-~0
114   // elements. We have to be a bit careful here, as the type of the constant
115   // may not be the same as the type of the vector elements due to type
116   // legalization (the elements are promoted to a legal type for the target and
117   // a vector of a type may be legal when the base element type is not).
118   // We only want to check enough bits to cover the vector elements, because
119   // we care if the resultant vector is all ones, not whether the individual
120   // constants are.
121   SDValue NotZero = N->getOperand(i);
122   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
123   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
124     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
125       return false;
126   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
127     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
128       return false;
129   } else
130     return false;
131
132   // Okay, we have at least one ~0 value, check to see if the rest match or are
133   // undefs. Even with the above element type twiddling, this should be OK, as
134   // the same type legalization should have applied to all the elements.
135   for (++i; i != e; ++i)
136     if (N->getOperand(i) != NotZero &&
137         N->getOperand(i).getOpcode() != ISD::UNDEF)
138       return false;
139   return true;
140 }
141
142
143 /// isBuildVectorAllZeros - Return true if the specified node is a
144 /// BUILD_VECTOR where all of the elements are 0 or undef.
145 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
146   // Look through a bit convert.
147   while (N->getOpcode() == ISD::BITCAST)
148     N = N->getOperand(0).getNode();
149
150   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
151
152   bool IsAllUndef = true;
153   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i) {
154     if (N->getOperand(i).getOpcode() == ISD::UNDEF)
155       continue;
156     IsAllUndef = false;
157     // Do not accept build_vectors that aren't all constants or which have non-0
158     // elements. We have to be a bit careful here, as the type of the constant
159     // may not be the same as the type of the vector elements due to type
160     // legalization (the elements are promoted to a legal type for the target
161     // and a vector of a type may be legal when the base element type is not).
162     // We only want to check enough bits to cover the vector elements, because
163     // we care if the resultant vector is all zeros, not whether the individual
164     // constants are.
165     SDValue Zero = N->getOperand(i);
166     unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
167     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Zero)) {
168       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
169         return false;
170     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Zero)) {
171       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
172         return false;
173     } else
174       return false;
175   }
176
177   // Do not accept an all-undef vector.
178   if (IsAllUndef)
179     return false;
180   return true;
181 }
182
183 /// \brief Return true if the specified node is a BUILD_VECTOR node of
184 /// all ConstantSDNode or undef.
185 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
186   if (N->getOpcode() != ISD::BUILD_VECTOR)
187     return false;
188
189   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
190     SDValue Op = N->getOperand(i);
191     if (Op.getOpcode() == ISD::UNDEF)
192       continue;
193     if (!isa<ConstantSDNode>(Op))
194       return false;
195   }
196   return true;
197 }
198
199 /// isScalarToVector - Return true if the specified node is a
200 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
201 /// element is not an undef.
202 bool ISD::isScalarToVector(const SDNode *N) {
203   if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
204     return true;
205
206   if (N->getOpcode() != ISD::BUILD_VECTOR)
207     return false;
208   if (N->getOperand(0).getOpcode() == ISD::UNDEF)
209     return false;
210   unsigned NumElems = N->getNumOperands();
211   if (NumElems == 1)
212     return false;
213   for (unsigned i = 1; i < NumElems; ++i) {
214     SDValue V = N->getOperand(i);
215     if (V.getOpcode() != ISD::UNDEF)
216       return false;
217   }
218   return true;
219 }
220
221 /// allOperandsUndef - Return true if the node has at least one operand
222 /// and all operands of the specified node are ISD::UNDEF.
223 bool ISD::allOperandsUndef(const SDNode *N) {
224   // Return false if the node has no operands.
225   // This is "logically inconsistent" with the definition of "all" but
226   // is probably the desired behavior.
227   if (N->getNumOperands() == 0)
228     return false;
229
230   for (unsigned i = 0, e = N->getNumOperands(); i != e ; ++i)
231     if (N->getOperand(i).getOpcode() != ISD::UNDEF)
232       return false;
233
234   return true;
235 }
236
237 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
238   switch (ExtType) {
239   case ISD::EXTLOAD:
240     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
241   case ISD::SEXTLOAD:
242     return ISD::SIGN_EXTEND;
243   case ISD::ZEXTLOAD:
244     return ISD::ZERO_EXTEND;
245   default:
246     break;
247   }
248
249   llvm_unreachable("Invalid LoadExtType");
250 }
251
252 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
253 /// when given the operation for (X op Y).
254 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
255   // To perform this operation, we just need to swap the L and G bits of the
256   // operation.
257   unsigned OldL = (Operation >> 2) & 1;
258   unsigned OldG = (Operation >> 1) & 1;
259   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
260                        (OldL << 1) |       // New G bit
261                        (OldG << 2));       // New L bit.
262 }
263
264 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
265 /// 'op' is a valid SetCC operation.
266 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
267   unsigned Operation = Op;
268   if (isInteger)
269     Operation ^= 7;   // Flip L, G, E bits, but not U.
270   else
271     Operation ^= 15;  // Flip all of the condition bits.
272
273   if (Operation > ISD::SETTRUE2)
274     Operation &= ~8;  // Don't let N and U bits get set.
275
276   return ISD::CondCode(Operation);
277 }
278
279
280 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
281 /// signed operation and 2 if the result is an unsigned comparison.  Return zero
282 /// if the operation does not depend on the sign of the input (setne and seteq).
283 static int isSignedOp(ISD::CondCode Opcode) {
284   switch (Opcode) {
285   default: llvm_unreachable("Illegal integer setcc operation!");
286   case ISD::SETEQ:
287   case ISD::SETNE: return 0;
288   case ISD::SETLT:
289   case ISD::SETLE:
290   case ISD::SETGT:
291   case ISD::SETGE: return 1;
292   case ISD::SETULT:
293   case ISD::SETULE:
294   case ISD::SETUGT:
295   case ISD::SETUGE: return 2;
296   }
297 }
298
299 /// getSetCCOrOperation - Return the result of a logical OR between different
300 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
301 /// returns SETCC_INVALID if it is not possible to represent the resultant
302 /// comparison.
303 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
304                                        bool isInteger) {
305   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
306     // Cannot fold a signed integer setcc with an unsigned integer setcc.
307     return ISD::SETCC_INVALID;
308
309   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
310
311   // If the N and U bits get set then the resultant comparison DOES suddenly
312   // care about orderedness, and is true when ordered.
313   if (Op > ISD::SETTRUE2)
314     Op &= ~16;     // Clear the U bit if the N bit is set.
315
316   // Canonicalize illegal integer setcc's.
317   if (isInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
318     Op = ISD::SETNE;
319
320   return ISD::CondCode(Op);
321 }
322
323 /// getSetCCAndOperation - Return the result of a logical AND between different
324 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
325 /// function returns zero if it is not possible to represent the resultant
326 /// comparison.
327 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
328                                         bool isInteger) {
329   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
330     // Cannot fold a signed setcc with an unsigned setcc.
331     return ISD::SETCC_INVALID;
332
333   // Combine all of the condition bits.
334   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
335
336   // Canonicalize illegal integer setcc's.
337   if (isInteger) {
338     switch (Result) {
339     default: break;
340     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
341     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
342     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
343     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
344     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
345     }
346   }
347
348   return Result;
349 }
350
351 //===----------------------------------------------------------------------===//
352 //                           SDNode Profile Support
353 //===----------------------------------------------------------------------===//
354
355 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
356 ///
357 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
358   ID.AddInteger(OpC);
359 }
360
361 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
362 /// solely with their pointer.
363 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
364   ID.AddPointer(VTList.VTs);
365 }
366
367 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
368 ///
369 static void AddNodeIDOperands(FoldingSetNodeID &ID,
370                               ArrayRef<SDValue> Ops) {
371   for (auto& Op : Ops) {
372     ID.AddPointer(Op.getNode());
373     ID.AddInteger(Op.getResNo());
374   }
375 }
376
377 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
378 ///
379 static void AddNodeIDOperands(FoldingSetNodeID &ID,
380                               ArrayRef<SDUse> Ops) {
381   for (auto& Op : Ops) {
382     ID.AddPointer(Op.getNode());
383     ID.AddInteger(Op.getResNo());
384   }
385 }
386
387 static void AddBinaryNodeIDCustom(FoldingSetNodeID &ID, bool nuw, bool nsw,
388                                   bool exact) {
389   ID.AddBoolean(nuw);
390   ID.AddBoolean(nsw);
391   ID.AddBoolean(exact);
392 }
393
394 /// AddBinaryNodeIDCustom - Add BinarySDNodes special infos
395 static void AddBinaryNodeIDCustom(FoldingSetNodeID &ID, unsigned Opcode,
396                                   bool nuw, bool nsw, bool exact) {
397   if (isBinOpWithFlags(Opcode))
398     AddBinaryNodeIDCustom(ID, nuw, nsw, exact);
399 }
400
401 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
402                           SDVTList VTList, ArrayRef<SDValue> OpList) {
403   AddNodeIDOpcode(ID, OpC);
404   AddNodeIDValueTypes(ID, VTList);
405   AddNodeIDOperands(ID, OpList);
406 }
407
408 /// AddNodeIDCustom - If this is an SDNode with special info, add this info to
409 /// the NodeID data.
410 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
411   switch (N->getOpcode()) {
412   case ISD::TargetExternalSymbol:
413   case ISD::ExternalSymbol:
414     llvm_unreachable("Should only be used on nodes with operands");
415   default: break;  // Normal nodes don't need extra info.
416   case ISD::TargetConstant:
417   case ISD::Constant: {
418     const ConstantSDNode *C = cast<ConstantSDNode>(N);
419     ID.AddPointer(C->getConstantIntValue());
420     ID.AddBoolean(C->isOpaque());
421     break;
422   }
423   case ISD::TargetConstantFP:
424   case ISD::ConstantFP: {
425     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
426     break;
427   }
428   case ISD::TargetGlobalAddress:
429   case ISD::GlobalAddress:
430   case ISD::TargetGlobalTLSAddress:
431   case ISD::GlobalTLSAddress: {
432     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
433     ID.AddPointer(GA->getGlobal());
434     ID.AddInteger(GA->getOffset());
435     ID.AddInteger(GA->getTargetFlags());
436     ID.AddInteger(GA->getAddressSpace());
437     break;
438   }
439   case ISD::BasicBlock:
440     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
441     break;
442   case ISD::Register:
443     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
444     break;
445   case ISD::RegisterMask:
446     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
447     break;
448   case ISD::SRCVALUE:
449     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
450     break;
451   case ISD::FrameIndex:
452   case ISD::TargetFrameIndex:
453     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
454     break;
455   case ISD::JumpTable:
456   case ISD::TargetJumpTable:
457     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
458     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
459     break;
460   case ISD::ConstantPool:
461   case ISD::TargetConstantPool: {
462     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
463     ID.AddInteger(CP->getAlignment());
464     ID.AddInteger(CP->getOffset());
465     if (CP->isMachineConstantPoolEntry())
466       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
467     else
468       ID.AddPointer(CP->getConstVal());
469     ID.AddInteger(CP->getTargetFlags());
470     break;
471   }
472   case ISD::TargetIndex: {
473     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
474     ID.AddInteger(TI->getIndex());
475     ID.AddInteger(TI->getOffset());
476     ID.AddInteger(TI->getTargetFlags());
477     break;
478   }
479   case ISD::LOAD: {
480     const LoadSDNode *LD = cast<LoadSDNode>(N);
481     ID.AddInteger(LD->getMemoryVT().getRawBits());
482     ID.AddInteger(LD->getRawSubclassData());
483     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
484     break;
485   }
486   case ISD::STORE: {
487     const StoreSDNode *ST = cast<StoreSDNode>(N);
488     ID.AddInteger(ST->getMemoryVT().getRawBits());
489     ID.AddInteger(ST->getRawSubclassData());
490     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
491     break;
492   }
493   case ISD::SDIV:
494   case ISD::UDIV:
495   case ISD::SRA:
496   case ISD::SRL:
497   case ISD::MUL:
498   case ISD::ADD:
499   case ISD::SUB:
500   case ISD::SHL: {
501     const BinaryWithFlagsSDNode *BinNode = cast<BinaryWithFlagsSDNode>(N);
502     AddBinaryNodeIDCustom(ID, N->getOpcode(), BinNode->hasNoUnsignedWrap(),
503                           BinNode->hasNoSignedWrap(), BinNode->isExact());
504     break;
505   }
506   case ISD::ATOMIC_CMP_SWAP:
507   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
508   case ISD::ATOMIC_SWAP:
509   case ISD::ATOMIC_LOAD_ADD:
510   case ISD::ATOMIC_LOAD_SUB:
511   case ISD::ATOMIC_LOAD_AND:
512   case ISD::ATOMIC_LOAD_OR:
513   case ISD::ATOMIC_LOAD_XOR:
514   case ISD::ATOMIC_LOAD_NAND:
515   case ISD::ATOMIC_LOAD_MIN:
516   case ISD::ATOMIC_LOAD_MAX:
517   case ISD::ATOMIC_LOAD_UMIN:
518   case ISD::ATOMIC_LOAD_UMAX:
519   case ISD::ATOMIC_LOAD:
520   case ISD::ATOMIC_STORE: {
521     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
522     ID.AddInteger(AT->getMemoryVT().getRawBits());
523     ID.AddInteger(AT->getRawSubclassData());
524     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
525     break;
526   }
527   case ISD::PREFETCH: {
528     const MemSDNode *PF = cast<MemSDNode>(N);
529     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
530     break;
531   }
532   case ISD::VECTOR_SHUFFLE: {
533     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
534     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
535          i != e; ++i)
536       ID.AddInteger(SVN->getMaskElt(i));
537     break;
538   }
539   case ISD::TargetBlockAddress:
540   case ISD::BlockAddress: {
541     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
542     ID.AddPointer(BA->getBlockAddress());
543     ID.AddInteger(BA->getOffset());
544     ID.AddInteger(BA->getTargetFlags());
545     break;
546   }
547   } // end switch (N->getOpcode())
548
549   // Target specific memory nodes could also have address spaces to check.
550   if (N->isTargetMemoryOpcode())
551     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
552 }
553
554 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
555 /// data.
556 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
557   AddNodeIDOpcode(ID, N->getOpcode());
558   // Add the return value info.
559   AddNodeIDValueTypes(ID, N->getVTList());
560   // Add the operand info.
561   AddNodeIDOperands(ID, N->ops());
562
563   // Handle SDNode leafs with special info.
564   AddNodeIDCustom(ID, N);
565 }
566
567 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
568 /// the CSE map that carries volatility, temporalness, indexing mode, and
569 /// extension/truncation information.
570 ///
571 static inline unsigned
572 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM, bool isVolatile,
573                      bool isNonTemporal, bool isInvariant) {
574   assert((ConvType & 3) == ConvType &&
575          "ConvType may not require more than 2 bits!");
576   assert((AM & 7) == AM &&
577          "AM may not require more than 3 bits!");
578   return ConvType |
579          (AM << 2) |
580          (isVolatile << 5) |
581          (isNonTemporal << 6) |
582          (isInvariant << 7);
583 }
584
585 //===----------------------------------------------------------------------===//
586 //                              SelectionDAG Class
587 //===----------------------------------------------------------------------===//
588
589 /// doNotCSE - Return true if CSE should not be performed for this node.
590 static bool doNotCSE(SDNode *N) {
591   if (N->getValueType(0) == MVT::Glue)
592     return true; // Never CSE anything that produces a flag.
593
594   switch (N->getOpcode()) {
595   default: break;
596   case ISD::HANDLENODE:
597   case ISD::EH_LABEL:
598     return true;   // Never CSE these nodes.
599   }
600
601   // Check that remaining values produced are not flags.
602   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
603     if (N->getValueType(i) == MVT::Glue)
604       return true; // Never CSE anything that produces a flag.
605
606   return false;
607 }
608
609 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
610 /// SelectionDAG.
611 void SelectionDAG::RemoveDeadNodes() {
612   // Create a dummy node (which is not added to allnodes), that adds a reference
613   // to the root node, preventing it from being deleted.
614   HandleSDNode Dummy(getRoot());
615
616   SmallVector<SDNode*, 128> DeadNodes;
617
618   // Add all obviously-dead nodes to the DeadNodes worklist.
619   for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
620     if (I->use_empty())
621       DeadNodes.push_back(I);
622
623   RemoveDeadNodes(DeadNodes);
624
625   // If the root changed (e.g. it was a dead load, update the root).
626   setRoot(Dummy.getValue());
627 }
628
629 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
630 /// given list, and any nodes that become unreachable as a result.
631 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
632
633   // Process the worklist, deleting the nodes and adding their uses to the
634   // worklist.
635   while (!DeadNodes.empty()) {
636     SDNode *N = DeadNodes.pop_back_val();
637
638     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
639       DUL->NodeDeleted(N, nullptr);
640
641     // Take the node out of the appropriate CSE map.
642     RemoveNodeFromCSEMaps(N);
643
644     // Next, brutally remove the operand list.  This is safe to do, as there are
645     // no cycles in the graph.
646     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
647       SDUse &Use = *I++;
648       SDNode *Operand = Use.getNode();
649       Use.set(SDValue());
650
651       // Now that we removed this operand, see if there are no uses of it left.
652       if (Operand->use_empty())
653         DeadNodes.push_back(Operand);
654     }
655
656     DeallocateNode(N);
657   }
658 }
659
660 void SelectionDAG::RemoveDeadNode(SDNode *N){
661   SmallVector<SDNode*, 16> DeadNodes(1, N);
662
663   // Create a dummy node that adds a reference to the root node, preventing
664   // it from being deleted.  (This matters if the root is an operand of the
665   // dead node.)
666   HandleSDNode Dummy(getRoot());
667
668   RemoveDeadNodes(DeadNodes);
669 }
670
671 void SelectionDAG::DeleteNode(SDNode *N) {
672   // First take this out of the appropriate CSE map.
673   RemoveNodeFromCSEMaps(N);
674
675   // Finally, remove uses due to operands of this node, remove from the
676   // AllNodes list, and delete the node.
677   DeleteNodeNotInCSEMaps(N);
678 }
679
680 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
681   assert(N != AllNodes.begin() && "Cannot delete the entry node!");
682   assert(N->use_empty() && "Cannot delete a node that is not dead!");
683
684   // Drop all of the operands and decrement used node's use counts.
685   N->DropOperands();
686
687   DeallocateNode(N);
688 }
689
690 void SDDbgInfo::erase(const SDNode *Node) {
691   DbgValMapType::iterator I = DbgValMap.find(Node);
692   if (I == DbgValMap.end())
693     return;
694   for (auto &Val: I->second)
695     Val->setIsInvalidated();
696   DbgValMap.erase(I);
697 }
698
699 void SelectionDAG::DeallocateNode(SDNode *N) {
700   if (N->OperandsNeedDelete)
701     delete[] N->OperandList;
702
703   // Set the opcode to DELETED_NODE to help catch bugs when node
704   // memory is reallocated.
705   N->NodeType = ISD::DELETED_NODE;
706
707   NodeAllocator.Deallocate(AllNodes.remove(N));
708
709   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
710   // them and forget about that node.
711   DbgInfo->erase(N);
712 }
713
714 #ifndef NDEBUG
715 /// VerifySDNode - Sanity check the given SDNode.  Aborts if it is invalid.
716 static void VerifySDNode(SDNode *N) {
717   switch (N->getOpcode()) {
718   default:
719     break;
720   case ISD::BUILD_PAIR: {
721     EVT VT = N->getValueType(0);
722     assert(N->getNumValues() == 1 && "Too many results!");
723     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
724            "Wrong return type!");
725     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
726     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
727            "Mismatched operand types!");
728     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
729            "Wrong operand type!");
730     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
731            "Wrong return type size");
732     break;
733   }
734   case ISD::BUILD_VECTOR: {
735     assert(N->getNumValues() == 1 && "Too many results!");
736     assert(N->getValueType(0).isVector() && "Wrong return type!");
737     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
738            "Wrong number of operands!");
739     EVT EltVT = N->getValueType(0).getVectorElementType();
740     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
741       assert((I->getValueType() == EltVT ||
742              (EltVT.isInteger() && I->getValueType().isInteger() &&
743               EltVT.bitsLE(I->getValueType()))) &&
744             "Wrong operand type!");
745       assert(I->getValueType() == N->getOperand(0).getValueType() &&
746              "Operands must all have the same type");
747     }
748     break;
749   }
750   }
751 }
752 #endif // NDEBUG
753
754 /// \brief Insert a newly allocated node into the DAG.
755 ///
756 /// Handles insertion into the all nodes list and CSE map, as well as
757 /// verification and other common operations when a new node is allocated.
758 void SelectionDAG::InsertNode(SDNode *N) {
759   AllNodes.push_back(N);
760 #ifndef NDEBUG
761   VerifySDNode(N);
762 #endif
763 }
764
765 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
766 /// correspond to it.  This is useful when we're about to delete or repurpose
767 /// the node.  We don't want future request for structurally identical nodes
768 /// to return N anymore.
769 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
770   bool Erased = false;
771   switch (N->getOpcode()) {
772   case ISD::HANDLENODE: return false;  // noop.
773   case ISD::CONDCODE:
774     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
775            "Cond code doesn't exist!");
776     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
777     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
778     break;
779   case ISD::ExternalSymbol:
780     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
781     break;
782   case ISD::TargetExternalSymbol: {
783     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
784     Erased = TargetExternalSymbols.erase(
785                std::pair<std::string,unsigned char>(ESN->getSymbol(),
786                                                     ESN->getTargetFlags()));
787     break;
788   }
789   case ISD::VALUETYPE: {
790     EVT VT = cast<VTSDNode>(N)->getVT();
791     if (VT.isExtended()) {
792       Erased = ExtendedValueTypeNodes.erase(VT);
793     } else {
794       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
795       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
796     }
797     break;
798   }
799   default:
800     // Remove it from the CSE Map.
801     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
802     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
803     Erased = CSEMap.RemoveNode(N);
804     break;
805   }
806 #ifndef NDEBUG
807   // Verify that the node was actually in one of the CSE maps, unless it has a
808   // flag result (which cannot be CSE'd) or is one of the special cases that are
809   // not subject to CSE.
810   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
811       !N->isMachineOpcode() && !doNotCSE(N)) {
812     N->dump(this);
813     dbgs() << "\n";
814     llvm_unreachable("Node is not in map!");
815   }
816 #endif
817   return Erased;
818 }
819
820 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
821 /// maps and modified in place. Add it back to the CSE maps, unless an identical
822 /// node already exists, in which case transfer all its users to the existing
823 /// node. This transfer can potentially trigger recursive merging.
824 ///
825 void
826 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
827   // For node types that aren't CSE'd, just act as if no identical node
828   // already exists.
829   if (!doNotCSE(N)) {
830     SDNode *Existing = CSEMap.GetOrInsertNode(N);
831     if (Existing != N) {
832       // If there was already an existing matching node, use ReplaceAllUsesWith
833       // to replace the dead one with the existing one.  This can cause
834       // recursive merging of other unrelated nodes down the line.
835       ReplaceAllUsesWith(N, Existing);
836
837       // N is now dead. Inform the listeners and delete it.
838       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
839         DUL->NodeDeleted(N, Existing);
840       DeleteNodeNotInCSEMaps(N);
841       return;
842     }
843   }
844
845   // If the node doesn't already exist, we updated it.  Inform listeners.
846   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
847     DUL->NodeUpdated(N);
848 }
849
850 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
851 /// were replaced with those specified.  If this node is never memoized,
852 /// return null, otherwise return a pointer to the slot it would take.  If a
853 /// node already exists with these operands, the slot will be non-null.
854 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
855                                            void *&InsertPos) {
856   if (doNotCSE(N))
857     return nullptr;
858
859   SDValue Ops[] = { Op };
860   FoldingSetNodeID ID;
861   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
862   AddNodeIDCustom(ID, N);
863   SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
864   return Node;
865 }
866
867 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
868 /// were replaced with those specified.  If this node is never memoized,
869 /// return null, otherwise return a pointer to the slot it would take.  If a
870 /// node already exists with these operands, the slot will be non-null.
871 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
872                                            SDValue Op1, SDValue Op2,
873                                            void *&InsertPos) {
874   if (doNotCSE(N))
875     return nullptr;
876
877   SDValue Ops[] = { Op1, Op2 };
878   FoldingSetNodeID ID;
879   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
880   AddNodeIDCustom(ID, N);
881   SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
882   return Node;
883 }
884
885
886 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
887 /// were replaced with those specified.  If this node is never memoized,
888 /// return null, otherwise return a pointer to the slot it would take.  If a
889 /// node already exists with these operands, the slot will be non-null.
890 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
891                                            void *&InsertPos) {
892   if (doNotCSE(N))
893     return nullptr;
894
895   FoldingSetNodeID ID;
896   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
897   AddNodeIDCustom(ID, N);
898   SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
899   return Node;
900 }
901
902 /// getEVTAlignment - Compute the default alignment value for the
903 /// given type.
904 ///
905 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
906   Type *Ty = VT == MVT::iPTR ?
907                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
908                    VT.getTypeForEVT(*getContext());
909
910   return TLI->getDataLayout()->getABITypeAlignment(Ty);
911 }
912
913 // EntryNode could meaningfully have debug info if we can find it...
914 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
915     : TM(tm), TSI(nullptr), TLI(nullptr), OptLevel(OL),
916       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
917       Root(getEntryNode()), NewNodesMustHaveLegalTypes(false),
918       UpdateListeners(nullptr) {
919   AllNodes.push_back(&EntryNode);
920   DbgInfo = new SDDbgInfo();
921 }
922
923 void SelectionDAG::init(MachineFunction &mf) {
924   MF = &mf;
925   TLI = getSubtarget().getTargetLowering();
926   TSI = getSubtarget().getSelectionDAGInfo();
927   Context = &mf.getFunction()->getContext();
928 }
929
930 SelectionDAG::~SelectionDAG() {
931   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
932   allnodes_clear();
933   delete DbgInfo;
934 }
935
936 void SelectionDAG::allnodes_clear() {
937   assert(&*AllNodes.begin() == &EntryNode);
938   AllNodes.remove(AllNodes.begin());
939   while (!AllNodes.empty())
940     DeallocateNode(AllNodes.begin());
941 }
942
943 BinarySDNode *SelectionDAG::GetBinarySDNode(unsigned Opcode, SDLoc DL,
944                                             SDVTList VTs, SDValue N1,
945                                             SDValue N2, bool nuw, bool nsw,
946                                             bool exact) {
947   if (isBinOpWithFlags(Opcode)) {
948     BinaryWithFlagsSDNode *FN = new (NodeAllocator) BinaryWithFlagsSDNode(
949         Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, N1, N2);
950     FN->setHasNoUnsignedWrap(nuw);
951     FN->setHasNoSignedWrap(nsw);
952     FN->setIsExact(exact);
953
954     return FN;
955   }
956
957   BinarySDNode *N = new (NodeAllocator)
958       BinarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, N1, N2);
959   return N;
960 }
961
962 void SelectionDAG::clear() {
963   allnodes_clear();
964   OperandAllocator.Reset();
965   CSEMap.clear();
966
967   ExtendedValueTypeNodes.clear();
968   ExternalSymbols.clear();
969   TargetExternalSymbols.clear();
970   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
971             static_cast<CondCodeSDNode*>(nullptr));
972   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
973             static_cast<SDNode*>(nullptr));
974
975   EntryNode.UseList = nullptr;
976   AllNodes.push_back(&EntryNode);
977   Root = getEntryNode();
978   DbgInfo->clear();
979 }
980
981 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) {
982   return VT.bitsGT(Op.getValueType()) ?
983     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
984     getNode(ISD::TRUNCATE, DL, VT, Op);
985 }
986
987 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) {
988   return VT.bitsGT(Op.getValueType()) ?
989     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
990     getNode(ISD::TRUNCATE, DL, VT, Op);
991 }
992
993 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) {
994   return VT.bitsGT(Op.getValueType()) ?
995     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
996     getNode(ISD::TRUNCATE, DL, VT, Op);
997 }
998
999 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, SDLoc SL, EVT VT,
1000                                         EVT OpVT) {
1001   if (VT.bitsLE(Op.getValueType()))
1002     return getNode(ISD::TRUNCATE, SL, VT, Op);
1003
1004   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1005   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1006 }
1007
1008 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, SDLoc DL, EVT VT) {
1009   assert(!VT.isVector() &&
1010          "getZeroExtendInReg should use the vector element type instead of "
1011          "the vector type!");
1012   if (Op.getValueType() == VT) return Op;
1013   unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
1014   APInt Imm = APInt::getLowBitsSet(BitWidth,
1015                                    VT.getSizeInBits());
1016   return getNode(ISD::AND, DL, Op.getValueType(), Op,
1017                  getConstant(Imm, Op.getValueType()));
1018 }
1019
1020 SDValue SelectionDAG::getAnyExtendVectorInReg(SDValue Op, SDLoc DL, EVT VT) {
1021   assert(VT.isVector() && "This DAG node is restricted to vector types.");
1022   assert(VT.getSizeInBits() == Op.getValueType().getSizeInBits() &&
1023          "The sizes of the input and result must match in order to perform the "
1024          "extend in-register.");
1025   assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1026          "The destination vector type must have fewer lanes than the input.");
1027   return getNode(ISD::ANY_EXTEND_VECTOR_INREG, DL, VT, Op);
1028 }
1029
1030 SDValue SelectionDAG::getSignExtendVectorInReg(SDValue Op, SDLoc DL, EVT VT) {
1031   assert(VT.isVector() && "This DAG node is restricted to vector types.");
1032   assert(VT.getSizeInBits() == Op.getValueType().getSizeInBits() &&
1033          "The sizes of the input and result must match in order to perform the "
1034          "extend in-register.");
1035   assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1036          "The destination vector type must have fewer lanes than the input.");
1037   return getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, VT, Op);
1038 }
1039
1040 SDValue SelectionDAG::getZeroExtendVectorInReg(SDValue Op, SDLoc DL, EVT VT) {
1041   assert(VT.isVector() && "This DAG node is restricted to vector types.");
1042   assert(VT.getSizeInBits() == Op.getValueType().getSizeInBits() &&
1043          "The sizes of the input and result must match in order to perform the "
1044          "extend in-register.");
1045   assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1046          "The destination vector type must have fewer lanes than the input.");
1047   return getNode(ISD::ZERO_EXTEND_VECTOR_INREG, DL, VT, Op);
1048 }
1049
1050 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1051 ///
1052 SDValue SelectionDAG::getNOT(SDLoc DL, SDValue Val, EVT VT) {
1053   EVT EltVT = VT.getScalarType();
1054   SDValue NegOne =
1055     getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
1056   return getNode(ISD::XOR, DL, VT, Val, NegOne);
1057 }
1058
1059 SDValue SelectionDAG::getLogicalNOT(SDLoc DL, SDValue Val, EVT VT) {
1060   EVT EltVT = VT.getScalarType();
1061   SDValue TrueValue;
1062   switch (TLI->getBooleanContents(VT)) {
1063     case TargetLowering::ZeroOrOneBooleanContent:
1064     case TargetLowering::UndefinedBooleanContent:
1065       TrueValue = getConstant(1, VT);
1066       break;
1067     case TargetLowering::ZeroOrNegativeOneBooleanContent:
1068       TrueValue = getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
1069                               VT);
1070       break;
1071   }
1072   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1073 }
1074
1075 SDValue SelectionDAG::getConstant(uint64_t Val, EVT VT, bool isT, bool isO) {
1076   EVT EltVT = VT.getScalarType();
1077   assert((EltVT.getSizeInBits() >= 64 ||
1078          (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1079          "getConstant with a uint64_t value that doesn't fit in the type!");
1080   return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT, isO);
1081 }
1082
1083 SDValue SelectionDAG::getConstant(const APInt &Val, EVT VT, bool isT, bool isO)
1084 {
1085   return getConstant(*ConstantInt::get(*Context, Val), VT, isT, isO);
1086 }
1087
1088 SDValue SelectionDAG::getConstant(const ConstantInt &Val, EVT VT, bool isT,
1089                                   bool isO) {
1090   assert(VT.isInteger() && "Cannot create FP integer constant!");
1091
1092   EVT EltVT = VT.getScalarType();
1093   const ConstantInt *Elt = &Val;
1094
1095   // In some cases the vector type is legal but the element type is illegal and
1096   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1097   // inserted value (the type does not need to match the vector element type).
1098   // Any extra bits introduced will be truncated away.
1099   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1100       TargetLowering::TypePromoteInteger) {
1101    EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1102    APInt NewVal = Elt->getValue().zext(EltVT.getSizeInBits());
1103    Elt = ConstantInt::get(*getContext(), NewVal);
1104   }
1105   // In other cases the element type is illegal and needs to be expanded, for
1106   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1107   // the value into n parts and use a vector type with n-times the elements.
1108   // Then bitcast to the type requested.
1109   // Legalizing constants too early makes the DAGCombiner's job harder so we
1110   // only legalize if the DAG tells us we must produce legal types.
1111   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1112            TLI->getTypeAction(*getContext(), EltVT) ==
1113            TargetLowering::TypeExpandInteger) {
1114     APInt NewVal = Elt->getValue();
1115     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1116     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1117     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1118     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1119
1120     // Check the temporary vector is the correct size. If this fails then
1121     // getTypeToTransformTo() probably returned a type whose size (in bits)
1122     // isn't a power-of-2 factor of the requested type size.
1123     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1124
1125     SmallVector<SDValue, 2> EltParts;
1126     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1127       EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
1128                                            .trunc(ViaEltSizeInBits),
1129                                      ViaEltVT, isT, isO));
1130     }
1131
1132     // EltParts is currently in little endian order. If we actually want
1133     // big-endian order then reverse it now.
1134     if (TLI->isBigEndian())
1135       std::reverse(EltParts.begin(), EltParts.end());
1136
1137     // The elements must be reversed when the element order is different
1138     // to the endianness of the elements (because the BITCAST is itself a
1139     // vector shuffle in this situation). However, we do not need any code to
1140     // perform this reversal because getConstant() is producing a vector
1141     // splat.
1142     // This situation occurs in MIPS MSA.
1143
1144     SmallVector<SDValue, 8> Ops;
1145     for (unsigned i = 0; i < VT.getVectorNumElements(); ++i)
1146       Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
1147
1148     SDValue Result = getNode(ISD::BITCAST, SDLoc(), VT,
1149                              getNode(ISD::BUILD_VECTOR, SDLoc(), ViaVecVT,
1150                                      Ops));
1151     return Result;
1152   }
1153
1154   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1155          "APInt size does not match type size!");
1156   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1157   FoldingSetNodeID ID;
1158   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1159   ID.AddPointer(Elt);
1160   ID.AddBoolean(isO);
1161   void *IP = nullptr;
1162   SDNode *N = nullptr;
1163   if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
1164     if (!VT.isVector())
1165       return SDValue(N, 0);
1166
1167   if (!N) {
1168     N = new (NodeAllocator) ConstantSDNode(isT, isO, Elt, EltVT);
1169     CSEMap.InsertNode(N, IP);
1170     InsertNode(N);
1171   }
1172
1173   SDValue Result(N, 0);
1174   if (VT.isVector()) {
1175     SmallVector<SDValue, 8> Ops;
1176     Ops.assign(VT.getVectorNumElements(), Result);
1177     Result = getNode(ISD::BUILD_VECTOR, SDLoc(), VT, Ops);
1178   }
1179   return Result;
1180 }
1181
1182 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
1183   return getConstant(Val, TLI->getPointerTy(), isTarget);
1184 }
1185
1186
1187 SDValue SelectionDAG::getConstantFP(const APFloat& V, EVT VT, bool isTarget) {
1188   return getConstantFP(*ConstantFP::get(*getContext(), V), VT, isTarget);
1189 }
1190
1191 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, EVT VT, bool isTarget){
1192   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1193
1194   EVT EltVT = VT.getScalarType();
1195
1196   // Do the map lookup using the actual bit pattern for the floating point
1197   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1198   // we don't have issues with SNANs.
1199   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1200   FoldingSetNodeID ID;
1201   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1202   ID.AddPointer(&V);
1203   void *IP = nullptr;
1204   SDNode *N = nullptr;
1205   if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
1206     if (!VT.isVector())
1207       return SDValue(N, 0);
1208
1209   if (!N) {
1210     N = new (NodeAllocator) ConstantFPSDNode(isTarget, &V, EltVT);
1211     CSEMap.InsertNode(N, IP);
1212     InsertNode(N);
1213   }
1214
1215   SDValue Result(N, 0);
1216   if (VT.isVector()) {
1217     SmallVector<SDValue, 8> Ops;
1218     Ops.assign(VT.getVectorNumElements(), Result);
1219     // FIXME SDLoc info might be appropriate here
1220     Result = getNode(ISD::BUILD_VECTOR, SDLoc(), VT, Ops);
1221   }
1222   return Result;
1223 }
1224
1225 SDValue SelectionDAG::getConstantFP(double Val, EVT VT, bool isTarget) {
1226   EVT EltVT = VT.getScalarType();
1227   if (EltVT==MVT::f32)
1228     return getConstantFP(APFloat((float)Val), VT, isTarget);
1229   else if (EltVT==MVT::f64)
1230     return getConstantFP(APFloat(Val), VT, isTarget);
1231   else if (EltVT==MVT::f80 || EltVT==MVT::f128 || EltVT==MVT::ppcf128 ||
1232            EltVT==MVT::f16) {
1233     bool ignored;
1234     APFloat apf = APFloat(Val);
1235     apf.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1236                 &ignored);
1237     return getConstantFP(apf, VT, isTarget);
1238   } else
1239     llvm_unreachable("Unsupported type in getConstantFP");
1240 }
1241
1242 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, SDLoc DL,
1243                                        EVT VT, int64_t Offset,
1244                                        bool isTargetGA,
1245                                        unsigned char TargetFlags) {
1246   assert((TargetFlags == 0 || isTargetGA) &&
1247          "Cannot set target flags on target-independent globals");
1248
1249   // Truncate (with sign-extension) the offset value to the pointer size.
1250   unsigned BitWidth = TLI->getPointerTypeSizeInBits(GV->getType());
1251   if (BitWidth < 64)
1252     Offset = SignExtend64(Offset, BitWidth);
1253
1254   unsigned Opc;
1255   if (GV->isThreadLocal())
1256     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1257   else
1258     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1259
1260   FoldingSetNodeID ID;
1261   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1262   ID.AddPointer(GV);
1263   ID.AddInteger(Offset);
1264   ID.AddInteger(TargetFlags);
1265   ID.AddInteger(GV->getType()->getAddressSpace());
1266   void *IP = nullptr;
1267   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1268     return SDValue(E, 0);
1269
1270   SDNode *N = new (NodeAllocator) GlobalAddressSDNode(Opc, DL.getIROrder(),
1271                                                       DL.getDebugLoc(), GV, VT,
1272                                                       Offset, TargetFlags);
1273   CSEMap.InsertNode(N, IP);
1274     InsertNode(N);
1275   return SDValue(N, 0);
1276 }
1277
1278 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1279   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1280   FoldingSetNodeID ID;
1281   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1282   ID.AddInteger(FI);
1283   void *IP = nullptr;
1284   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1285     return SDValue(E, 0);
1286
1287   SDNode *N = new (NodeAllocator) FrameIndexSDNode(FI, VT, isTarget);
1288   CSEMap.InsertNode(N, IP);
1289   InsertNode(N);
1290   return SDValue(N, 0);
1291 }
1292
1293 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1294                                    unsigned char TargetFlags) {
1295   assert((TargetFlags == 0 || isTarget) &&
1296          "Cannot set target flags on target-independent jump tables");
1297   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1298   FoldingSetNodeID ID;
1299   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1300   ID.AddInteger(JTI);
1301   ID.AddInteger(TargetFlags);
1302   void *IP = nullptr;
1303   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1304     return SDValue(E, 0);
1305
1306   SDNode *N = new (NodeAllocator) JumpTableSDNode(JTI, VT, isTarget,
1307                                                   TargetFlags);
1308   CSEMap.InsertNode(N, IP);
1309   InsertNode(N);
1310   return SDValue(N, 0);
1311 }
1312
1313 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1314                                       unsigned Alignment, int Offset,
1315                                       bool isTarget,
1316                                       unsigned char TargetFlags) {
1317   assert((TargetFlags == 0 || isTarget) &&
1318          "Cannot set target flags on target-independent globals");
1319   if (Alignment == 0)
1320     Alignment = TLI->getDataLayout()->getPrefTypeAlignment(C->getType());
1321   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1322   FoldingSetNodeID ID;
1323   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1324   ID.AddInteger(Alignment);
1325   ID.AddInteger(Offset);
1326   ID.AddPointer(C);
1327   ID.AddInteger(TargetFlags);
1328   void *IP = nullptr;
1329   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1330     return SDValue(E, 0);
1331
1332   SDNode *N = new (NodeAllocator) ConstantPoolSDNode(isTarget, C, VT, Offset,
1333                                                      Alignment, TargetFlags);
1334   CSEMap.InsertNode(N, IP);
1335   InsertNode(N);
1336   return SDValue(N, 0);
1337 }
1338
1339
1340 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1341                                       unsigned Alignment, int Offset,
1342                                       bool isTarget,
1343                                       unsigned char TargetFlags) {
1344   assert((TargetFlags == 0 || isTarget) &&
1345          "Cannot set target flags on target-independent globals");
1346   if (Alignment == 0)
1347     Alignment = TLI->getDataLayout()->getPrefTypeAlignment(C->getType());
1348   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1349   FoldingSetNodeID ID;
1350   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1351   ID.AddInteger(Alignment);
1352   ID.AddInteger(Offset);
1353   C->addSelectionDAGCSEId(ID);
1354   ID.AddInteger(TargetFlags);
1355   void *IP = nullptr;
1356   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1357     return SDValue(E, 0);
1358
1359   SDNode *N = new (NodeAllocator) ConstantPoolSDNode(isTarget, C, VT, Offset,
1360                                                      Alignment, TargetFlags);
1361   CSEMap.InsertNode(N, IP);
1362   InsertNode(N);
1363   return SDValue(N, 0);
1364 }
1365
1366 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1367                                      unsigned char TargetFlags) {
1368   FoldingSetNodeID ID;
1369   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1370   ID.AddInteger(Index);
1371   ID.AddInteger(Offset);
1372   ID.AddInteger(TargetFlags);
1373   void *IP = nullptr;
1374   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1375     return SDValue(E, 0);
1376
1377   SDNode *N = new (NodeAllocator) TargetIndexSDNode(Index, VT, Offset,
1378                                                     TargetFlags);
1379   CSEMap.InsertNode(N, IP);
1380   InsertNode(N);
1381   return SDValue(N, 0);
1382 }
1383
1384 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1385   FoldingSetNodeID ID;
1386   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1387   ID.AddPointer(MBB);
1388   void *IP = nullptr;
1389   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1390     return SDValue(E, 0);
1391
1392   SDNode *N = new (NodeAllocator) BasicBlockSDNode(MBB);
1393   CSEMap.InsertNode(N, IP);
1394   InsertNode(N);
1395   return SDValue(N, 0);
1396 }
1397
1398 SDValue SelectionDAG::getValueType(EVT VT) {
1399   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1400       ValueTypeNodes.size())
1401     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1402
1403   SDNode *&N = VT.isExtended() ?
1404     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1405
1406   if (N) return SDValue(N, 0);
1407   N = new (NodeAllocator) VTSDNode(VT);
1408   InsertNode(N);
1409   return SDValue(N, 0);
1410 }
1411
1412 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1413   SDNode *&N = ExternalSymbols[Sym];
1414   if (N) return SDValue(N, 0);
1415   N = new (NodeAllocator) ExternalSymbolSDNode(false, Sym, 0, VT);
1416   InsertNode(N);
1417   return SDValue(N, 0);
1418 }
1419
1420 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1421                                               unsigned char TargetFlags) {
1422   SDNode *&N =
1423     TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1424                                                                TargetFlags)];
1425   if (N) return SDValue(N, 0);
1426   N = new (NodeAllocator) ExternalSymbolSDNode(true, Sym, TargetFlags, VT);
1427   InsertNode(N);
1428   return SDValue(N, 0);
1429 }
1430
1431 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1432   if ((unsigned)Cond >= CondCodeNodes.size())
1433     CondCodeNodes.resize(Cond+1);
1434
1435   if (!CondCodeNodes[Cond]) {
1436     CondCodeSDNode *N = new (NodeAllocator) CondCodeSDNode(Cond);
1437     CondCodeNodes[Cond] = N;
1438     InsertNode(N);
1439   }
1440
1441   return SDValue(CondCodeNodes[Cond], 0);
1442 }
1443
1444 // commuteShuffle - swaps the values of N1 and N2, and swaps all indices in
1445 // the shuffle mask M that point at N1 to point at N2, and indices that point
1446 // N2 to point at N1.
1447 static void commuteShuffle(SDValue &N1, SDValue &N2, SmallVectorImpl<int> &M) {
1448   std::swap(N1, N2);
1449   int NElts = M.size();
1450   for (int i = 0; i != NElts; ++i) {
1451     if (M[i] >= NElts)
1452       M[i] -= NElts;
1453     else if (M[i] >= 0)
1454       M[i] += NElts;
1455   }
1456 }
1457
1458 SDValue SelectionDAG::getVectorShuffle(EVT VT, SDLoc dl, SDValue N1,
1459                                        SDValue N2, const int *Mask) {
1460   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1461          "Invalid VECTOR_SHUFFLE");
1462
1463   // Canonicalize shuffle undef, undef -> undef
1464   if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() == ISD::UNDEF)
1465     return getUNDEF(VT);
1466
1467   // Validate that all indices in Mask are within the range of the elements
1468   // input to the shuffle.
1469   unsigned NElts = VT.getVectorNumElements();
1470   SmallVector<int, 8> MaskVec;
1471   for (unsigned i = 0; i != NElts; ++i) {
1472     assert(Mask[i] < (int)(NElts * 2) && "Index out of range");
1473     MaskVec.push_back(Mask[i]);
1474   }
1475
1476   // Canonicalize shuffle v, v -> v, undef
1477   if (N1 == N2) {
1478     N2 = getUNDEF(VT);
1479     for (unsigned i = 0; i != NElts; ++i)
1480       if (MaskVec[i] >= (int)NElts) MaskVec[i] -= NElts;
1481   }
1482
1483   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1484   if (N1.getOpcode() == ISD::UNDEF)
1485     commuteShuffle(N1, N2, MaskVec);
1486
1487   // Canonicalize all index into lhs, -> shuffle lhs, undef
1488   // Canonicalize all index into rhs, -> shuffle rhs, undef
1489   bool AllLHS = true, AllRHS = true;
1490   bool N2Undef = N2.getOpcode() == ISD::UNDEF;
1491   for (unsigned i = 0; i != NElts; ++i) {
1492     if (MaskVec[i] >= (int)NElts) {
1493       if (N2Undef)
1494         MaskVec[i] = -1;
1495       else
1496         AllLHS = false;
1497     } else if (MaskVec[i] >= 0) {
1498       AllRHS = false;
1499     }
1500   }
1501   if (AllLHS && AllRHS)
1502     return getUNDEF(VT);
1503   if (AllLHS && !N2Undef)
1504     N2 = getUNDEF(VT);
1505   if (AllRHS) {
1506     N1 = getUNDEF(VT);
1507     commuteShuffle(N1, N2, MaskVec);
1508   }
1509   // Reset our undef status after accounting for the mask.
1510   N2Undef = N2.getOpcode() == ISD::UNDEF;
1511   // Re-check whether both sides ended up undef.
1512   if (N1.getOpcode() == ISD::UNDEF && N2Undef)
1513     return getUNDEF(VT);
1514
1515   // If Identity shuffle return that node.
1516   bool Identity = true, AllSame = true;
1517   for (unsigned i = 0; i != NElts; ++i) {
1518     if (MaskVec[i] >= 0 && MaskVec[i] != (int)i) Identity = false;
1519     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1520   }
1521   if (Identity && NElts)
1522     return N1;
1523
1524   // Shuffling a constant splat doesn't change the result.
1525   if (N2Undef) {
1526     SDValue V = N1;
1527
1528     // Look through any bitcasts. We check that these don't change the number
1529     // (and size) of elements and just changes their types.
1530     while (V.getOpcode() == ISD::BITCAST)
1531       V = V->getOperand(0);
1532
1533     // A splat should always show up as a build vector node.
1534     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1535       BitVector UndefElements;
1536       SDValue Splat = BV->getSplatValue(&UndefElements);
1537       // If this is a splat of an undef, shuffling it is also undef.
1538       if (Splat && Splat.getOpcode() == ISD::UNDEF)
1539         return getUNDEF(VT);
1540
1541       // We only have a splat which can skip shuffles if there is a splatted
1542       // value and no undef lanes rearranged by the shuffle.
1543       if (Splat && UndefElements.none()) {
1544         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1545         // number of elements match or the value splatted is a zero constant.
1546         if (V.getValueType().getVectorNumElements() ==
1547             VT.getVectorNumElements())
1548           return N1;
1549         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1550           if (C->isNullValue())
1551             return N1;
1552       }
1553
1554       // If the shuffle itself creates a constant splat, build the vector
1555       // directly.
1556       if (AllSame) {
1557          const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1558          if (isa<ConstantSDNode>(Splatted) || isa<ConstantFPSDNode>(Splatted)) {
1559            SmallVector<SDValue, 8> Ops;
1560            for (unsigned i = 0; i != NElts; ++i) {
1561              Ops.push_back(Splatted);
1562            }
1563            SDValue NewBV = getNode(ISD::BUILD_VECTOR, dl,
1564              BV->getValueType(0), Ops);
1565
1566            // We may have jumped through bitcasts, so the type of the
1567            // BUILD_VECTOR may not match the type of the shuffle.
1568            if (BV->getValueType(0) != VT)
1569              NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1570            return NewBV;
1571          }
1572       }
1573     }
1574   }
1575
1576   FoldingSetNodeID ID;
1577   SDValue Ops[2] = { N1, N2 };
1578   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1579   for (unsigned i = 0; i != NElts; ++i)
1580     ID.AddInteger(MaskVec[i]);
1581
1582   void* IP = nullptr;
1583   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1584     return SDValue(E, 0);
1585
1586   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1587   // SDNode doesn't have access to it.  This memory will be "leaked" when
1588   // the node is deallocated, but recovered when the NodeAllocator is released.
1589   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1590   memcpy(MaskAlloc, &MaskVec[0], NElts * sizeof(int));
1591
1592   ShuffleVectorSDNode *N =
1593     new (NodeAllocator) ShuffleVectorSDNode(VT, dl.getIROrder(),
1594                                             dl.getDebugLoc(), N1, N2,
1595                                             MaskAlloc);
1596   CSEMap.InsertNode(N, IP);
1597   InsertNode(N);
1598   return SDValue(N, 0);
1599 }
1600
1601 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1602   MVT VT = SV.getSimpleValueType(0);
1603   unsigned NumElems = VT.getVectorNumElements();
1604   SmallVector<int, 8> MaskVec;
1605
1606   for (unsigned i = 0; i != NumElems; ++i) {
1607     int Idx = SV.getMaskElt(i);
1608     if (Idx >= 0) {
1609       if (Idx < (int)NumElems)
1610         Idx += NumElems;
1611       else
1612         Idx -= NumElems;
1613     }
1614     MaskVec.push_back(Idx);
1615   }
1616
1617   SDValue Op0 = SV.getOperand(0);
1618   SDValue Op1 = SV.getOperand(1);
1619   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, &MaskVec[0]);
1620 }
1621
1622 SDValue SelectionDAG::getConvertRndSat(EVT VT, SDLoc dl,
1623                                        SDValue Val, SDValue DTy,
1624                                        SDValue STy, SDValue Rnd, SDValue Sat,
1625                                        ISD::CvtCode Code) {
1626   // If the src and dest types are the same and the conversion is between
1627   // integer types of the same sign or two floats, no conversion is necessary.
1628   if (DTy == STy &&
1629       (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF))
1630     return Val;
1631
1632   FoldingSetNodeID ID;
1633   SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
1634   AddNodeIDNode(ID, ISD::CONVERT_RNDSAT, getVTList(VT), Ops);
1635   void* IP = nullptr;
1636   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1637     return SDValue(E, 0);
1638
1639   CvtRndSatSDNode *N = new (NodeAllocator) CvtRndSatSDNode(VT, dl.getIROrder(),
1640                                                            dl.getDebugLoc(),
1641                                                            Ops, Code);
1642   CSEMap.InsertNode(N, IP);
1643   InsertNode(N);
1644   return SDValue(N, 0);
1645 }
1646
1647 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1648   FoldingSetNodeID ID;
1649   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1650   ID.AddInteger(RegNo);
1651   void *IP = nullptr;
1652   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1653     return SDValue(E, 0);
1654
1655   SDNode *N = new (NodeAllocator) RegisterSDNode(RegNo, VT);
1656   CSEMap.InsertNode(N, IP);
1657   InsertNode(N);
1658   return SDValue(N, 0);
1659 }
1660
1661 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1662   FoldingSetNodeID ID;
1663   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1664   ID.AddPointer(RegMask);
1665   void *IP = nullptr;
1666   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1667     return SDValue(E, 0);
1668
1669   SDNode *N = new (NodeAllocator) RegisterMaskSDNode(RegMask);
1670   CSEMap.InsertNode(N, IP);
1671   InsertNode(N);
1672   return SDValue(N, 0);
1673 }
1674
1675 SDValue SelectionDAG::getEHLabel(SDLoc dl, SDValue Root, MCSymbol *Label) {
1676   FoldingSetNodeID ID;
1677   SDValue Ops[] = { Root };
1678   AddNodeIDNode(ID, ISD::EH_LABEL, getVTList(MVT::Other), Ops);
1679   ID.AddPointer(Label);
1680   void *IP = nullptr;
1681   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1682     return SDValue(E, 0);
1683
1684   SDNode *N = new (NodeAllocator) EHLabelSDNode(dl.getIROrder(),
1685                                                 dl.getDebugLoc(), Root, Label);
1686   CSEMap.InsertNode(N, IP);
1687   InsertNode(N);
1688   return SDValue(N, 0);
1689 }
1690
1691
1692 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1693                                       int64_t Offset,
1694                                       bool isTarget,
1695                                       unsigned char TargetFlags) {
1696   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1697
1698   FoldingSetNodeID ID;
1699   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1700   ID.AddPointer(BA);
1701   ID.AddInteger(Offset);
1702   ID.AddInteger(TargetFlags);
1703   void *IP = nullptr;
1704   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1705     return SDValue(E, 0);
1706
1707   SDNode *N = new (NodeAllocator) BlockAddressSDNode(Opc, VT, BA, Offset,
1708                                                      TargetFlags);
1709   CSEMap.InsertNode(N, IP);
1710   InsertNode(N);
1711   return SDValue(N, 0);
1712 }
1713
1714 SDValue SelectionDAG::getSrcValue(const Value *V) {
1715   assert((!V || V->getType()->isPointerTy()) &&
1716          "SrcValue is not a pointer?");
1717
1718   FoldingSetNodeID ID;
1719   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
1720   ID.AddPointer(V);
1721
1722   void *IP = nullptr;
1723   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1724     return SDValue(E, 0);
1725
1726   SDNode *N = new (NodeAllocator) SrcValueSDNode(V);
1727   CSEMap.InsertNode(N, IP);
1728   InsertNode(N);
1729   return SDValue(N, 0);
1730 }
1731
1732 /// getMDNode - Return an MDNodeSDNode which holds an MDNode.
1733 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1734   FoldingSetNodeID ID;
1735   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
1736   ID.AddPointer(MD);
1737
1738   void *IP = nullptr;
1739   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1740     return SDValue(E, 0);
1741
1742   SDNode *N = new (NodeAllocator) MDNodeSDNode(MD);
1743   CSEMap.InsertNode(N, IP);
1744   InsertNode(N);
1745   return SDValue(N, 0);
1746 }
1747
1748 /// getAddrSpaceCast - Return an AddrSpaceCastSDNode.
1749 SDValue SelectionDAG::getAddrSpaceCast(SDLoc dl, EVT VT, SDValue Ptr,
1750                                        unsigned SrcAS, unsigned DestAS) {
1751   SDValue Ops[] = {Ptr};
1752   FoldingSetNodeID ID;
1753   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
1754   ID.AddInteger(SrcAS);
1755   ID.AddInteger(DestAS);
1756
1757   void *IP = nullptr;
1758   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1759     return SDValue(E, 0);
1760
1761   SDNode *N = new (NodeAllocator) AddrSpaceCastSDNode(dl.getIROrder(),
1762                                                       dl.getDebugLoc(),
1763                                                       VT, Ptr, SrcAS, DestAS);
1764   CSEMap.InsertNode(N, IP);
1765   InsertNode(N);
1766   return SDValue(N, 0);
1767 }
1768
1769 /// getShiftAmountOperand - Return the specified value casted to
1770 /// the target's desired shift amount type.
1771 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1772   EVT OpTy = Op.getValueType();
1773   EVT ShTy = TLI->getShiftAmountTy(LHSTy);
1774   if (OpTy == ShTy || OpTy.isVector()) return Op;
1775
1776   ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ?  ISD::TRUNCATE : ISD::ZERO_EXTEND;
1777   return getNode(Opcode, SDLoc(Op), ShTy, Op);
1778 }
1779
1780 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1781 /// specified value type.
1782 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1783   MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1784   unsigned ByteSize = VT.getStoreSize();
1785   Type *Ty = VT.getTypeForEVT(*getContext());
1786   unsigned StackAlign =
1787   std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty), minAlign);
1788
1789   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
1790   return getFrameIndex(FrameIdx, TLI->getPointerTy());
1791 }
1792
1793 /// CreateStackTemporary - Create a stack temporary suitable for holding
1794 /// either of the specified value types.
1795 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1796   unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
1797                             VT2.getStoreSizeInBits())/8;
1798   Type *Ty1 = VT1.getTypeForEVT(*getContext());
1799   Type *Ty2 = VT2.getTypeForEVT(*getContext());
1800   const DataLayout *TD = TLI->getDataLayout();
1801   unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
1802                             TD->getPrefTypeAlignment(Ty2));
1803
1804   MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1805   int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align, false);
1806   return getFrameIndex(FrameIdx, TLI->getPointerTy());
1807 }
1808
1809 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1,
1810                                 SDValue N2, ISD::CondCode Cond, SDLoc dl) {
1811   // These setcc operations always fold.
1812   switch (Cond) {
1813   default: break;
1814   case ISD::SETFALSE:
1815   case ISD::SETFALSE2: return getConstant(0, VT);
1816   case ISD::SETTRUE:
1817   case ISD::SETTRUE2: {
1818     TargetLowering::BooleanContent Cnt =
1819         TLI->getBooleanContents(N1->getValueType(0));
1820     return getConstant(
1821         Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, VT);
1822   }
1823
1824   case ISD::SETOEQ:
1825   case ISD::SETOGT:
1826   case ISD::SETOGE:
1827   case ISD::SETOLT:
1828   case ISD::SETOLE:
1829   case ISD::SETONE:
1830   case ISD::SETO:
1831   case ISD::SETUO:
1832   case ISD::SETUEQ:
1833   case ISD::SETUNE:
1834     assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1835     break;
1836   }
1837
1838   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
1839     const APInt &C2 = N2C->getAPIntValue();
1840     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1841       const APInt &C1 = N1C->getAPIntValue();
1842
1843       switch (Cond) {
1844       default: llvm_unreachable("Unknown integer setcc!");
1845       case ISD::SETEQ:  return getConstant(C1 == C2, VT);
1846       case ISD::SETNE:  return getConstant(C1 != C2, VT);
1847       case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1848       case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1849       case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1850       case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1851       case ISD::SETLT:  return getConstant(C1.slt(C2), VT);
1852       case ISD::SETGT:  return getConstant(C1.sgt(C2), VT);
1853       case ISD::SETLE:  return getConstant(C1.sle(C2), VT);
1854       case ISD::SETGE:  return getConstant(C1.sge(C2), VT);
1855       }
1856     }
1857   }
1858   if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1859     if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
1860       APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1861       switch (Cond) {
1862       default: break;
1863       case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
1864                           return getUNDEF(VT);
1865                         // fall through
1866       case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1867       case ISD::SETNE:  if (R==APFloat::cmpUnordered)
1868                           return getUNDEF(VT);
1869                         // fall through
1870       case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1871                                            R==APFloat::cmpLessThan, VT);
1872       case ISD::SETLT:  if (R==APFloat::cmpUnordered)
1873                           return getUNDEF(VT);
1874                         // fall through
1875       case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1876       case ISD::SETGT:  if (R==APFloat::cmpUnordered)
1877                           return getUNDEF(VT);
1878                         // fall through
1879       case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1880       case ISD::SETLE:  if (R==APFloat::cmpUnordered)
1881                           return getUNDEF(VT);
1882                         // fall through
1883       case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1884                                            R==APFloat::cmpEqual, VT);
1885       case ISD::SETGE:  if (R==APFloat::cmpUnordered)
1886                           return getUNDEF(VT);
1887                         // fall through
1888       case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1889                                            R==APFloat::cmpEqual, VT);
1890       case ISD::SETO:   return getConstant(R!=APFloat::cmpUnordered, VT);
1891       case ISD::SETUO:  return getConstant(R==APFloat::cmpUnordered, VT);
1892       case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1893                                            R==APFloat::cmpEqual, VT);
1894       case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1895       case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1896                                            R==APFloat::cmpLessThan, VT);
1897       case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1898                                            R==APFloat::cmpUnordered, VT);
1899       case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1900       case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1901       }
1902     } else {
1903       // Ensure that the constant occurs on the RHS.
1904       ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
1905       MVT CompVT = N1.getValueType().getSimpleVT();
1906       if (!TLI->isCondCodeLegal(SwappedCond, CompVT))
1907         return SDValue();
1908
1909       return getSetCC(dl, VT, N2, N1, SwappedCond);
1910     }
1911   }
1912
1913   // Could not fold it.
1914   return SDValue();
1915 }
1916
1917 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
1918 /// use this predicate to simplify operations downstream.
1919 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1920   // This predicate is not safe for vector operations.
1921   if (Op.getValueType().isVector())
1922     return false;
1923
1924   unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
1925   return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1926 }
1927
1928 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1929 /// this predicate to simplify operations downstream.  Mask is known to be zero
1930 /// for bits that V cannot have.
1931 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1932                                      unsigned Depth) const {
1933   APInt KnownZero, KnownOne;
1934   computeKnownBits(Op, KnownZero, KnownOne, Depth);
1935   return (KnownZero & Mask) == Mask;
1936 }
1937
1938 /// Determine which bits of Op are known to be either zero or one and return
1939 /// them in the KnownZero/KnownOne bitsets.
1940 void SelectionDAG::computeKnownBits(SDValue Op, APInt &KnownZero,
1941                                     APInt &KnownOne, unsigned Depth) const {
1942   unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
1943
1944   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
1945   if (Depth == 6)
1946     return;  // Limit search depth.
1947
1948   APInt KnownZero2, KnownOne2;
1949
1950   switch (Op.getOpcode()) {
1951   case ISD::Constant:
1952     // We know all of the bits for a constant!
1953     KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
1954     KnownZero = ~KnownOne;
1955     break;
1956   case ISD::AND:
1957     // If either the LHS or the RHS are Zero, the result is zero.
1958     computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1959     computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1960
1961     // Output known-1 bits are only known if set in both the LHS & RHS.
1962     KnownOne &= KnownOne2;
1963     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1964     KnownZero |= KnownZero2;
1965     break;
1966   case ISD::OR:
1967     computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1968     computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1969
1970     // Output known-0 bits are only known if clear in both the LHS & RHS.
1971     KnownZero &= KnownZero2;
1972     // Output known-1 are known to be set if set in either the LHS | RHS.
1973     KnownOne |= KnownOne2;
1974     break;
1975   case ISD::XOR: {
1976     computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1977     computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1978
1979     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1980     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1981     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1982     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1983     KnownZero = KnownZeroOut;
1984     break;
1985   }
1986   case ISD::MUL: {
1987     computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1988     computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1989
1990     // If low bits are zero in either operand, output low known-0 bits.
1991     // Also compute a conserative estimate for high known-0 bits.
1992     // More trickiness is possible, but this is sufficient for the
1993     // interesting case of alignment computation.
1994     KnownOne.clearAllBits();
1995     unsigned TrailZ = KnownZero.countTrailingOnes() +
1996                       KnownZero2.countTrailingOnes();
1997     unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
1998                                KnownZero2.countLeadingOnes(),
1999                                BitWidth) - BitWidth;
2000
2001     TrailZ = std::min(TrailZ, BitWidth);
2002     LeadZ = std::min(LeadZ, BitWidth);
2003     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
2004                 APInt::getHighBitsSet(BitWidth, LeadZ);
2005     break;
2006   }
2007   case ISD::UDIV: {
2008     // For the purposes of computing leading zeros we can conservatively
2009     // treat a udiv as a logical right shift by the power of 2 known to
2010     // be less than the denominator.
2011     computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
2012     unsigned LeadZ = KnownZero2.countLeadingOnes();
2013
2014     KnownOne2.clearAllBits();
2015     KnownZero2.clearAllBits();
2016     computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2017     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
2018     if (RHSUnknownLeadingOnes != BitWidth)
2019       LeadZ = std::min(BitWidth,
2020                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
2021
2022     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
2023     break;
2024   }
2025   case ISD::SELECT:
2026     computeKnownBits(Op.getOperand(2), KnownZero, KnownOne, Depth+1);
2027     computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2028
2029     // Only known if known in both the LHS and RHS.
2030     KnownOne &= KnownOne2;
2031     KnownZero &= KnownZero2;
2032     break;
2033   case ISD::SELECT_CC:
2034     computeKnownBits(Op.getOperand(3), KnownZero, KnownOne, Depth+1);
2035     computeKnownBits(Op.getOperand(2), KnownZero2, KnownOne2, Depth+1);
2036
2037     // Only known if known in both the LHS and RHS.
2038     KnownOne &= KnownOne2;
2039     KnownZero &= KnownZero2;
2040     break;
2041   case ISD::SADDO:
2042   case ISD::UADDO:
2043   case ISD::SSUBO:
2044   case ISD::USUBO:
2045   case ISD::SMULO:
2046   case ISD::UMULO:
2047     if (Op.getResNo() != 1)
2048       break;
2049     // The boolean result conforms to getBooleanContents.
2050     // If we know the result of a setcc has the top bits zero, use this info.
2051     // We know that we have an integer-based boolean since these operations
2052     // are only available for integer.
2053     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2054             TargetLowering::ZeroOrOneBooleanContent &&
2055         BitWidth > 1)
2056       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
2057     break;
2058   case ISD::SETCC:
2059     // If we know the result of a setcc has the top bits zero, use this info.
2060     if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2061             TargetLowering::ZeroOrOneBooleanContent &&
2062         BitWidth > 1)
2063       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
2064     break;
2065   case ISD::SHL:
2066     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
2067     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2068       unsigned ShAmt = SA->getZExtValue();
2069
2070       // If the shift count is an invalid immediate, don't do anything.
2071       if (ShAmt >= BitWidth)
2072         break;
2073
2074       computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2075       KnownZero <<= ShAmt;
2076       KnownOne  <<= ShAmt;
2077       // low bits known zero.
2078       KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
2079     }
2080     break;
2081   case ISD::SRL:
2082     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
2083     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2084       unsigned ShAmt = SA->getZExtValue();
2085
2086       // If the shift count is an invalid immediate, don't do anything.
2087       if (ShAmt >= BitWidth)
2088         break;
2089
2090       computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2091       KnownZero = KnownZero.lshr(ShAmt);
2092       KnownOne  = KnownOne.lshr(ShAmt);
2093
2094       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
2095       KnownZero |= HighBits;  // High bits known zero.
2096     }
2097     break;
2098   case ISD::SRA:
2099     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2100       unsigned ShAmt = SA->getZExtValue();
2101
2102       // If the shift count is an invalid immediate, don't do anything.
2103       if (ShAmt >= BitWidth)
2104         break;
2105
2106       // If any of the demanded bits are produced by the sign extension, we also
2107       // demand the input sign bit.
2108       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
2109
2110       computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2111       KnownZero = KnownZero.lshr(ShAmt);
2112       KnownOne  = KnownOne.lshr(ShAmt);
2113
2114       // Handle the sign bits.
2115       APInt SignBit = APInt::getSignBit(BitWidth);
2116       SignBit = SignBit.lshr(ShAmt);  // Adjust to where it is now in the mask.
2117
2118       if (KnownZero.intersects(SignBit)) {
2119         KnownZero |= HighBits;  // New bits are known zero.
2120       } else if (KnownOne.intersects(SignBit)) {
2121         KnownOne  |= HighBits;  // New bits are known one.
2122       }
2123     }
2124     break;
2125   case ISD::SIGN_EXTEND_INREG: {
2126     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2127     unsigned EBits = EVT.getScalarType().getSizeInBits();
2128
2129     // Sign extension.  Compute the demanded bits in the result that are not
2130     // present in the input.
2131     APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
2132
2133     APInt InSignBit = APInt::getSignBit(EBits);
2134     APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
2135
2136     // If the sign extended bits are demanded, we know that the sign
2137     // bit is demanded.
2138     InSignBit = InSignBit.zext(BitWidth);
2139     if (NewBits.getBoolValue())
2140       InputDemandedBits |= InSignBit;
2141
2142     computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2143     KnownOne &= InputDemandedBits;
2144     KnownZero &= InputDemandedBits;
2145
2146     // If the sign bit of the input is known set or clear, then we know the
2147     // top bits of the result.
2148     if (KnownZero.intersects(InSignBit)) {         // Input sign bit known clear
2149       KnownZero |= NewBits;
2150       KnownOne  &= ~NewBits;
2151     } else if (KnownOne.intersects(InSignBit)) {   // Input sign bit known set
2152       KnownOne  |= NewBits;
2153       KnownZero &= ~NewBits;
2154     } else {                              // Input sign bit unknown
2155       KnownZero &= ~NewBits;
2156       KnownOne  &= ~NewBits;
2157     }
2158     break;
2159   }
2160   case ISD::CTTZ:
2161   case ISD::CTTZ_ZERO_UNDEF:
2162   case ISD::CTLZ:
2163   case ISD::CTLZ_ZERO_UNDEF:
2164   case ISD::CTPOP: {
2165     unsigned LowBits = Log2_32(BitWidth)+1;
2166     KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
2167     KnownOne.clearAllBits();
2168     break;
2169   }
2170   case ISD::LOAD: {
2171     LoadSDNode *LD = cast<LoadSDNode>(Op);
2172     // If this is a ZEXTLoad and we are looking at the loaded value.
2173     if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
2174       EVT VT = LD->getMemoryVT();
2175       unsigned MemBits = VT.getScalarType().getSizeInBits();
2176       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
2177     } else if (const MDNode *Ranges = LD->getRanges()) {
2178       computeKnownBitsFromRangeMetadata(*Ranges, KnownZero);
2179     }
2180     break;
2181   }
2182   case ISD::ZERO_EXTEND: {
2183     EVT InVT = Op.getOperand(0).getValueType();
2184     unsigned InBits = InVT.getScalarType().getSizeInBits();
2185     APInt NewBits   = APInt::getHighBitsSet(BitWidth, BitWidth - InBits);
2186     KnownZero = KnownZero.trunc(InBits);
2187     KnownOne = KnownOne.trunc(InBits);
2188     computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2189     KnownZero = KnownZero.zext(BitWidth);
2190     KnownOne = KnownOne.zext(BitWidth);
2191     KnownZero |= NewBits;
2192     break;
2193   }
2194   case ISD::SIGN_EXTEND: {
2195     EVT InVT = Op.getOperand(0).getValueType();
2196     unsigned InBits = InVT.getScalarType().getSizeInBits();
2197     APInt NewBits   = APInt::getHighBitsSet(BitWidth, BitWidth - InBits);
2198
2199     KnownZero = KnownZero.trunc(InBits);
2200     KnownOne = KnownOne.trunc(InBits);
2201     computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2202
2203     // Note if the sign bit is known to be zero or one.
2204     bool SignBitKnownZero = KnownZero.isNegative();
2205     bool SignBitKnownOne  = KnownOne.isNegative();
2206
2207     KnownZero = KnownZero.zext(BitWidth);
2208     KnownOne = KnownOne.zext(BitWidth);
2209
2210     // If the sign bit is known zero or one, the top bits match.
2211     if (SignBitKnownZero)
2212       KnownZero |= NewBits;
2213     else if (SignBitKnownOne)
2214       KnownOne  |= NewBits;
2215     break;
2216   }
2217   case ISD::ANY_EXTEND: {
2218     EVT InVT = Op.getOperand(0).getValueType();
2219     unsigned InBits = InVT.getScalarType().getSizeInBits();
2220     KnownZero = KnownZero.trunc(InBits);
2221     KnownOne = KnownOne.trunc(InBits);
2222     computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2223     KnownZero = KnownZero.zext(BitWidth);
2224     KnownOne = KnownOne.zext(BitWidth);
2225     break;
2226   }
2227   case ISD::TRUNCATE: {
2228     EVT InVT = Op.getOperand(0).getValueType();
2229     unsigned InBits = InVT.getScalarType().getSizeInBits();
2230     KnownZero = KnownZero.zext(InBits);
2231     KnownOne = KnownOne.zext(InBits);
2232     computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2233     KnownZero = KnownZero.trunc(BitWidth);
2234     KnownOne = KnownOne.trunc(BitWidth);
2235     break;
2236   }
2237   case ISD::AssertZext: {
2238     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2239     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
2240     computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2241     KnownZero |= (~InMask);
2242     KnownOne  &= (~KnownZero);
2243     break;
2244   }
2245   case ISD::FGETSIGN:
2246     // All bits are zero except the low bit.
2247     KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
2248     break;
2249
2250   case ISD::SUB: {
2251     if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
2252       // We know that the top bits of C-X are clear if X contains less bits
2253       // than C (i.e. no wrap-around can happen).  For example, 20-X is
2254       // positive if we can prove that X is >= 0 and < 16.
2255       if (CLHS->getAPIntValue().isNonNegative()) {
2256         unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
2257         // NLZ can't be BitWidth with no sign bit
2258         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
2259         computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2260
2261         // If all of the MaskV bits are known to be zero, then we know the
2262         // output top bits are zero, because we now know that the output is
2263         // from [0-C].
2264         if ((KnownZero2 & MaskV) == MaskV) {
2265           unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
2266           // Top bits known zero.
2267           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
2268         }
2269       }
2270     }
2271   }
2272   // fall through
2273   case ISD::ADD:
2274   case ISD::ADDE: {
2275     // Output known-0 bits are known if clear or set in both the low clear bits
2276     // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
2277     // low 3 bits clear.
2278     computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
2279     unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
2280
2281     computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2282     KnownZeroOut = std::min(KnownZeroOut,
2283                             KnownZero2.countTrailingOnes());
2284
2285     if (Op.getOpcode() == ISD::ADD) {
2286       KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
2287       break;
2288     }
2289
2290     // With ADDE, a carry bit may be added in, so we can only use this
2291     // information if we know (at least) that the low two bits are clear.  We
2292     // then return to the caller that the low bit is unknown but that other bits
2293     // are known zero.
2294     if (KnownZeroOut >= 2) // ADDE
2295       KnownZero |= APInt::getBitsSet(BitWidth, 1, KnownZeroOut);
2296     break;
2297   }
2298   case ISD::SREM:
2299     if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2300       const APInt &RA = Rem->getAPIntValue().abs();
2301       if (RA.isPowerOf2()) {
2302         APInt LowBits = RA - 1;
2303         computeKnownBits(Op.getOperand(0), KnownZero2,KnownOne2,Depth+1);
2304
2305         // The low bits of the first operand are unchanged by the srem.
2306         KnownZero = KnownZero2 & LowBits;
2307         KnownOne = KnownOne2 & LowBits;
2308
2309         // If the first operand is non-negative or has all low bits zero, then
2310         // the upper bits are all zero.
2311         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
2312           KnownZero |= ~LowBits;
2313
2314         // If the first operand is negative and not all low bits are zero, then
2315         // the upper bits are all one.
2316         if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
2317           KnownOne |= ~LowBits;
2318         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
2319       }
2320     }
2321     break;
2322   case ISD::UREM: {
2323     if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2324       const APInt &RA = Rem->getAPIntValue();
2325       if (RA.isPowerOf2()) {
2326         APInt LowBits = (RA - 1);
2327         computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth + 1);
2328
2329         // The upper bits are all zero, the lower ones are unchanged.
2330         KnownZero = KnownZero2 | ~LowBits;
2331         KnownOne = KnownOne2 & LowBits;
2332         break;
2333       }
2334     }
2335
2336     // Since the result is less than or equal to either operand, any leading
2337     // zero bits in either operand must also exist in the result.
2338     computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2339     computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2340
2341     uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
2342                                 KnownZero2.countLeadingOnes());
2343     KnownOne.clearAllBits();
2344     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
2345     break;
2346   }
2347   case ISD::FrameIndex:
2348   case ISD::TargetFrameIndex:
2349     if (unsigned Align = InferPtrAlignment(Op)) {
2350       // The low bits are known zero if the pointer is aligned.
2351       KnownZero = APInt::getLowBitsSet(BitWidth, Log2_32(Align));
2352       break;
2353     }
2354     break;
2355
2356   default:
2357     if (Op.getOpcode() < ISD::BUILTIN_OP_END)
2358       break;
2359     // Fallthrough
2360   case ISD::INTRINSIC_WO_CHAIN:
2361   case ISD::INTRINSIC_W_CHAIN:
2362   case ISD::INTRINSIC_VOID:
2363     // Allow the target to implement this method for its nodes.
2364     TLI->computeKnownBitsForTargetNode(Op, KnownZero, KnownOne, *this, Depth);
2365     break;
2366   }
2367
2368   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
2369 }
2370
2371 /// ComputeNumSignBits - Return the number of times the sign bit of the
2372 /// register is replicated into the other bits.  We know that at least 1 bit
2373 /// is always equal to the sign bit (itself), but other cases can give us
2374 /// information.  For example, immediately after an "SRA X, 2", we know that
2375 /// the top 3 bits are all equal to each other, so we return 3.
2376 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
2377   EVT VT = Op.getValueType();
2378   assert(VT.isInteger() && "Invalid VT!");
2379   unsigned VTBits = VT.getScalarType().getSizeInBits();
2380   unsigned Tmp, Tmp2;
2381   unsigned FirstAnswer = 1;
2382
2383   if (Depth == 6)
2384     return 1;  // Limit search depth.
2385
2386   switch (Op.getOpcode()) {
2387   default: break;
2388   case ISD::AssertSext:
2389     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2390     return VTBits-Tmp+1;
2391   case ISD::AssertZext:
2392     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2393     return VTBits-Tmp;
2394
2395   case ISD::Constant: {
2396     const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2397     return Val.getNumSignBits();
2398   }
2399
2400   case ISD::SIGN_EXTEND:
2401     Tmp =
2402         VTBits-Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
2403     return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2404
2405   case ISD::SIGN_EXTEND_INREG:
2406     // Max of the input and what this extends.
2407     Tmp =
2408       cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarType().getSizeInBits();
2409     Tmp = VTBits-Tmp+1;
2410
2411     Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2412     return std::max(Tmp, Tmp2);
2413
2414   case ISD::SRA:
2415     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2416     // SRA X, C   -> adds C sign bits.
2417     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2418       Tmp += C->getZExtValue();
2419       if (Tmp > VTBits) Tmp = VTBits;
2420     }
2421     return Tmp;
2422   case ISD::SHL:
2423     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2424       // shl destroys sign bits.
2425       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2426       if (C->getZExtValue() >= VTBits ||      // Bad shift.
2427           C->getZExtValue() >= Tmp) break;    // Shifted all sign bits out.
2428       return Tmp - C->getZExtValue();
2429     }
2430     break;
2431   case ISD::AND:
2432   case ISD::OR:
2433   case ISD::XOR:    // NOT is handled here.
2434     // Logical binary ops preserve the number of sign bits at the worst.
2435     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2436     if (Tmp != 1) {
2437       Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2438       FirstAnswer = std::min(Tmp, Tmp2);
2439       // We computed what we know about the sign bits as our first
2440       // answer. Now proceed to the generic code that uses
2441       // computeKnownBits, and pick whichever answer is better.
2442     }
2443     break;
2444
2445   case ISD::SELECT:
2446     Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2447     if (Tmp == 1) return 1;  // Early out.
2448     Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2449     return std::min(Tmp, Tmp2);
2450
2451   case ISD::SADDO:
2452   case ISD::UADDO:
2453   case ISD::SSUBO:
2454   case ISD::USUBO:
2455   case ISD::SMULO:
2456   case ISD::UMULO:
2457     if (Op.getResNo() != 1)
2458       break;
2459     // The boolean result conforms to getBooleanContents.  Fall through.
2460     // If setcc returns 0/-1, all bits are sign bits.
2461     // We know that we have an integer-based boolean since these operations
2462     // are only available for integer.
2463     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2464         TargetLowering::ZeroOrNegativeOneBooleanContent)
2465       return VTBits;
2466     break;
2467   case ISD::SETCC:
2468     // If setcc returns 0/-1, all bits are sign bits.
2469     if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2470         TargetLowering::ZeroOrNegativeOneBooleanContent)
2471       return VTBits;
2472     break;
2473   case ISD::ROTL:
2474   case ISD::ROTR:
2475     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2476       unsigned RotAmt = C->getZExtValue() & (VTBits-1);
2477
2478       // Handle rotate right by N like a rotate left by 32-N.
2479       if (Op.getOpcode() == ISD::ROTR)
2480         RotAmt = (VTBits-RotAmt) & (VTBits-1);
2481
2482       // If we aren't rotating out all of the known-in sign bits, return the
2483       // number that are left.  This handles rotl(sext(x), 1) for example.
2484       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2485       if (Tmp > RotAmt+1) return Tmp-RotAmt;
2486     }
2487     break;
2488   case ISD::ADD:
2489     // Add can have at most one carry bit.  Thus we know that the output
2490     // is, at worst, one more bit than the inputs.
2491     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2492     if (Tmp == 1) return 1;  // Early out.
2493
2494     // Special case decrementing a value (ADD X, -1):
2495     if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2496       if (CRHS->isAllOnesValue()) {
2497         APInt KnownZero, KnownOne;
2498         computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2499
2500         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2501         // sign bits set.
2502         if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue())
2503           return VTBits;
2504
2505         // If we are subtracting one from a positive number, there is no carry
2506         // out of the result.
2507         if (KnownZero.isNegative())
2508           return Tmp;
2509       }
2510
2511     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2512     if (Tmp2 == 1) return 1;
2513     return std::min(Tmp, Tmp2)-1;
2514
2515   case ISD::SUB:
2516     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2517     if (Tmp2 == 1) return 1;
2518
2519     // Handle NEG.
2520     if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2521       if (CLHS->isNullValue()) {
2522         APInt KnownZero, KnownOne;
2523         computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
2524         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2525         // sign bits set.
2526         if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue())
2527           return VTBits;
2528
2529         // If the input is known to be positive (the sign bit is known clear),
2530         // the output of the NEG has the same number of sign bits as the input.
2531         if (KnownZero.isNegative())
2532           return Tmp2;
2533
2534         // Otherwise, we treat this like a SUB.
2535       }
2536
2537     // Sub can have at most one carry bit.  Thus we know that the output
2538     // is, at worst, one more bit than the inputs.
2539     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2540     if (Tmp == 1) return 1;  // Early out.
2541     return std::min(Tmp, Tmp2)-1;
2542   case ISD::TRUNCATE:
2543     // FIXME: it's tricky to do anything useful for this, but it is an important
2544     // case for targets like X86.
2545     break;
2546   }
2547
2548   // If we are looking at the loaded value of the SDNode.
2549   if (Op.getResNo() == 0) {
2550     // Handle LOADX separately here. EXTLOAD case will fallthrough.
2551     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
2552       unsigned ExtType = LD->getExtensionType();
2553       switch (ExtType) {
2554         default: break;
2555         case ISD::SEXTLOAD:    // '17' bits known
2556           Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
2557           return VTBits-Tmp+1;
2558         case ISD::ZEXTLOAD:    // '16' bits known
2559           Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
2560           return VTBits-Tmp;
2561       }
2562     }
2563   }
2564
2565   // Allow the target to implement this method for its nodes.
2566   if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2567       Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2568       Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2569       Op.getOpcode() == ISD::INTRINSIC_VOID) {
2570     unsigned NumBits = TLI->ComputeNumSignBitsForTargetNode(Op, *this, Depth);
2571     if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2572   }
2573
2574   // Finally, if we can prove that the top bits of the result are 0's or 1's,
2575   // use this information.
2576   APInt KnownZero, KnownOne;
2577   computeKnownBits(Op, KnownZero, KnownOne, Depth);
2578
2579   APInt Mask;
2580   if (KnownZero.isNegative()) {        // sign bit is 0
2581     Mask = KnownZero;
2582   } else if (KnownOne.isNegative()) {  // sign bit is 1;
2583     Mask = KnownOne;
2584   } else {
2585     // Nothing known.
2586     return FirstAnswer;
2587   }
2588
2589   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
2590   // the number of identical bits in the top of the input value.
2591   Mask = ~Mask;
2592   Mask <<= Mask.getBitWidth()-VTBits;
2593   // Return # leading zeros.  We use 'min' here in case Val was zero before
2594   // shifting.  We don't want to return '64' as for an i32 "0".
2595   return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2596 }
2597
2598 /// isBaseWithConstantOffset - Return true if the specified operand is an
2599 /// ISD::ADD with a ConstantSDNode on the right-hand side, or if it is an
2600 /// ISD::OR with a ConstantSDNode that is guaranteed to have the same
2601 /// semantics as an ADD.  This handles the equivalence:
2602 ///     X|Cst == X+Cst iff X&Cst = 0.
2603 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
2604   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
2605       !isa<ConstantSDNode>(Op.getOperand(1)))
2606     return false;
2607
2608   if (Op.getOpcode() == ISD::OR &&
2609       !MaskedValueIsZero(Op.getOperand(0),
2610                      cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue()))
2611     return false;
2612
2613   return true;
2614 }
2615
2616
2617 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
2618   // If we're told that NaNs won't happen, assume they won't.
2619   if (getTarget().Options.NoNaNsFPMath)
2620     return true;
2621
2622   // If the value is a constant, we can obviously see if it is a NaN or not.
2623   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2624     return !C->getValueAPF().isNaN();
2625
2626   // TODO: Recognize more cases here.
2627
2628   return false;
2629 }
2630
2631 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
2632   // If the value is a constant, we can obviously see if it is a zero or not.
2633   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2634     return !C->isZero();
2635
2636   // TODO: Recognize more cases here.
2637   switch (Op.getOpcode()) {
2638   default: break;
2639   case ISD::OR:
2640     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2641       return !C->isNullValue();
2642     break;
2643   }
2644
2645   return false;
2646 }
2647
2648 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
2649   // Check the obvious case.
2650   if (A == B) return true;
2651
2652   // For for negative and positive zero.
2653   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
2654     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
2655       if (CA->isZero() && CB->isZero()) return true;
2656
2657   // Otherwise they may not be equal.
2658   return false;
2659 }
2660
2661 /// getNode - Gets or creates the specified node.
2662 ///
2663 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT) {
2664   FoldingSetNodeID ID;
2665   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
2666   void *IP = nullptr;
2667   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2668     return SDValue(E, 0);
2669
2670   SDNode *N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(),
2671                                          DL.getDebugLoc(), getVTList(VT));
2672   CSEMap.InsertNode(N, IP);
2673
2674   InsertNode(N);
2675   return SDValue(N, 0);
2676 }
2677
2678 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL,
2679                               EVT VT, SDValue Operand) {
2680   // Constant fold unary operations with an integer constant operand. Even
2681   // opaque constant will be folded, because the folding of unary operations
2682   // doesn't create new constants with different values. Nevertheless, the
2683   // opaque flag is preserved during folding to prevent future folding with
2684   // other constants.
2685   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2686     const APInt &Val = C->getAPIntValue();
2687     switch (Opcode) {
2688     default: break;
2689     case ISD::SIGN_EXTEND:
2690       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), VT,
2691                          C->isTargetOpcode(), C->isOpaque());
2692     case ISD::ANY_EXTEND:
2693     case ISD::ZERO_EXTEND:
2694     case ISD::TRUNCATE:
2695       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), VT,
2696                          C->isTargetOpcode(), C->isOpaque());
2697     case ISD::UINT_TO_FP:
2698     case ISD::SINT_TO_FP: {
2699       APFloat apf(EVTToAPFloatSemantics(VT),
2700                   APInt::getNullValue(VT.getSizeInBits()));
2701       (void)apf.convertFromAPInt(Val,
2702                                  Opcode==ISD::SINT_TO_FP,
2703                                  APFloat::rmNearestTiesToEven);
2704       return getConstantFP(apf, VT);
2705     }
2706     case ISD::BITCAST:
2707       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
2708         return getConstantFP(APFloat(APFloat::IEEEhalf, Val), VT);
2709       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2710         return getConstantFP(APFloat(APFloat::IEEEsingle, Val), VT);
2711       else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2712         return getConstantFP(APFloat(APFloat::IEEEdouble, Val), VT);
2713       break;
2714     case ISD::BSWAP:
2715       return getConstant(Val.byteSwap(), VT, C->isTargetOpcode(),
2716                          C->isOpaque());
2717     case ISD::CTPOP:
2718       return getConstant(Val.countPopulation(), VT, C->isTargetOpcode(),
2719                          C->isOpaque());
2720     case ISD::CTLZ:
2721     case ISD::CTLZ_ZERO_UNDEF:
2722       return getConstant(Val.countLeadingZeros(), VT, C->isTargetOpcode(),
2723                          C->isOpaque());
2724     case ISD::CTTZ:
2725     case ISD::CTTZ_ZERO_UNDEF:
2726       return getConstant(Val.countTrailingZeros(), VT, C->isTargetOpcode(),
2727                          C->isOpaque());
2728     }
2729   }
2730
2731   // Constant fold unary operations with a floating point constant operand.
2732   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2733     APFloat V = C->getValueAPF();    // make copy
2734     switch (Opcode) {
2735     case ISD::FNEG:
2736       V.changeSign();
2737       return getConstantFP(V, VT);
2738     case ISD::FABS:
2739       V.clearSign();
2740       return getConstantFP(V, VT);
2741     case ISD::FCEIL: {
2742       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
2743       if (fs == APFloat::opOK || fs == APFloat::opInexact)
2744         return getConstantFP(V, VT);
2745       break;
2746     }
2747     case ISD::FTRUNC: {
2748       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
2749       if (fs == APFloat::opOK || fs == APFloat::opInexact)
2750         return getConstantFP(V, VT);
2751       break;
2752     }
2753     case ISD::FFLOOR: {
2754       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
2755       if (fs == APFloat::opOK || fs == APFloat::opInexact)
2756         return getConstantFP(V, VT);
2757       break;
2758     }
2759     case ISD::FP_EXTEND: {
2760       bool ignored;
2761       // This can return overflow, underflow, or inexact; we don't care.
2762       // FIXME need to be more flexible about rounding mode.
2763       (void)V.convert(EVTToAPFloatSemantics(VT),
2764                       APFloat::rmNearestTiesToEven, &ignored);
2765       return getConstantFP(V, VT);
2766     }
2767     case ISD::FP_TO_SINT:
2768     case ISD::FP_TO_UINT: {
2769       integerPart x[2];
2770       bool ignored;
2771       static_assert(integerPartWidth >= 64, "APFloat parts too small!");
2772       // FIXME need to be more flexible about rounding mode.
2773       APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(),
2774                             Opcode==ISD::FP_TO_SINT,
2775                             APFloat::rmTowardZero, &ignored);
2776       if (s==APFloat::opInvalidOp)     // inexact is OK, in fact usual
2777         break;
2778       APInt api(VT.getSizeInBits(), x);
2779       return getConstant(api, VT);
2780     }
2781     case ISD::BITCAST:
2782       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
2783         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), VT);
2784       else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2785         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
2786       else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2787         return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
2788       break;
2789     }
2790   }
2791
2792   // Constant fold unary operations with a vector integer operand.
2793   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand.getNode())) {
2794     if (BV->isConstant()) {
2795       switch (Opcode) {
2796       default:
2797         // FIXME: Entirely reasonable to perform folding of other unary
2798         // operations here as the need arises.
2799         break;
2800       case ISD::UINT_TO_FP:
2801       case ISD::SINT_TO_FP: {
2802         SmallVector<SDValue, 8> Ops;
2803         for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
2804           SDValue OpN = BV->getOperand(i);
2805           // Let the above scalar folding handle the conversion of each
2806           // element.
2807           OpN = getNode(ISD::SINT_TO_FP, DL, VT.getVectorElementType(),
2808                         OpN);
2809           Ops.push_back(OpN);
2810         }
2811         return getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
2812       }
2813       }
2814     }
2815   }
2816
2817   unsigned OpOpcode = Operand.getNode()->getOpcode();
2818   switch (Opcode) {
2819   case ISD::TokenFactor:
2820   case ISD::MERGE_VALUES:
2821   case ISD::CONCAT_VECTORS:
2822     return Operand;         // Factor, merge or concat of one node?  No need.
2823   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
2824   case ISD::FP_EXTEND:
2825     assert(VT.isFloatingPoint() &&
2826            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2827     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
2828     assert((!VT.isVector() ||
2829             VT.getVectorNumElements() ==
2830             Operand.getValueType().getVectorNumElements()) &&
2831            "Vector element count mismatch!");
2832     if (Operand.getOpcode() == ISD::UNDEF)
2833       return getUNDEF(VT);
2834     break;
2835   case ISD::SIGN_EXTEND:
2836     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2837            "Invalid SIGN_EXTEND!");
2838     if (Operand.getValueType() == VT) return Operand;   // noop extension
2839     assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2840            "Invalid sext node, dst < src!");
2841     assert((!VT.isVector() ||
2842             VT.getVectorNumElements() ==
2843             Operand.getValueType().getVectorNumElements()) &&
2844            "Vector element count mismatch!");
2845     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2846       return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2847     else if (OpOpcode == ISD::UNDEF)
2848       // sext(undef) = 0, because the top bits will all be the same.
2849       return getConstant(0, VT);
2850     break;
2851   case ISD::ZERO_EXTEND:
2852     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2853            "Invalid ZERO_EXTEND!");
2854     if (Operand.getValueType() == VT) return Operand;   // noop extension
2855     assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2856            "Invalid zext node, dst < src!");
2857     assert((!VT.isVector() ||
2858             VT.getVectorNumElements() ==
2859             Operand.getValueType().getVectorNumElements()) &&
2860            "Vector element count mismatch!");
2861     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
2862       return getNode(ISD::ZERO_EXTEND, DL, VT,
2863                      Operand.getNode()->getOperand(0));
2864     else if (OpOpcode == ISD::UNDEF)
2865       // zext(undef) = 0, because the top bits will be zero.
2866       return getConstant(0, VT);
2867     break;
2868   case ISD::ANY_EXTEND:
2869     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2870            "Invalid ANY_EXTEND!");
2871     if (Operand.getValueType() == VT) return Operand;   // noop extension
2872     assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2873            "Invalid anyext node, dst < src!");
2874     assert((!VT.isVector() ||
2875             VT.getVectorNumElements() ==
2876             Operand.getValueType().getVectorNumElements()) &&
2877            "Vector element count mismatch!");
2878
2879     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2880         OpOpcode == ISD::ANY_EXTEND)
2881       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
2882       return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2883     else if (OpOpcode == ISD::UNDEF)
2884       return getUNDEF(VT);
2885
2886     // (ext (trunx x)) -> x
2887     if (OpOpcode == ISD::TRUNCATE) {
2888       SDValue OpOp = Operand.getNode()->getOperand(0);
2889       if (OpOp.getValueType() == VT)
2890         return OpOp;
2891     }
2892     break;
2893   case ISD::TRUNCATE:
2894     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2895            "Invalid TRUNCATE!");
2896     if (Operand.getValueType() == VT) return Operand;   // noop truncate
2897     assert(Operand.getValueType().getScalarType().bitsGT(VT.getScalarType()) &&
2898            "Invalid truncate node, src < dst!");
2899     assert((!VT.isVector() ||
2900             VT.getVectorNumElements() ==
2901             Operand.getValueType().getVectorNumElements()) &&
2902            "Vector element count mismatch!");
2903     if (OpOpcode == ISD::TRUNCATE)
2904       return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2905     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2906         OpOpcode == ISD::ANY_EXTEND) {
2907       // If the source is smaller than the dest, we still need an extend.
2908       if (Operand.getNode()->getOperand(0).getValueType().getScalarType()
2909             .bitsLT(VT.getScalarType()))
2910         return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2911       if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2912         return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2913       return Operand.getNode()->getOperand(0);
2914     }
2915     if (OpOpcode == ISD::UNDEF)
2916       return getUNDEF(VT);
2917     break;
2918   case ISD::BITCAST:
2919     // Basic sanity checking.
2920     assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2921            && "Cannot BITCAST between types of different sizes!");
2922     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
2923     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
2924       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
2925     if (OpOpcode == ISD::UNDEF)
2926       return getUNDEF(VT);
2927     break;
2928   case ISD::SCALAR_TO_VECTOR:
2929     assert(VT.isVector() && !Operand.getValueType().isVector() &&
2930            (VT.getVectorElementType() == Operand.getValueType() ||
2931             (VT.getVectorElementType().isInteger() &&
2932              Operand.getValueType().isInteger() &&
2933              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
2934            "Illegal SCALAR_TO_VECTOR node!");
2935     if (OpOpcode == ISD::UNDEF)
2936       return getUNDEF(VT);
2937     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2938     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2939         isa<ConstantSDNode>(Operand.getOperand(1)) &&
2940         Operand.getConstantOperandVal(1) == 0 &&
2941         Operand.getOperand(0).getValueType() == VT)
2942       return Operand.getOperand(0);
2943     break;
2944   case ISD::FNEG:
2945     // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
2946     if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB)
2947       return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
2948                      Operand.getNode()->getOperand(0));
2949     if (OpOpcode == ISD::FNEG)  // --X -> X
2950       return Operand.getNode()->getOperand(0);
2951     break;
2952   case ISD::FABS:
2953     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
2954       return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
2955     break;
2956   }
2957
2958   SDNode *N;
2959   SDVTList VTs = getVTList(VT);
2960   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
2961     FoldingSetNodeID ID;
2962     SDValue Ops[1] = { Operand };
2963     AddNodeIDNode(ID, Opcode, VTs, Ops);
2964     void *IP = nullptr;
2965     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2966       return SDValue(E, 0);
2967
2968     N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(),
2969                                         DL.getDebugLoc(), VTs, Operand);
2970     CSEMap.InsertNode(N, IP);
2971   } else {
2972     N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(),
2973                                         DL.getDebugLoc(), VTs, Operand);
2974   }
2975
2976   InsertNode(N);
2977   return SDValue(N, 0);
2978 }
2979
2980 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, EVT VT,
2981                                              SDNode *Cst1, SDNode *Cst2) {
2982   // If the opcode is a target-specific ISD node, there's nothing we can
2983   // do here and the operand rules may not line up with the below, so
2984   // bail early.
2985   if (Opcode >= ISD::BUILTIN_OP_END)
2986     return SDValue();
2987
2988   SmallVector<std::pair<ConstantSDNode *, ConstantSDNode *>, 4> Inputs;
2989   SmallVector<SDValue, 4> Outputs;
2990   EVT SVT = VT.getScalarType();
2991
2992   ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1);
2993   ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2);
2994   if (Scalar1 && Scalar2 && (Scalar1->isOpaque() || Scalar2->isOpaque()))
2995     return SDValue();
2996
2997   if (Scalar1 && Scalar2)
2998     // Scalar instruction.
2999     Inputs.push_back(std::make_pair(Scalar1, Scalar2));
3000   else {
3001     // For vectors extract each constant element into Inputs so we can constant
3002     // fold them individually.
3003     BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1);
3004     BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2);
3005     if (!BV1 || !BV2)
3006       return SDValue();
3007
3008     assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!");
3009
3010     for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) {
3011       ConstantSDNode *V1 = dyn_cast<ConstantSDNode>(BV1->getOperand(I));
3012       ConstantSDNode *V2 = dyn_cast<ConstantSDNode>(BV2->getOperand(I));
3013       if (!V1 || !V2) // Not a constant, bail.
3014         return SDValue();
3015
3016       if (V1->isOpaque() || V2->isOpaque())
3017         return SDValue();
3018
3019       // Avoid BUILD_VECTOR nodes that perform implicit truncation.
3020       // FIXME: This is valid and could be handled by truncating the APInts.
3021       if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
3022         return SDValue();
3023
3024       Inputs.push_back(std::make_pair(V1, V2));
3025     }
3026   }
3027
3028   // We have a number of constant values, constant fold them element by element.
3029   for (unsigned I = 0, E = Inputs.size(); I != E; ++I) {
3030     const APInt &C1 = Inputs[I].first->getAPIntValue();
3031     const APInt &C2 = Inputs[I].second->getAPIntValue();
3032
3033     switch (Opcode) {
3034     case ISD::ADD:
3035       Outputs.push_back(getConstant(C1 + C2, SVT));
3036       break;
3037     case ISD::SUB:
3038       Outputs.push_back(getConstant(C1 - C2, SVT));
3039       break;
3040     case ISD::MUL:
3041       Outputs.push_back(getConstant(C1 * C2, SVT));
3042       break;
3043     case ISD::UDIV:
3044       if (!C2.getBoolValue())
3045         return SDValue();
3046       Outputs.push_back(getConstant(C1.udiv(C2), SVT));
3047       break;
3048     case ISD::UREM:
3049       if (!C2.getBoolValue())
3050         return SDValue();
3051       Outputs.push_back(getConstant(C1.urem(C2), SVT));
3052       break;
3053     case ISD::SDIV:
3054       if (!C2.getBoolValue())
3055         return SDValue();
3056       Outputs.push_back(getConstant(C1.sdiv(C2), SVT));
3057       break;
3058     case ISD::SREM:
3059       if (!C2.getBoolValue())
3060         return SDValue();
3061       Outputs.push_back(getConstant(C1.srem(C2), SVT));
3062       break;
3063     case ISD::AND:
3064       Outputs.push_back(getConstant(C1 & C2, SVT));
3065       break;
3066     case ISD::OR:
3067       Outputs.push_back(getConstant(C1 | C2, SVT));
3068       break;
3069     case ISD::XOR:
3070       Outputs.push_back(getConstant(C1 ^ C2, SVT));
3071       break;
3072     case ISD::SHL:
3073       Outputs.push_back(getConstant(C1 << C2, SVT));
3074       break;
3075     case ISD::SRL:
3076       Outputs.push_back(getConstant(C1.lshr(C2), SVT));
3077       break;
3078     case ISD::SRA:
3079       Outputs.push_back(getConstant(C1.ashr(C2), SVT));
3080       break;
3081     case ISD::ROTL:
3082       Outputs.push_back(getConstant(C1.rotl(C2), SVT));
3083       break;
3084     case ISD::ROTR:
3085       Outputs.push_back(getConstant(C1.rotr(C2), SVT));
3086       break;
3087     default:
3088       return SDValue();
3089     }
3090   }
3091
3092   assert((Scalar1 && Scalar2) || (VT.getVectorNumElements() == Outputs.size() &&
3093                                   "Expected a scalar or vector!"));
3094
3095   // Handle the scalar case first.
3096   if (!VT.isVector())
3097     return Outputs.back();
3098
3099   // We may have a vector type but a scalar result. Create a splat.
3100   Outputs.resize(VT.getVectorNumElements(), Outputs.back());
3101
3102   // Build a big vector out of the scalar elements we generated.
3103   return getNode(ISD::BUILD_VECTOR, SDLoc(), VT, Outputs);
3104 }
3105
3106 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT, SDValue N1,
3107                               SDValue N2, bool nuw, bool nsw, bool exact) {
3108   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
3109   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
3110   switch (Opcode) {
3111   default: break;
3112   case ISD::TokenFactor:
3113     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
3114            N2.getValueType() == MVT::Other && "Invalid token factor!");
3115     // Fold trivial token factors.
3116     if (N1.getOpcode() == ISD::EntryToken) return N2;
3117     if (N2.getOpcode() == ISD::EntryToken) return N1;
3118     if (N1 == N2) return N1;
3119     break;
3120   case ISD::CONCAT_VECTORS:
3121     // Concat of UNDEFs is UNDEF.
3122     if (N1.getOpcode() == ISD::UNDEF &&
3123         N2.getOpcode() == ISD::UNDEF)
3124       return getUNDEF(VT);
3125
3126     // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
3127     // one big BUILD_VECTOR.
3128     if (N1.getOpcode() == ISD::BUILD_VECTOR &&
3129         N2.getOpcode() == ISD::BUILD_VECTOR) {
3130       SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(),
3131                                     N1.getNode()->op_end());
3132       Elts.append(N2.getNode()->op_begin(), N2.getNode()->op_end());
3133       return getNode(ISD::BUILD_VECTOR, DL, VT, Elts);
3134     }
3135     break;
3136   case ISD::AND:
3137     assert(VT.isInteger() && "This operator does not apply to FP types!");
3138     assert(N1.getValueType() == N2.getValueType() &&
3139            N1.getValueType() == VT && "Binary operator types must match!");
3140     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
3141     // worth handling here.
3142     if (N2C && N2C->isNullValue())
3143       return N2;
3144     if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
3145       return N1;
3146     break;
3147   case ISD::OR:
3148   case ISD::XOR:
3149   case ISD::ADD:
3150   case ISD::SUB:
3151     assert(VT.isInteger() && "This operator does not apply to FP types!");
3152     assert(N1.getValueType() == N2.getValueType() &&
3153            N1.getValueType() == VT && "Binary operator types must match!");
3154     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
3155     // it's worth handling here.
3156     if (N2C && N2C->isNullValue())
3157       return N1;
3158     break;
3159   case ISD::UDIV:
3160   case ISD::UREM:
3161   case ISD::MULHU:
3162   case ISD::MULHS:
3163   case ISD::MUL:
3164   case ISD::SDIV:
3165   case ISD::SREM:
3166     assert(VT.isInteger() && "This operator does not apply to FP types!");
3167     assert(N1.getValueType() == N2.getValueType() &&
3168            N1.getValueType() == VT && "Binary operator types must match!");
3169     break;
3170   case ISD::FADD:
3171   case ISD::FSUB:
3172   case ISD::FMUL:
3173   case ISD::FDIV:
3174   case ISD::FREM:
3175     if (getTarget().Options.UnsafeFPMath) {
3176       if (Opcode == ISD::FADD) {
3177         // 0+x --> x
3178         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
3179           if (CFP->getValueAPF().isZero())
3180             return N2;
3181         // x+0 --> x
3182         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
3183           if (CFP->getValueAPF().isZero())
3184             return N1;
3185       } else if (Opcode == ISD::FSUB) {
3186         // x-0 --> x
3187         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
3188           if (CFP->getValueAPF().isZero())
3189             return N1;
3190       } else if (Opcode == ISD::FMUL) {
3191         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1);
3192         SDValue V = N2;
3193
3194         // If the first operand isn't the constant, try the second
3195         if (!CFP) {
3196           CFP = dyn_cast<ConstantFPSDNode>(N2);
3197           V = N1;
3198         }
3199
3200         if (CFP) {
3201           // 0*x --> 0
3202           if (CFP->isZero())
3203             return SDValue(CFP,0);
3204           // 1*x --> x
3205           if (CFP->isExactlyValue(1.0))
3206             return V;
3207         }
3208       }
3209     }
3210     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
3211     assert(N1.getValueType() == N2.getValueType() &&
3212            N1.getValueType() == VT && "Binary operator types must match!");
3213     break;
3214   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
3215     assert(N1.getValueType() == VT &&
3216            N1.getValueType().isFloatingPoint() &&
3217            N2.getValueType().isFloatingPoint() &&
3218            "Invalid FCOPYSIGN!");
3219     break;
3220   case ISD::SHL:
3221   case ISD::SRA:
3222   case ISD::SRL:
3223   case ISD::ROTL:
3224   case ISD::ROTR:
3225     assert(VT == N1.getValueType() &&
3226            "Shift operators return type must be the same as their first arg");
3227     assert(VT.isInteger() && N2.getValueType().isInteger() &&
3228            "Shifts only work on integers");
3229     assert((!VT.isVector() || VT == N2.getValueType()) &&
3230            "Vector shift amounts must be in the same as their first arg");
3231     // Verify that the shift amount VT is bit enough to hold valid shift
3232     // amounts.  This catches things like trying to shift an i1024 value by an
3233     // i8, which is easy to fall into in generic code that uses
3234     // TLI.getShiftAmount().
3235     assert(N2.getValueType().getSizeInBits() >=
3236                    Log2_32_Ceil(N1.getValueType().getSizeInBits()) &&
3237            "Invalid use of small shift amount with oversized value!");
3238
3239     // Always fold shifts of i1 values so the code generator doesn't need to
3240     // handle them.  Since we know the size of the shift has to be less than the
3241     // size of the value, the shift/rotate count is guaranteed to be zero.
3242     if (VT == MVT::i1)
3243       return N1;
3244     if (N2C && N2C->isNullValue())
3245       return N1;
3246     break;
3247   case ISD::FP_ROUND_INREG: {
3248     EVT EVT = cast<VTSDNode>(N2)->getVT();
3249     assert(VT == N1.getValueType() && "Not an inreg round!");
3250     assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
3251            "Cannot FP_ROUND_INREG integer types");
3252     assert(EVT.isVector() == VT.isVector() &&
3253            "FP_ROUND_INREG type should be vector iff the operand "
3254            "type is vector!");
3255     assert((!EVT.isVector() ||
3256             EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
3257            "Vector element counts must match in FP_ROUND_INREG");
3258     assert(EVT.bitsLE(VT) && "Not rounding down!");
3259     (void)EVT;
3260     if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
3261     break;
3262   }
3263   case ISD::FP_ROUND:
3264     assert(VT.isFloatingPoint() &&
3265            N1.getValueType().isFloatingPoint() &&
3266            VT.bitsLE(N1.getValueType()) &&
3267            isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
3268     if (N1.getValueType() == VT) return N1;  // noop conversion.
3269     break;
3270   case ISD::AssertSext:
3271   case ISD::AssertZext: {
3272     EVT EVT = cast<VTSDNode>(N2)->getVT();
3273     assert(VT == N1.getValueType() && "Not an inreg extend!");
3274     assert(VT.isInteger() && EVT.isInteger() &&
3275            "Cannot *_EXTEND_INREG FP types");
3276     assert(!EVT.isVector() &&
3277            "AssertSExt/AssertZExt type should be the vector element type "
3278            "rather than the vector type!");
3279     assert(EVT.bitsLE(VT) && "Not extending!");
3280     if (VT == EVT) return N1; // noop assertion.
3281     break;
3282   }
3283   case ISD::SIGN_EXTEND_INREG: {
3284     EVT EVT = cast<VTSDNode>(N2)->getVT();
3285     assert(VT == N1.getValueType() && "Not an inreg extend!");
3286     assert(VT.isInteger() && EVT.isInteger() &&
3287            "Cannot *_EXTEND_INREG FP types");
3288     assert(EVT.isVector() == VT.isVector() &&
3289            "SIGN_EXTEND_INREG type should be vector iff the operand "
3290            "type is vector!");
3291     assert((!EVT.isVector() ||
3292             EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
3293            "Vector element counts must match in SIGN_EXTEND_INREG");
3294     assert(EVT.bitsLE(VT) && "Not extending!");
3295     if (EVT == VT) return N1;  // Not actually extending
3296
3297     if (N1C) {
3298       APInt Val = N1C->getAPIntValue();
3299       unsigned FromBits = EVT.getScalarType().getSizeInBits();
3300       Val <<= Val.getBitWidth()-FromBits;
3301       Val = Val.ashr(Val.getBitWidth()-FromBits);
3302       return getConstant(Val, VT);
3303     }
3304     break;
3305   }
3306   case ISD::EXTRACT_VECTOR_ELT:
3307     // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
3308     if (N1.getOpcode() == ISD::UNDEF)
3309       return getUNDEF(VT);
3310
3311     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
3312     // expanding copies of large vectors from registers.
3313     if (N2C &&
3314         N1.getOpcode() == ISD::CONCAT_VECTORS &&
3315         N1.getNumOperands() > 0) {
3316       unsigned Factor =
3317         N1.getOperand(0).getValueType().getVectorNumElements();
3318       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
3319                      N1.getOperand(N2C->getZExtValue() / Factor),
3320                      getConstant(N2C->getZExtValue() % Factor,
3321                                  N2.getValueType()));
3322     }
3323
3324     // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
3325     // expanding large vector constants.
3326     if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
3327       SDValue Elt = N1.getOperand(N2C->getZExtValue());
3328
3329       if (VT != Elt.getValueType())
3330         // If the vector element type is not legal, the BUILD_VECTOR operands
3331         // are promoted and implicitly truncated, and the result implicitly
3332         // extended. Make that explicit here.
3333         Elt = getAnyExtOrTrunc(Elt, DL, VT);
3334
3335       return Elt;
3336     }
3337
3338     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
3339     // operations are lowered to scalars.
3340     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
3341       // If the indices are the same, return the inserted element else
3342       // if the indices are known different, extract the element from
3343       // the original vector.
3344       SDValue N1Op2 = N1.getOperand(2);
3345       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2.getNode());
3346
3347       if (N1Op2C && N2C) {
3348         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
3349           if (VT == N1.getOperand(1).getValueType())
3350             return N1.getOperand(1);
3351           else
3352             return getSExtOrTrunc(N1.getOperand(1), DL, VT);
3353         }
3354
3355         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
3356       }
3357     }
3358     break;
3359   case ISD::EXTRACT_ELEMENT:
3360     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
3361     assert(!N1.getValueType().isVector() && !VT.isVector() &&
3362            (N1.getValueType().isInteger() == VT.isInteger()) &&
3363            N1.getValueType() != VT &&
3364            "Wrong types for EXTRACT_ELEMENT!");
3365
3366     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
3367     // 64-bit integers into 32-bit parts.  Instead of building the extract of
3368     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
3369     if (N1.getOpcode() == ISD::BUILD_PAIR)
3370       return N1.getOperand(N2C->getZExtValue());
3371
3372     // EXTRACT_ELEMENT of a constant int is also very common.
3373     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3374       unsigned ElementSize = VT.getSizeInBits();
3375       unsigned Shift = ElementSize * N2C->getZExtValue();
3376       APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
3377       return getConstant(ShiftedVal.trunc(ElementSize), VT);
3378     }
3379     break;
3380   case ISD::EXTRACT_SUBVECTOR: {
3381     SDValue Index = N2;
3382     if (VT.isSimple() && N1.getValueType().isSimple()) {
3383       assert(VT.isVector() && N1.getValueType().isVector() &&
3384              "Extract subvector VTs must be a vectors!");
3385       assert(VT.getVectorElementType() ==
3386              N1.getValueType().getVectorElementType() &&
3387              "Extract subvector VTs must have the same element type!");
3388       assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
3389              "Extract subvector must be from larger vector to smaller vector!");
3390
3391       if (isa<ConstantSDNode>(Index.getNode())) {
3392         assert((VT.getVectorNumElements() +
3393                 cast<ConstantSDNode>(Index.getNode())->getZExtValue()
3394                 <= N1.getValueType().getVectorNumElements())
3395                && "Extract subvector overflow!");
3396       }
3397
3398       // Trivial extraction.
3399       if (VT.getSimpleVT() == N1.getSimpleValueType())
3400         return N1;
3401     }
3402     break;
3403   }
3404   }
3405
3406   // Perform trivial constant folding.
3407   if (SDValue SV =
3408           FoldConstantArithmetic(Opcode, VT, N1.getNode(), N2.getNode()))
3409     return SV;
3410
3411   // Canonicalize constant to RHS if commutative.
3412   if (N1C && !N2C && isCommutativeBinOp(Opcode)) {
3413     std::swap(N1C, N2C);
3414     std::swap(N1, N2);
3415   }
3416
3417   // Constant fold FP operations.
3418   bool HasFPExceptions = TLI->hasFloatingPointExceptions();
3419   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
3420   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
3421   if (N1CFP) {
3422     if (!N2CFP && isCommutativeBinOp(Opcode)) {
3423       // Canonicalize constant to RHS if commutative.
3424       std::swap(N1CFP, N2CFP);
3425       std::swap(N1, N2);
3426     } else if (N2CFP) {
3427       APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
3428       APFloat::opStatus s;
3429       switch (Opcode) {
3430       case ISD::FADD:
3431         s = V1.add(V2, APFloat::rmNearestTiesToEven);
3432         if (!HasFPExceptions || s != APFloat::opInvalidOp)
3433           return getConstantFP(V1, VT);
3434         break;
3435       case ISD::FSUB:
3436         s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
3437         if (!HasFPExceptions || s!=APFloat::opInvalidOp)
3438           return getConstantFP(V1, VT);
3439         break;
3440       case ISD::FMUL:
3441         s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
3442         if (!HasFPExceptions || s!=APFloat::opInvalidOp)
3443           return getConstantFP(V1, VT);
3444         break;
3445       case ISD::FDIV:
3446         s = V1.divide(V2, APFloat::rmNearestTiesToEven);
3447         if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
3448                                  s!=APFloat::opDivByZero)) {
3449           return getConstantFP(V1, VT);
3450         }
3451         break;
3452       case ISD::FREM :
3453         s = V1.mod(V2, APFloat::rmNearestTiesToEven);
3454         if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
3455                                  s!=APFloat::opDivByZero)) {
3456           return getConstantFP(V1, VT);
3457         }
3458         break;
3459       case ISD::FCOPYSIGN:
3460         V1.copySign(V2);
3461         return getConstantFP(V1, VT);
3462       default: break;
3463       }
3464     }
3465
3466     if (Opcode == ISD::FP_ROUND) {
3467       APFloat V = N1CFP->getValueAPF();    // make copy
3468       bool ignored;
3469       // This can return overflow, underflow, or inexact; we don't care.
3470       // FIXME need to be more flexible about rounding mode.
3471       (void)V.convert(EVTToAPFloatSemantics(VT),
3472                       APFloat::rmNearestTiesToEven, &ignored);
3473       return getConstantFP(V, VT);
3474     }
3475   }
3476
3477   // Canonicalize an UNDEF to the RHS, even over a constant.
3478   if (N1.getOpcode() == ISD::UNDEF) {
3479     if (isCommutativeBinOp(Opcode)) {
3480       std::swap(N1, N2);
3481     } else {
3482       switch (Opcode) {
3483       case ISD::FP_ROUND_INREG:
3484       case ISD::SIGN_EXTEND_INREG:
3485       case ISD::SUB:
3486       case ISD::FSUB:
3487       case ISD::FDIV:
3488       case ISD::FREM:
3489       case ISD::SRA:
3490         return N1;     // fold op(undef, arg2) -> undef
3491       case ISD::UDIV:
3492       case ISD::SDIV:
3493       case ISD::UREM:
3494       case ISD::SREM:
3495       case ISD::SRL:
3496       case ISD::SHL:
3497         if (!VT.isVector())
3498           return getConstant(0, VT);    // fold op(undef, arg2) -> 0
3499         // For vectors, we can't easily build an all zero vector, just return
3500         // the LHS.
3501         return N2;
3502       }
3503     }
3504   }
3505
3506   // Fold a bunch of operators when the RHS is undef.
3507   if (N2.getOpcode() == ISD::UNDEF) {
3508     switch (Opcode) {
3509     case ISD::XOR:
3510       if (N1.getOpcode() == ISD::UNDEF)
3511         // Handle undef ^ undef -> 0 special case. This is a common
3512         // idiom (misuse).
3513         return getConstant(0, VT);
3514       // fallthrough
3515     case ISD::ADD:
3516     case ISD::ADDC:
3517     case ISD::ADDE:
3518     case ISD::SUB:
3519     case ISD::UDIV:
3520     case ISD::SDIV:
3521     case ISD::UREM:
3522     case ISD::SREM:
3523       return N2;       // fold op(arg1, undef) -> undef
3524     case ISD::FADD:
3525     case ISD::FSUB:
3526     case ISD::FMUL:
3527     case ISD::FDIV:
3528     case ISD::FREM:
3529       if (getTarget().Options.UnsafeFPMath)
3530         return N2;
3531       break;
3532     case ISD::MUL:
3533     case ISD::AND:
3534     case ISD::SRL:
3535     case ISD::SHL:
3536       if (!VT.isVector())
3537         return getConstant(0, VT);  // fold op(arg1, undef) -> 0
3538       // For vectors, we can't easily build an all zero vector, just return
3539       // the LHS.
3540       return N1;
3541     case ISD::OR:
3542       if (!VT.isVector())
3543         return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
3544       // For vectors, we can't easily build an all one vector, just return
3545       // the LHS.
3546       return N1;
3547     case ISD::SRA:
3548       return N1;
3549     }
3550   }
3551
3552   // Memoize this node if possible.
3553   BinarySDNode *N;
3554   SDVTList VTs = getVTList(VT);
3555   const bool BinOpHasFlags = isBinOpWithFlags(Opcode);
3556   if (VT != MVT::Glue) {
3557     SDValue Ops[] = {N1, N2};
3558     FoldingSetNodeID ID;
3559     AddNodeIDNode(ID, Opcode, VTs, Ops);
3560     if (BinOpHasFlags)
3561       AddBinaryNodeIDCustom(ID, Opcode, nuw, nsw, exact);
3562     void *IP = nullptr;
3563     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3564       return SDValue(E, 0);
3565
3566     N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, nuw, nsw, exact);
3567
3568     CSEMap.InsertNode(N, IP);
3569   } else {
3570
3571     N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, nuw, nsw, exact);
3572   }
3573
3574   InsertNode(N);
3575   return SDValue(N, 0);
3576 }
3577
3578 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
3579                               SDValue N1, SDValue N2, SDValue N3) {
3580   // Perform various simplifications.
3581   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
3582   switch (Opcode) {
3583   case ISD::FMA: {
3584     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3585     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
3586     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
3587     if (N1CFP && N2CFP && N3CFP) {
3588       APFloat  V1 = N1CFP->getValueAPF();
3589       const APFloat &V2 = N2CFP->getValueAPF();
3590       const APFloat &V3 = N3CFP->getValueAPF();
3591       APFloat::opStatus s =
3592         V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
3593       if (s != APFloat::opInvalidOp)
3594         return getConstantFP(V1, VT);
3595     }
3596     break;
3597   }
3598   case ISD::CONCAT_VECTORS:
3599     // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
3600     // one big BUILD_VECTOR.
3601     if (N1.getOpcode() == ISD::BUILD_VECTOR &&
3602         N2.getOpcode() == ISD::BUILD_VECTOR &&
3603         N3.getOpcode() == ISD::BUILD_VECTOR) {
3604       SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(),
3605                                     N1.getNode()->op_end());
3606       Elts.append(N2.getNode()->op_begin(), N2.getNode()->op_end());
3607       Elts.append(N3.getNode()->op_begin(), N3.getNode()->op_end());
3608       return getNode(ISD::BUILD_VECTOR, DL, VT, Elts);
3609     }
3610     break;
3611   case ISD::SETCC: {
3612     // Use FoldSetCC to simplify SETCC's.
3613     SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
3614     if (Simp.getNode()) return Simp;
3615     break;
3616   }
3617   case ISD::SELECT:
3618     if (N1C) {
3619      if (N1C->getZExtValue())
3620        return N2;             // select true, X, Y -> X
3621      return N3;             // select false, X, Y -> Y
3622     }
3623
3624     if (N2 == N3) return N2;   // select C, X, X -> X
3625     break;
3626   case ISD::VECTOR_SHUFFLE:
3627     llvm_unreachable("should use getVectorShuffle constructor!");
3628   case ISD::INSERT_SUBVECTOR: {
3629     SDValue Index = N3;
3630     if (VT.isSimple() && N1.getValueType().isSimple()
3631         && N2.getValueType().isSimple()) {
3632       assert(VT.isVector() && N1.getValueType().isVector() &&
3633              N2.getValueType().isVector() &&
3634              "Insert subvector VTs must be a vectors");
3635       assert(VT == N1.getValueType() &&
3636              "Dest and insert subvector source types must match!");
3637       assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
3638              "Insert subvector must be from smaller vector to larger vector!");
3639       if (isa<ConstantSDNode>(Index.getNode())) {
3640         assert((N2.getValueType().getVectorNumElements() +
3641                 cast<ConstantSDNode>(Index.getNode())->getZExtValue()
3642                 <= VT.getVectorNumElements())
3643                && "Insert subvector overflow!");
3644       }
3645
3646       // Trivial insertion.
3647       if (VT.getSimpleVT() == N2.getSimpleValueType())
3648         return N2;
3649     }
3650     break;
3651   }
3652   case ISD::BITCAST:
3653     // Fold bit_convert nodes from a type to themselves.
3654     if (N1.getValueType() == VT)
3655       return N1;
3656     break;
3657   }
3658
3659   // Memoize node if it doesn't produce a flag.
3660   SDNode *N;
3661   SDVTList VTs = getVTList(VT);
3662   if (VT != MVT::Glue) {
3663     SDValue Ops[] = { N1, N2, N3 };
3664     FoldingSetNodeID ID;
3665     AddNodeIDNode(ID, Opcode, VTs, Ops);
3666     void *IP = nullptr;
3667     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3668       return SDValue(E, 0);
3669
3670     N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(),
3671                                           DL.getDebugLoc(), VTs, N1, N2, N3);
3672     CSEMap.InsertNode(N, IP);
3673   } else {
3674     N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(),
3675                                           DL.getDebugLoc(), VTs, N1, N2, N3);
3676   }
3677
3678   InsertNode(N);
3679   return SDValue(N, 0);
3680 }
3681
3682 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
3683                               SDValue N1, SDValue N2, SDValue N3,
3684                               SDValue N4) {
3685   SDValue Ops[] = { N1, N2, N3, N4 };
3686   return getNode(Opcode, DL, VT, Ops);
3687 }
3688
3689 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
3690                               SDValue N1, SDValue N2, SDValue N3,
3691                               SDValue N4, SDValue N5) {
3692   SDValue Ops[] = { N1, N2, N3, N4, N5 };
3693   return getNode(Opcode, DL, VT, Ops);
3694 }
3695
3696 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
3697 /// the incoming stack arguments to be loaded from the stack.
3698 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
3699   SmallVector<SDValue, 8> ArgChains;
3700
3701   // Include the original chain at the beginning of the list. When this is
3702   // used by target LowerCall hooks, this helps legalize find the
3703   // CALLSEQ_BEGIN node.
3704   ArgChains.push_back(Chain);
3705
3706   // Add a chain value for each stack argument.
3707   for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
3708        UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
3709     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3710       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3711         if (FI->getIndex() < 0)
3712           ArgChains.push_back(SDValue(L, 1));
3713
3714   // Build a tokenfactor for all the chains.
3715   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3716 }
3717
3718 /// getMemsetValue - Vectorized representation of the memset value
3719 /// operand.
3720 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
3721                               SDLoc dl) {
3722   assert(Value.getOpcode() != ISD::UNDEF);
3723
3724   unsigned NumBits = VT.getScalarType().getSizeInBits();
3725   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3726     assert(C->getAPIntValue().getBitWidth() == 8);
3727     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
3728     if (VT.isInteger())
3729       return DAG.getConstant(Val, VT);
3730     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), VT);
3731   }
3732
3733   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value);
3734   if (NumBits > 8) {
3735     // Use a multiplication with 0x010101... to extend the input to the
3736     // required length.
3737     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
3738     Value = DAG.getNode(ISD::MUL, dl, VT, Value, DAG.getConstant(Magic, VT));
3739   }
3740
3741   return Value;
3742 }
3743
3744 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3745 /// used when a memcpy is turned into a memset when the source is a constant
3746 /// string ptr.
3747 static SDValue getMemsetStringVal(EVT VT, SDLoc dl, SelectionDAG &DAG,
3748                                   const TargetLowering &TLI, StringRef Str) {
3749   // Handle vector with all elements zero.
3750   if (Str.empty()) {
3751     if (VT.isInteger())
3752       return DAG.getConstant(0, VT);
3753     else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
3754       return DAG.getConstantFP(0.0, VT);
3755     else if (VT.isVector()) {
3756       unsigned NumElts = VT.getVectorNumElements();
3757       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
3758       return DAG.getNode(ISD::BITCAST, dl, VT,
3759                          DAG.getConstant(0, EVT::getVectorVT(*DAG.getContext(),
3760                                                              EltVT, NumElts)));
3761     } else
3762       llvm_unreachable("Expected type!");
3763   }
3764
3765   assert(!VT.isVector() && "Can't handle vector type here!");
3766   unsigned NumVTBits = VT.getSizeInBits();
3767   unsigned NumVTBytes = NumVTBits / 8;
3768   unsigned NumBytes = std::min(NumVTBytes, unsigned(Str.size()));
3769
3770   APInt Val(NumVTBits, 0);
3771   if (TLI.isLittleEndian()) {
3772     for (unsigned i = 0; i != NumBytes; ++i)
3773       Val |= (uint64_t)(unsigned char)Str[i] << i*8;
3774   } else {
3775     for (unsigned i = 0; i != NumBytes; ++i)
3776       Val |= (uint64_t)(unsigned char)Str[i] << (NumVTBytes-i-1)*8;
3777   }
3778
3779   // If the "cost" of materializing the integer immediate is less than the cost
3780   // of a load, then it is cost effective to turn the load into the immediate.
3781   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
3782   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
3783     return DAG.getConstant(Val, VT);
3784   return SDValue(nullptr, 0);
3785 }
3786
3787 /// getMemBasePlusOffset - Returns base and offset node for the
3788 ///
3789 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset, SDLoc dl,
3790                                       SelectionDAG &DAG) {
3791   EVT VT = Base.getValueType();
3792   return DAG.getNode(ISD::ADD, dl,
3793                      VT, Base, DAG.getConstant(Offset, VT));
3794 }
3795
3796 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
3797 ///
3798 static bool isMemSrcFromString(SDValue Src, StringRef &Str) {
3799   unsigned SrcDelta = 0;
3800   GlobalAddressSDNode *G = nullptr;
3801   if (Src.getOpcode() == ISD::GlobalAddress)
3802     G = cast<GlobalAddressSDNode>(Src);
3803   else if (Src.getOpcode() == ISD::ADD &&
3804            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3805            Src.getOperand(1).getOpcode() == ISD::Constant) {
3806     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
3807     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
3808   }
3809   if (!G)
3810     return false;
3811
3812   return getConstantStringInfo(G->getGlobal(), Str, SrcDelta, false);
3813 }
3814
3815 /// FindOptimalMemOpLowering - Determines the optimial series memory ops
3816 /// to replace the memset / memcpy. Return true if the number of memory ops
3817 /// is below the threshold. It returns the types of the sequence of
3818 /// memory ops to perform memset / memcpy by reference.
3819 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
3820                                      unsigned Limit, uint64_t Size,
3821                                      unsigned DstAlign, unsigned SrcAlign,
3822                                      bool IsMemset,
3823                                      bool ZeroMemset,
3824                                      bool MemcpyStrSrc,
3825                                      bool AllowOverlap,
3826                                      SelectionDAG &DAG,
3827                                      const TargetLowering &TLI) {
3828   assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
3829          "Expecting memcpy / memset source to meet alignment requirement!");
3830   // If 'SrcAlign' is zero, that means the memory operation does not need to
3831   // load the value, i.e. memset or memcpy from constant string. Otherwise,
3832   // it's the inferred alignment of the source. 'DstAlign', on the other hand,
3833   // is the specified alignment of the memory operation. If it is zero, that
3834   // means it's possible to change the alignment of the destination.
3835   // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
3836   // not need to be loaded.
3837   EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
3838                                    IsMemset, ZeroMemset, MemcpyStrSrc,
3839                                    DAG.getMachineFunction());
3840
3841   if (VT == MVT::Other) {
3842     unsigned AS = 0;
3843     if (DstAlign >= TLI.getDataLayout()->getPointerPrefAlignment(AS) ||
3844         TLI.allowsMisalignedMemoryAccesses(VT, AS, DstAlign)) {
3845       VT = TLI.getPointerTy();
3846     } else {
3847       switch (DstAlign & 7) {
3848       case 0:  VT = MVT::i64; break;
3849       case 4:  VT = MVT::i32; break;
3850       case 2:  VT = MVT::i16; break;
3851       default: VT = MVT::i8;  break;
3852       }
3853     }
3854
3855     MVT LVT = MVT::i64;
3856     while (!TLI.isTypeLegal(LVT))
3857       LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
3858     assert(LVT.isInteger());
3859
3860     if (VT.bitsGT(LVT))
3861       VT = LVT;
3862   }
3863
3864   unsigned NumMemOps = 0;
3865   while (Size != 0) {
3866     unsigned VTSize = VT.getSizeInBits() / 8;
3867     while (VTSize > Size) {
3868       // For now, only use non-vector load / store's for the left-over pieces.
3869       EVT NewVT = VT;
3870       unsigned NewVTSize;
3871
3872       bool Found = false;
3873       if (VT.isVector() || VT.isFloatingPoint()) {
3874         NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
3875         if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) &&
3876             TLI.isSafeMemOpType(NewVT.getSimpleVT()))
3877           Found = true;
3878         else if (NewVT == MVT::i64 &&
3879                  TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
3880                  TLI.isSafeMemOpType(MVT::f64)) {
3881           // i64 is usually not legal on 32-bit targets, but f64 may be.
3882           NewVT = MVT::f64;
3883           Found = true;
3884         }
3885       }
3886
3887       if (!Found) {
3888         do {
3889           NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
3890           if (NewVT == MVT::i8)
3891             break;
3892         } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT()));
3893       }
3894       NewVTSize = NewVT.getSizeInBits() / 8;
3895
3896       // If the new VT cannot cover all of the remaining bits, then consider
3897       // issuing a (or a pair of) unaligned and overlapping load / store.
3898       // FIXME: Only does this for 64-bit or more since we don't have proper
3899       // cost model for unaligned load / store.
3900       bool Fast;
3901       unsigned AS = 0;
3902       if (NumMemOps && AllowOverlap &&
3903           VTSize >= 8 && NewVTSize < Size &&
3904           TLI.allowsMisalignedMemoryAccesses(VT, AS, DstAlign, &Fast) && Fast)
3905         VTSize = Size;
3906       else {
3907         VT = NewVT;
3908         VTSize = NewVTSize;
3909       }
3910     }
3911
3912     if (++NumMemOps > Limit)
3913       return false;
3914
3915     MemOps.push_back(VT);
3916     Size -= VTSize;
3917   }
3918
3919   return true;
3920 }
3921
3922 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, SDLoc dl,
3923                                        SDValue Chain, SDValue Dst,
3924                                        SDValue Src, uint64_t Size,
3925                                        unsigned Align, bool isVol,
3926                                        bool AlwaysInline,
3927                                        MachinePointerInfo DstPtrInfo,
3928                                        MachinePointerInfo SrcPtrInfo) {
3929   // Turn a memcpy of undef to nop.
3930   if (Src.getOpcode() == ISD::UNDEF)
3931     return Chain;
3932
3933   // Expand memcpy to a series of load and store ops if the size operand falls
3934   // below a certain threshold.
3935   // TODO: In the AlwaysInline case, if the size is big then generate a loop
3936   // rather than maybe a humongous number of loads and stores.
3937   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3938   std::vector<EVT> MemOps;
3939   bool DstAlignCanChange = false;
3940   MachineFunction &MF = DAG.getMachineFunction();
3941   MachineFrameInfo *MFI = MF.getFrameInfo();
3942   bool OptSize =
3943     MF.getFunction()->getAttributes().
3944       hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
3945   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
3946   if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
3947     DstAlignCanChange = true;
3948   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
3949   if (Align > SrcAlign)
3950     SrcAlign = Align;
3951   StringRef Str;
3952   bool CopyFromStr = isMemSrcFromString(Src, Str);
3953   bool isZeroStr = CopyFromStr && Str.empty();
3954   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
3955
3956   if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
3957                                 (DstAlignCanChange ? 0 : Align),
3958                                 (isZeroStr ? 0 : SrcAlign),
3959                                 false, false, CopyFromStr, true, DAG, TLI))
3960     return SDValue();
3961
3962   if (DstAlignCanChange) {
3963     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
3964     unsigned NewAlign = (unsigned) TLI.getDataLayout()->getABITypeAlignment(Ty);
3965
3966     // Don't promote to an alignment that would require dynamic stack
3967     // realignment.
3968     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
3969     if (!TRI->needsStackRealignment(MF))
3970        while (NewAlign > Align &&
3971              TLI.getDataLayout()->exceedsNaturalStackAlignment(NewAlign))
3972           NewAlign /= 2;
3973
3974     if (NewAlign > Align) {
3975       // Give the stack frame object a larger alignment if needed.
3976       if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
3977         MFI->setObjectAlignment(FI->getIndex(), NewAlign);
3978       Align = NewAlign;
3979     }
3980   }
3981
3982   SmallVector<SDValue, 8> OutChains;
3983   unsigned NumMemOps = MemOps.size();
3984   uint64_t SrcOff = 0, DstOff = 0;
3985   for (unsigned i = 0; i != NumMemOps; ++i) {
3986     EVT VT = MemOps[i];
3987     unsigned VTSize = VT.getSizeInBits() / 8;
3988     SDValue Value, Store;
3989
3990     if (VTSize > Size) {
3991       // Issuing an unaligned load / store pair  that overlaps with the previous
3992       // pair. Adjust the offset accordingly.
3993       assert(i == NumMemOps-1 && i != 0);
3994       SrcOff -= VTSize - Size;
3995       DstOff -= VTSize - Size;
3996     }
3997
3998     if (CopyFromStr &&
3999         (isZeroStr || (VT.isInteger() && !VT.isVector()))) {
4000       // It's unlikely a store of a vector immediate can be done in a single
4001       // instruction. It would require a load from a constantpool first.
4002       // We only handle zero vectors here.
4003       // FIXME: Handle other cases where store of vector immediate is done in
4004       // a single instruction.
4005       Value = getMemsetStringVal(VT, dl, DAG, TLI, Str.substr(SrcOff));
4006       if (Value.getNode())
4007         Store = DAG.getStore(Chain, dl, Value,
4008                              getMemBasePlusOffset(Dst, DstOff, dl, DAG),
4009                              DstPtrInfo.getWithOffset(DstOff), isVol,
4010                              false, Align);
4011     }
4012
4013     if (!Store.getNode()) {
4014       // The type might not be legal for the target.  This should only happen
4015       // if the type is smaller than a legal type, as on PPC, so the right
4016       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
4017       // to Load/Store if NVT==VT.
4018       // FIXME does the case above also need this?
4019       EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
4020       assert(NVT.bitsGE(VT));
4021       Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
4022                              getMemBasePlusOffset(Src, SrcOff, dl, DAG),
4023                              SrcPtrInfo.getWithOffset(SrcOff), VT, isVol, false,
4024                              false, MinAlign(SrcAlign, SrcOff));
4025       Store = DAG.getTruncStore(Chain, dl, Value,
4026                                 getMemBasePlusOffset(Dst, DstOff, dl, DAG),
4027                                 DstPtrInfo.getWithOffset(DstOff), VT, isVol,
4028                                 false, Align);
4029     }
4030     OutChains.push_back(Store);
4031     SrcOff += VTSize;
4032     DstOff += VTSize;
4033     Size -= VTSize;
4034   }
4035
4036   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
4037 }
4038
4039 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, SDLoc dl,
4040                                         SDValue Chain, SDValue Dst,
4041                                         SDValue Src, uint64_t Size,
4042                                         unsigned Align,  bool isVol,
4043                                         bool AlwaysInline,
4044                                         MachinePointerInfo DstPtrInfo,
4045                                         MachinePointerInfo SrcPtrInfo) {
4046   // Turn a memmove of undef to nop.
4047   if (Src.getOpcode() == ISD::UNDEF)
4048     return Chain;
4049
4050   // Expand memmove to a series of load and store ops if the size operand falls
4051   // below a certain threshold.
4052   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4053   std::vector<EVT> MemOps;
4054   bool DstAlignCanChange = false;
4055   MachineFunction &MF = DAG.getMachineFunction();
4056   MachineFrameInfo *MFI = MF.getFrameInfo();
4057   bool OptSize = MF.getFunction()->getAttributes().
4058     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
4059   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4060   if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
4061     DstAlignCanChange = true;
4062   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
4063   if (Align > SrcAlign)
4064     SrcAlign = Align;
4065   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
4066
4067   if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
4068                                 (DstAlignCanChange ? 0 : Align), SrcAlign,
4069                                 false, false, false, false, DAG, TLI))
4070     return SDValue();
4071
4072   if (DstAlignCanChange) {
4073     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4074     unsigned NewAlign = (unsigned) TLI.getDataLayout()->getABITypeAlignment(Ty);
4075     if (NewAlign > Align) {
4076       // Give the stack frame object a larger alignment if needed.
4077       if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
4078         MFI->setObjectAlignment(FI->getIndex(), NewAlign);
4079       Align = NewAlign;
4080     }
4081   }
4082
4083   uint64_t SrcOff = 0, DstOff = 0;
4084   SmallVector<SDValue, 8> LoadValues;
4085   SmallVector<SDValue, 8> LoadChains;
4086   SmallVector<SDValue, 8> OutChains;
4087   unsigned NumMemOps = MemOps.size();
4088   for (unsigned i = 0; i < NumMemOps; i++) {
4089     EVT VT = MemOps[i];
4090     unsigned VTSize = VT.getSizeInBits() / 8;
4091     SDValue Value;
4092
4093     Value = DAG.getLoad(VT, dl, Chain,
4094                         getMemBasePlusOffset(Src, SrcOff, dl, DAG),
4095                         SrcPtrInfo.getWithOffset(SrcOff), isVol,
4096                         false, false, SrcAlign);
4097     LoadValues.push_back(Value);
4098     LoadChains.push_back(Value.getValue(1));
4099     SrcOff += VTSize;
4100   }
4101   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
4102   OutChains.clear();
4103   for (unsigned i = 0; i < NumMemOps; i++) {
4104     EVT VT = MemOps[i];
4105     unsigned VTSize = VT.getSizeInBits() / 8;
4106     SDValue Store;
4107
4108     Store = DAG.getStore(Chain, dl, LoadValues[i],
4109                          getMemBasePlusOffset(Dst, DstOff, dl, DAG),
4110                          DstPtrInfo.getWithOffset(DstOff), isVol, false, Align);
4111     OutChains.push_back(Store);
4112     DstOff += VTSize;
4113   }
4114
4115   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
4116 }
4117
4118 /// \brief Lower the call to 'memset' intrinsic function into a series of store
4119 /// operations.
4120 ///
4121 /// \param DAG Selection DAG where lowered code is placed.
4122 /// \param dl Link to corresponding IR location.
4123 /// \param Chain Control flow dependency.
4124 /// \param Dst Pointer to destination memory location.
4125 /// \param Src Value of byte to write into the memory.
4126 /// \param Size Number of bytes to write.
4127 /// \param Align Alignment of the destination in bytes.
4128 /// \param isVol True if destination is volatile.
4129 /// \param DstPtrInfo IR information on the memory pointer.
4130 /// \returns New head in the control flow, if lowering was successful, empty
4131 /// SDValue otherwise.
4132 ///
4133 /// The function tries to replace 'llvm.memset' intrinsic with several store
4134 /// operations and value calculation code. This is usually profitable for small
4135 /// memory size.
4136 static SDValue getMemsetStores(SelectionDAG &DAG, SDLoc dl,
4137                                SDValue Chain, SDValue Dst,
4138                                SDValue Src, uint64_t Size,
4139                                unsigned Align, bool isVol,
4140                                MachinePointerInfo DstPtrInfo) {
4141   // Turn a memset of undef to nop.
4142   if (Src.getOpcode() == ISD::UNDEF)
4143     return Chain;
4144
4145   // Expand memset to a series of load/store ops if the size operand
4146   // falls below a certain threshold.
4147   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4148   std::vector<EVT> MemOps;
4149   bool DstAlignCanChange = false;
4150   MachineFunction &MF = DAG.getMachineFunction();
4151   MachineFrameInfo *MFI = MF.getFrameInfo();
4152   bool OptSize = MF.getFunction()->getAttributes().
4153     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
4154   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4155   if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
4156     DstAlignCanChange = true;
4157   bool IsZeroVal =
4158     isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
4159   if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
4160                                 Size, (DstAlignCanChange ? 0 : Align), 0,
4161                                 true, IsZeroVal, false, true, DAG, TLI))
4162     return SDValue();
4163
4164   if (DstAlignCanChange) {
4165     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4166     unsigned NewAlign = (unsigned) TLI.getDataLayout()->getABITypeAlignment(Ty);
4167     if (NewAlign > Align) {
4168       // Give the stack frame object a larger alignment if needed.
4169       if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
4170         MFI->setObjectAlignment(FI->getIndex(), NewAlign);
4171       Align = NewAlign;
4172     }
4173   }
4174
4175   SmallVector<SDValue, 8> OutChains;
4176   uint64_t DstOff = 0;
4177   unsigned NumMemOps = MemOps.size();
4178
4179   // Find the largest store and generate the bit pattern for it.
4180   EVT LargestVT = MemOps[0];
4181   for (unsigned i = 1; i < NumMemOps; i++)
4182     if (MemOps[i].bitsGT(LargestVT))
4183       LargestVT = MemOps[i];
4184   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
4185
4186   for (unsigned i = 0; i < NumMemOps; i++) {
4187     EVT VT = MemOps[i];
4188     unsigned VTSize = VT.getSizeInBits() / 8;
4189     if (VTSize > Size) {
4190       // Issuing an unaligned load / store pair  that overlaps with the previous
4191       // pair. Adjust the offset accordingly.
4192       assert(i == NumMemOps-1 && i != 0);
4193       DstOff -= VTSize - Size;
4194     }
4195
4196     // If this store is smaller than the largest store see whether we can get
4197     // the smaller value for free with a truncate.
4198     SDValue Value = MemSetValue;
4199     if (VT.bitsLT(LargestVT)) {
4200       if (!LargestVT.isVector() && !VT.isVector() &&
4201           TLI.isTruncateFree(LargestVT, VT))
4202         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
4203       else
4204         Value = getMemsetValue(Src, VT, DAG, dl);
4205     }
4206     assert(Value.getValueType() == VT && "Value with wrong type.");
4207     SDValue Store = DAG.getStore(Chain, dl, Value,
4208                                  getMemBasePlusOffset(Dst, DstOff, dl, DAG),
4209                                  DstPtrInfo.getWithOffset(DstOff),
4210                                  isVol, false, Align);
4211     OutChains.push_back(Store);
4212     DstOff += VT.getSizeInBits() / 8;
4213     Size -= VTSize;
4214   }
4215
4216   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
4217 }
4218
4219 SDValue SelectionDAG::getMemcpy(SDValue Chain, SDLoc dl, SDValue Dst,
4220                                 SDValue Src, SDValue Size,
4221                                 unsigned Align, bool isVol, bool AlwaysInline,
4222                                 MachinePointerInfo DstPtrInfo,
4223                                 MachinePointerInfo SrcPtrInfo) {
4224   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
4225
4226   // Check to see if we should lower the memcpy to loads and stores first.
4227   // For cases within the target-specified limits, this is the best choice.
4228   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4229   if (ConstantSize) {
4230     // Memcpy with size zero? Just return the original chain.
4231     if (ConstantSize->isNullValue())
4232       return Chain;
4233
4234     SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
4235                                              ConstantSize->getZExtValue(),Align,
4236                                 isVol, false, DstPtrInfo, SrcPtrInfo);
4237     if (Result.getNode())
4238       return Result;
4239   }
4240
4241   // Then check to see if we should lower the memcpy with target-specific
4242   // code. If the target chooses to do this, this is the next best.
4243   SDValue Result =
4244       TSI->EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align,
4245                                    isVol, AlwaysInline, DstPtrInfo, SrcPtrInfo);
4246   if (Result.getNode())
4247     return Result;
4248
4249   // If we really need inline code and the target declined to provide it,
4250   // use a (potentially long) sequence of loads and stores.
4251   if (AlwaysInline) {
4252     assert(ConstantSize && "AlwaysInline requires a constant size!");
4253     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
4254                                    ConstantSize->getZExtValue(), Align, isVol,
4255                                    true, DstPtrInfo, SrcPtrInfo);
4256   }
4257
4258   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
4259   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
4260   // respect volatile, so they may do things like read or write memory
4261   // beyond the given memory regions. But fixing this isn't easy, and most
4262   // people don't care.
4263
4264   // Emit a library call.
4265   TargetLowering::ArgListTy Args;
4266   TargetLowering::ArgListEntry Entry;
4267   Entry.Ty = TLI->getDataLayout()->getIntPtrType(*getContext());
4268   Entry.Node = Dst; Args.push_back(Entry);
4269   Entry.Node = Src; Args.push_back(Entry);
4270   Entry.Node = Size; Args.push_back(Entry);
4271   // FIXME: pass in SDLoc
4272   TargetLowering::CallLoweringInfo CLI(*this);
4273   CLI.setDebugLoc(dl).setChain(Chain)
4274     .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
4275                Type::getVoidTy(*getContext()),
4276                getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
4277                                  TLI->getPointerTy()), std::move(Args), 0)
4278     .setDiscardResult();
4279   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
4280
4281   return CallResult.second;
4282 }
4283
4284 SDValue SelectionDAG::getMemmove(SDValue Chain, SDLoc dl, SDValue Dst,
4285                                  SDValue Src, SDValue Size,
4286                                  unsigned Align, bool isVol,
4287                                  MachinePointerInfo DstPtrInfo,
4288                                  MachinePointerInfo SrcPtrInfo) {
4289   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
4290
4291   // Check to see if we should lower the memmove to loads and stores first.
4292   // For cases within the target-specified limits, this is the best choice.
4293   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4294   if (ConstantSize) {
4295     // Memmove with size zero? Just return the original chain.
4296     if (ConstantSize->isNullValue())
4297       return Chain;
4298
4299     SDValue Result =
4300       getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
4301                                ConstantSize->getZExtValue(), Align, isVol,
4302                                false, DstPtrInfo, SrcPtrInfo);
4303     if (Result.getNode())
4304       return Result;
4305   }
4306
4307   // Then check to see if we should lower the memmove with target-specific
4308   // code. If the target chooses to do this, this is the next best.
4309   SDValue Result = TSI->EmitTargetCodeForMemmove(
4310       *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
4311   if (Result.getNode())
4312     return Result;
4313
4314   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
4315   // not be safe.  See memcpy above for more details.
4316
4317   // Emit a library call.
4318   TargetLowering::ArgListTy Args;
4319   TargetLowering::ArgListEntry Entry;
4320   Entry.Ty = TLI->getDataLayout()->getIntPtrType(*getContext());
4321   Entry.Node = Dst; Args.push_back(Entry);
4322   Entry.Node = Src; Args.push_back(Entry);
4323   Entry.Node = Size; Args.push_back(Entry);
4324   // FIXME:  pass in SDLoc
4325   TargetLowering::CallLoweringInfo CLI(*this);
4326   CLI.setDebugLoc(dl).setChain(Chain)
4327     .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
4328                Type::getVoidTy(*getContext()),
4329                getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
4330                                  TLI->getPointerTy()), std::move(Args), 0)
4331     .setDiscardResult();
4332   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
4333
4334   return CallResult.second;
4335 }
4336
4337 SDValue SelectionDAG::getMemset(SDValue Chain, SDLoc dl, SDValue Dst,
4338                                 SDValue Src, SDValue Size,
4339                                 unsigned Align, bool isVol,
4340                                 MachinePointerInfo DstPtrInfo) {
4341   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
4342
4343   // Check to see if we should lower the memset to stores first.
4344   // For cases within the target-specified limits, this is the best choice.
4345   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4346   if (ConstantSize) {
4347     // Memset with size zero? Just return the original chain.
4348     if (ConstantSize->isNullValue())
4349       return Chain;
4350
4351     SDValue Result =
4352       getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
4353                       Align, isVol, DstPtrInfo);
4354
4355     if (Result.getNode())
4356       return Result;
4357   }
4358
4359   // Then check to see if we should lower the memset with target-specific
4360   // code. If the target chooses to do this, this is the next best.
4361   SDValue Result = TSI->EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src,
4362                                                 Size, Align, isVol, DstPtrInfo);
4363   if (Result.getNode())
4364     return Result;
4365
4366   // Emit a library call.
4367   Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(*getContext());
4368   TargetLowering::ArgListTy Args;
4369   TargetLowering::ArgListEntry Entry;
4370   Entry.Node = Dst; Entry.Ty = IntPtrTy;
4371   Args.push_back(Entry);
4372   Entry.Node = Src;
4373   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
4374   Args.push_back(Entry);
4375   Entry.Node = Size;
4376   Entry.Ty = IntPtrTy;
4377   Args.push_back(Entry);
4378
4379   // FIXME: pass in SDLoc
4380   TargetLowering::CallLoweringInfo CLI(*this);
4381   CLI.setDebugLoc(dl).setChain(Chain)
4382     .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
4383                Type::getVoidTy(*getContext()),
4384                getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
4385                                  TLI->getPointerTy()), std::move(Args), 0)
4386     .setDiscardResult();
4387
4388   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
4389   return CallResult.second;
4390 }
4391
4392 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4393                                 SDVTList VTList, ArrayRef<SDValue> Ops,
4394                                 MachineMemOperand *MMO,
4395                                 AtomicOrdering SuccessOrdering,
4396                                 AtomicOrdering FailureOrdering,
4397                                 SynchronizationScope SynchScope) {
4398   FoldingSetNodeID ID;
4399   ID.AddInteger(MemVT.getRawBits());
4400   AddNodeIDNode(ID, Opcode, VTList, Ops);
4401   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4402   void* IP = nullptr;
4403   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4404     cast<AtomicSDNode>(E)->refineAlignment(MMO);
4405     return SDValue(E, 0);
4406   }
4407
4408   // Allocate the operands array for the node out of the BumpPtrAllocator, since
4409   // SDNode doesn't have access to it.  This memory will be "leaked" when
4410   // the node is deallocated, but recovered when the allocator is released.
4411   // If the number of operands is less than 5 we use AtomicSDNode's internal
4412   // storage.
4413   unsigned NumOps = Ops.size();
4414   SDUse *DynOps = NumOps > 4 ? OperandAllocator.Allocate<SDUse>(NumOps)
4415                              : nullptr;
4416
4417   SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl.getIROrder(),
4418                                                dl.getDebugLoc(), VTList, MemVT,
4419                                                Ops.data(), DynOps, NumOps, MMO,
4420                                                SuccessOrdering, FailureOrdering,
4421                                                SynchScope);
4422   CSEMap.InsertNode(N, IP);
4423   InsertNode(N);
4424   return SDValue(N, 0);
4425 }
4426
4427 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4428                                 SDVTList VTList, ArrayRef<SDValue> Ops,
4429                                 MachineMemOperand *MMO,
4430                                 AtomicOrdering Ordering,
4431                                 SynchronizationScope SynchScope) {
4432   return getAtomic(Opcode, dl, MemVT, VTList, Ops, MMO, Ordering,
4433                    Ordering, SynchScope);
4434 }
4435
4436 SDValue SelectionDAG::getAtomicCmpSwap(
4437     unsigned Opcode, SDLoc dl, EVT MemVT, SDVTList VTs, SDValue Chain,
4438     SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo,
4439     unsigned Alignment, AtomicOrdering SuccessOrdering,
4440     AtomicOrdering FailureOrdering, SynchronizationScope SynchScope) {
4441   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
4442          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
4443   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
4444
4445   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
4446     Alignment = getEVTAlignment(MemVT);
4447
4448   MachineFunction &MF = getMachineFunction();
4449
4450   // FIXME: Volatile isn't really correct; we should keep track of atomic
4451   // orderings in the memoperand.
4452   unsigned Flags = MachineMemOperand::MOVolatile;
4453   Flags |= MachineMemOperand::MOLoad;
4454   Flags |= MachineMemOperand::MOStore;
4455
4456   MachineMemOperand *MMO =
4457     MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment);
4458
4459   return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO,
4460                           SuccessOrdering, FailureOrdering, SynchScope);
4461 }
4462
4463 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, SDLoc dl, EVT MemVT,
4464                                        SDVTList VTs, SDValue Chain, SDValue Ptr,
4465                                        SDValue Cmp, SDValue Swp,
4466                                        MachineMemOperand *MMO,
4467                                        AtomicOrdering SuccessOrdering,
4468                                        AtomicOrdering FailureOrdering,
4469                                        SynchronizationScope SynchScope) {
4470   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
4471          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
4472   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
4473
4474   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
4475   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO,
4476                    SuccessOrdering, FailureOrdering, SynchScope);
4477 }
4478
4479 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4480                                 SDValue Chain,
4481                                 SDValue Ptr, SDValue Val,
4482                                 const Value* PtrVal,
4483                                 unsigned Alignment,
4484                                 AtomicOrdering Ordering,
4485                                 SynchronizationScope SynchScope) {
4486   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
4487     Alignment = getEVTAlignment(MemVT);
4488
4489   MachineFunction &MF = getMachineFunction();
4490   // An atomic store does not load. An atomic load does not store.
4491   // (An atomicrmw obviously both loads and stores.)
4492   // For now, atomics are considered to be volatile always, and they are
4493   // chained as such.
4494   // FIXME: Volatile isn't really correct; we should keep track of atomic
4495   // orderings in the memoperand.
4496   unsigned Flags = MachineMemOperand::MOVolatile;
4497   if (Opcode != ISD::ATOMIC_STORE)
4498     Flags |= MachineMemOperand::MOLoad;
4499   if (Opcode != ISD::ATOMIC_LOAD)
4500     Flags |= MachineMemOperand::MOStore;
4501
4502   MachineMemOperand *MMO =
4503     MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
4504                             MemVT.getStoreSize(), Alignment);
4505
4506   return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO,
4507                    Ordering, SynchScope);
4508 }
4509
4510 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4511                                 SDValue Chain,
4512                                 SDValue Ptr, SDValue Val,
4513                                 MachineMemOperand *MMO,
4514                                 AtomicOrdering Ordering,
4515                                 SynchronizationScope SynchScope) {
4516   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
4517           Opcode == ISD::ATOMIC_LOAD_SUB ||
4518           Opcode == ISD::ATOMIC_LOAD_AND ||
4519           Opcode == ISD::ATOMIC_LOAD_OR ||
4520           Opcode == ISD::ATOMIC_LOAD_XOR ||
4521           Opcode == ISD::ATOMIC_LOAD_NAND ||
4522           Opcode == ISD::ATOMIC_LOAD_MIN ||
4523           Opcode == ISD::ATOMIC_LOAD_MAX ||
4524           Opcode == ISD::ATOMIC_LOAD_UMIN ||
4525           Opcode == ISD::ATOMIC_LOAD_UMAX ||
4526           Opcode == ISD::ATOMIC_SWAP ||
4527           Opcode == ISD::ATOMIC_STORE) &&
4528          "Invalid Atomic Op");
4529
4530   EVT VT = Val.getValueType();
4531
4532   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
4533                                                getVTList(VT, MVT::Other);
4534   SDValue Ops[] = {Chain, Ptr, Val};
4535   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO, Ordering, SynchScope);
4536 }
4537
4538 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4539                                 EVT VT, SDValue Chain,
4540                                 SDValue Ptr,
4541                                 MachineMemOperand *MMO,
4542                                 AtomicOrdering Ordering,
4543                                 SynchronizationScope SynchScope) {
4544   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
4545
4546   SDVTList VTs = getVTList(VT, MVT::Other);
4547   SDValue Ops[] = {Chain, Ptr};
4548   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO, Ordering, SynchScope);
4549 }
4550
4551 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
4552 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, SDLoc dl) {
4553   if (Ops.size() == 1)
4554     return Ops[0];
4555
4556   SmallVector<EVT, 4> VTs;
4557   VTs.reserve(Ops.size());
4558   for (unsigned i = 0; i < Ops.size(); ++i)
4559     VTs.push_back(Ops[i].getValueType());
4560   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
4561 }
4562
4563 SDValue
4564 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDLoc dl, SDVTList VTList,
4565                                   ArrayRef<SDValue> Ops,
4566                                   EVT MemVT, MachinePointerInfo PtrInfo,
4567                                   unsigned Align, bool Vol,
4568                                   bool ReadMem, bool WriteMem, unsigned Size) {
4569   if (Align == 0)  // Ensure that codegen never sees alignment 0
4570     Align = getEVTAlignment(MemVT);
4571
4572   MachineFunction &MF = getMachineFunction();
4573   unsigned Flags = 0;
4574   if (WriteMem)
4575     Flags |= MachineMemOperand::MOStore;
4576   if (ReadMem)
4577     Flags |= MachineMemOperand::MOLoad;
4578   if (Vol)
4579     Flags |= MachineMemOperand::MOVolatile;
4580   if (!Size)
4581     Size = MemVT.getStoreSize();
4582   MachineMemOperand *MMO =
4583     MF.getMachineMemOperand(PtrInfo, Flags, Size, Align);
4584
4585   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
4586 }
4587
4588 SDValue
4589 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDLoc dl, SDVTList VTList,
4590                                   ArrayRef<SDValue> Ops, EVT MemVT,
4591                                   MachineMemOperand *MMO) {
4592   assert((Opcode == ISD::INTRINSIC_VOID ||
4593           Opcode == ISD::INTRINSIC_W_CHAIN ||
4594           Opcode == ISD::PREFETCH ||
4595           Opcode == ISD::LIFETIME_START ||
4596           Opcode == ISD::LIFETIME_END ||
4597           (Opcode <= INT_MAX &&
4598            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
4599          "Opcode is not a memory-accessing opcode!");
4600
4601   // Memoize the node unless it returns a flag.
4602   MemIntrinsicSDNode *N;
4603   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
4604     FoldingSetNodeID ID;
4605     AddNodeIDNode(ID, Opcode, VTList, Ops);
4606     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4607     void *IP = nullptr;
4608     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4609       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
4610       return SDValue(E, 0);
4611     }
4612
4613     N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl.getIROrder(),
4614                                                dl.getDebugLoc(), VTList, Ops,
4615                                                MemVT, MMO);
4616     CSEMap.InsertNode(N, IP);
4617   } else {
4618     N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl.getIROrder(),
4619                                                dl.getDebugLoc(), VTList, Ops,
4620                                                MemVT, MMO);
4621   }
4622   InsertNode(N);
4623   return SDValue(N, 0);
4624 }
4625
4626 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
4627 /// MachinePointerInfo record from it.  This is particularly useful because the
4628 /// code generator has many cases where it doesn't bother passing in a
4629 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
4630 static MachinePointerInfo InferPointerInfo(SDValue Ptr, int64_t Offset = 0) {
4631   // If this is FI+Offset, we can model it.
4632   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
4633     return MachinePointerInfo::getFixedStack(FI->getIndex(), Offset);
4634
4635   // If this is (FI+Offset1)+Offset2, we can model it.
4636   if (Ptr.getOpcode() != ISD::ADD ||
4637       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
4638       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
4639     return MachinePointerInfo();
4640
4641   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4642   return MachinePointerInfo::getFixedStack(FI, Offset+
4643                        cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
4644 }
4645
4646 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
4647 /// MachinePointerInfo record from it.  This is particularly useful because the
4648 /// code generator has many cases where it doesn't bother passing in a
4649 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
4650 static MachinePointerInfo InferPointerInfo(SDValue Ptr, SDValue OffsetOp) {
4651   // If the 'Offset' value isn't a constant, we can't handle this.
4652   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
4653     return InferPointerInfo(Ptr, OffsetNode->getSExtValue());
4654   if (OffsetOp.getOpcode() == ISD::UNDEF)
4655     return InferPointerInfo(Ptr);
4656   return MachinePointerInfo();
4657 }
4658
4659
4660 SDValue
4661 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
4662                       EVT VT, SDLoc dl, SDValue Chain,
4663                       SDValue Ptr, SDValue Offset,
4664                       MachinePointerInfo PtrInfo, EVT MemVT,
4665                       bool isVolatile, bool isNonTemporal, bool isInvariant,
4666                       unsigned Alignment, const AAMDNodes &AAInfo,
4667                       const MDNode *Ranges) {
4668   assert(Chain.getValueType() == MVT::Other &&
4669         "Invalid chain type");
4670   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
4671     Alignment = getEVTAlignment(VT);
4672
4673   unsigned Flags = MachineMemOperand::MOLoad;
4674   if (isVolatile)
4675     Flags |= MachineMemOperand::MOVolatile;
4676   if (isNonTemporal)
4677     Flags |= MachineMemOperand::MONonTemporal;
4678   if (isInvariant)
4679     Flags |= MachineMemOperand::MOInvariant;
4680
4681   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
4682   // clients.
4683   if (PtrInfo.V.isNull())
4684     PtrInfo = InferPointerInfo(Ptr, Offset);
4685
4686   MachineFunction &MF = getMachineFunction();
4687   MachineMemOperand *MMO =
4688     MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment,
4689                             AAInfo, Ranges);
4690   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
4691 }
4692
4693 SDValue
4694 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
4695                       EVT VT, SDLoc dl, SDValue Chain,
4696                       SDValue Ptr, SDValue Offset, EVT MemVT,
4697                       MachineMemOperand *MMO) {
4698   if (VT == MemVT) {
4699     ExtType = ISD::NON_EXTLOAD;
4700   } else if (ExtType == ISD::NON_EXTLOAD) {
4701     assert(VT == MemVT && "Non-extending load from different memory type!");
4702   } else {
4703     // Extending load.
4704     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
4705            "Should only be an extending load, not truncating!");
4706     assert(VT.isInteger() == MemVT.isInteger() &&
4707            "Cannot convert from FP to Int or Int -> FP!");
4708     assert(VT.isVector() == MemVT.isVector() &&
4709            "Cannot use trunc store to convert to or from a vector!");
4710     assert((!VT.isVector() ||
4711             VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
4712            "Cannot use trunc store to change the number of vector elements!");
4713   }
4714
4715   bool Indexed = AM != ISD::UNINDEXED;
4716   assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
4717          "Unindexed load with an offset!");
4718
4719   SDVTList VTs = Indexed ?
4720     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
4721   SDValue Ops[] = { Chain, Ptr, Offset };
4722   FoldingSetNodeID ID;
4723   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
4724   ID.AddInteger(MemVT.getRawBits());
4725   ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile(),
4726                                      MMO->isNonTemporal(),
4727                                      MMO->isInvariant()));
4728   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4729   void *IP = nullptr;
4730   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4731     cast<LoadSDNode>(E)->refineAlignment(MMO);
4732     return SDValue(E, 0);
4733   }
4734   SDNode *N = new (NodeAllocator) LoadSDNode(Ops, dl.getIROrder(),
4735                                              dl.getDebugLoc(), VTs, AM, ExtType,
4736                                              MemVT, MMO);
4737   CSEMap.InsertNode(N, IP);
4738   InsertNode(N);
4739   return SDValue(N, 0);
4740 }
4741
4742 SDValue SelectionDAG::getLoad(EVT VT, SDLoc dl,
4743                               SDValue Chain, SDValue Ptr,
4744                               MachinePointerInfo PtrInfo,
4745                               bool isVolatile, bool isNonTemporal,
4746                               bool isInvariant, unsigned Alignment,
4747                               const AAMDNodes &AAInfo,
4748                               const MDNode *Ranges) {
4749   SDValue Undef = getUNDEF(Ptr.getValueType());
4750   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
4751                  PtrInfo, VT, isVolatile, isNonTemporal, isInvariant, Alignment,
4752                  AAInfo, Ranges);
4753 }
4754
4755 SDValue SelectionDAG::getLoad(EVT VT, SDLoc dl,
4756                               SDValue Chain, SDValue Ptr,
4757                               MachineMemOperand *MMO) {
4758   SDValue Undef = getUNDEF(Ptr.getValueType());
4759   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
4760                  VT, MMO);
4761 }
4762
4763 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, SDLoc dl, EVT VT,
4764                                  SDValue Chain, SDValue Ptr,
4765                                  MachinePointerInfo PtrInfo, EVT MemVT,
4766                                  bool isVolatile, bool isNonTemporal,
4767                                  bool isInvariant, unsigned Alignment,
4768                                  const AAMDNodes &AAInfo) {
4769   SDValue Undef = getUNDEF(Ptr.getValueType());
4770   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
4771                  PtrInfo, MemVT, isVolatile, isNonTemporal, isInvariant,
4772                  Alignment, AAInfo);
4773 }
4774
4775
4776 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, SDLoc dl, EVT VT,
4777                                  SDValue Chain, SDValue Ptr, EVT MemVT,
4778                                  MachineMemOperand *MMO) {
4779   SDValue Undef = getUNDEF(Ptr.getValueType());
4780   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
4781                  MemVT, MMO);
4782 }
4783
4784 SDValue
4785 SelectionDAG::getIndexedLoad(SDValue OrigLoad, SDLoc dl, SDValue Base,
4786                              SDValue Offset, ISD::MemIndexedMode AM) {
4787   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
4788   assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
4789          "Load is already a indexed load!");
4790   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
4791                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
4792                  LD->getMemoryVT(), LD->isVolatile(), LD->isNonTemporal(),
4793                  false, LD->getAlignment());
4794 }
4795
4796 SDValue SelectionDAG::getStore(SDValue Chain, SDLoc dl, SDValue Val,
4797                                SDValue Ptr, MachinePointerInfo PtrInfo,
4798                                bool isVolatile, bool isNonTemporal,
4799                                unsigned Alignment, const AAMDNodes &AAInfo) {
4800   assert(Chain.getValueType() == MVT::Other &&
4801         "Invalid chain type");
4802   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
4803     Alignment = getEVTAlignment(Val.getValueType());
4804
4805   unsigned Flags = MachineMemOperand::MOStore;
4806   if (isVolatile)
4807     Flags |= MachineMemOperand::MOVolatile;
4808   if (isNonTemporal)
4809     Flags |= MachineMemOperand::MONonTemporal;
4810
4811   if (PtrInfo.V.isNull())
4812     PtrInfo = InferPointerInfo(Ptr);
4813
4814   MachineFunction &MF = getMachineFunction();
4815   MachineMemOperand *MMO =
4816     MF.getMachineMemOperand(PtrInfo, Flags,
4817                             Val.getValueType().getStoreSize(), Alignment,
4818                             AAInfo);
4819
4820   return getStore(Chain, dl, Val, Ptr, MMO);
4821 }
4822
4823 SDValue SelectionDAG::getStore(SDValue Chain, SDLoc dl, SDValue Val,
4824                                SDValue Ptr, MachineMemOperand *MMO) {
4825   assert(Chain.getValueType() == MVT::Other &&
4826         "Invalid chain type");
4827   EVT VT = Val.getValueType();
4828   SDVTList VTs = getVTList(MVT::Other);
4829   SDValue Undef = getUNDEF(Ptr.getValueType());
4830   SDValue Ops[] = { Chain, Val, Ptr, Undef };
4831   FoldingSetNodeID ID;
4832   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
4833   ID.AddInteger(VT.getRawBits());
4834   ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(),
4835                                      MMO->isNonTemporal(), MMO->isInvariant()));
4836   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4837   void *IP = nullptr;
4838   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4839     cast<StoreSDNode>(E)->refineAlignment(MMO);
4840     return SDValue(E, 0);
4841   }
4842   SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(),
4843                                               dl.getDebugLoc(), VTs,
4844                                               ISD::UNINDEXED, false, VT, MMO);
4845   CSEMap.InsertNode(N, IP);
4846   InsertNode(N);
4847   return SDValue(N, 0);
4848 }
4849
4850 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDLoc dl, SDValue Val,
4851                                     SDValue Ptr, MachinePointerInfo PtrInfo,
4852                                     EVT SVT,bool isVolatile, bool isNonTemporal,
4853                                     unsigned Alignment,
4854                                     const AAMDNodes &AAInfo) {
4855   assert(Chain.getValueType() == MVT::Other &&
4856         "Invalid chain type");
4857   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
4858     Alignment = getEVTAlignment(SVT);
4859
4860   unsigned Flags = MachineMemOperand::MOStore;
4861   if (isVolatile)
4862     Flags |= MachineMemOperand::MOVolatile;
4863   if (isNonTemporal)
4864     Flags |= MachineMemOperand::MONonTemporal;
4865
4866   if (PtrInfo.V.isNull())
4867     PtrInfo = InferPointerInfo(Ptr);
4868
4869   MachineFunction &MF = getMachineFunction();
4870   MachineMemOperand *MMO =
4871     MF.getMachineMemOperand(PtrInfo, Flags, SVT.getStoreSize(), Alignment,
4872                             AAInfo);
4873
4874   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
4875 }
4876
4877 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDLoc dl, SDValue Val,
4878                                     SDValue Ptr, EVT SVT,
4879                                     MachineMemOperand *MMO) {
4880   EVT VT = Val.getValueType();
4881
4882   assert(Chain.getValueType() == MVT::Other &&
4883         "Invalid chain type");
4884   if (VT == SVT)
4885     return getStore(Chain, dl, Val, Ptr, MMO);
4886
4887   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
4888          "Should only be a truncating store, not extending!");
4889   assert(VT.isInteger() == SVT.isInteger() &&
4890          "Can't do FP-INT conversion!");
4891   assert(VT.isVector() == SVT.isVector() &&
4892          "Cannot use trunc store to convert to or from a vector!");
4893   assert((!VT.isVector() ||
4894           VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
4895          "Cannot use trunc store to change the number of vector elements!");
4896
4897   SDVTList VTs = getVTList(MVT::Other);
4898   SDValue Undef = getUNDEF(Ptr.getValueType());
4899   SDValue Ops[] = { Chain, Val, Ptr, Undef };
4900   FoldingSetNodeID ID;
4901   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
4902   ID.AddInteger(SVT.getRawBits());
4903   ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile(),
4904                                      MMO->isNonTemporal(), MMO->isInvariant()));
4905   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4906   void *IP = nullptr;
4907   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4908     cast<StoreSDNode>(E)->refineAlignment(MMO);
4909     return SDValue(E, 0);
4910   }
4911   SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(),
4912                                               dl.getDebugLoc(), VTs,
4913                                               ISD::UNINDEXED, true, SVT, MMO);
4914   CSEMap.InsertNode(N, IP);
4915   InsertNode(N);
4916   return SDValue(N, 0);
4917 }
4918
4919 SDValue
4920 SelectionDAG::getIndexedStore(SDValue OrigStore, SDLoc dl, SDValue Base,
4921                               SDValue Offset, ISD::MemIndexedMode AM) {
4922   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
4923   assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
4924          "Store is already a indexed store!");
4925   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
4926   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
4927   FoldingSetNodeID ID;
4928   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
4929   ID.AddInteger(ST->getMemoryVT().getRawBits());
4930   ID.AddInteger(ST->getRawSubclassData());
4931   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
4932   void *IP = nullptr;
4933   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4934     return SDValue(E, 0);
4935
4936   SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(),
4937                                               dl.getDebugLoc(), VTs, AM,
4938                                               ST->isTruncatingStore(),
4939                                               ST->getMemoryVT(),
4940                                               ST->getMemOperand());
4941   CSEMap.InsertNode(N, IP);
4942   InsertNode(N);
4943   return SDValue(N, 0);
4944 }
4945
4946 SDValue
4947 SelectionDAG::getMaskedLoad(EVT VT, SDLoc dl, SDValue Chain,
4948                             SDValue Ptr, SDValue Mask, SDValue Src0, EVT MemVT,
4949                             MachineMemOperand *MMO, ISD::LoadExtType ExtTy) {
4950
4951   SDVTList VTs = getVTList(VT, MVT::Other);
4952   SDValue Ops[] = { Chain, Ptr, Mask, Src0 };
4953   FoldingSetNodeID ID;
4954   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
4955   ID.AddInteger(VT.getRawBits());
4956   ID.AddInteger(encodeMemSDNodeFlags(ExtTy, ISD::UNINDEXED,
4957                                      MMO->isVolatile(),
4958                                      MMO->isNonTemporal(),
4959                                      MMO->isInvariant()));
4960   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4961   void *IP = nullptr;
4962   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4963     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
4964     return SDValue(E, 0);
4965   }
4966   SDNode *N = new (NodeAllocator) MaskedLoadSDNode(dl.getIROrder(),
4967                                              dl.getDebugLoc(), Ops, 4, VTs,
4968                                              ExtTy, MemVT, MMO);
4969   CSEMap.InsertNode(N, IP);
4970   InsertNode(N);
4971   return SDValue(N, 0);
4972 }
4973
4974 SDValue SelectionDAG::getMaskedStore(SDValue Chain, SDLoc dl, SDValue Val,
4975                                      SDValue Ptr, SDValue Mask, EVT MemVT,
4976                                      MachineMemOperand *MMO, bool isTrunc) {
4977   assert(Chain.getValueType() == MVT::Other &&
4978         "Invalid chain type");
4979   EVT VT = Val.getValueType();
4980   SDVTList VTs = getVTList(MVT::Other);
4981   SDValue Ops[] = { Chain, Ptr, Mask, Val };
4982   FoldingSetNodeID ID;
4983   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
4984   ID.AddInteger(VT.getRawBits());
4985   ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(),
4986                                      MMO->isNonTemporal(), MMO->isInvariant()));
4987   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4988   void *IP = nullptr;
4989   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4990     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
4991     return SDValue(E, 0);
4992   }
4993   SDNode *N = new (NodeAllocator) MaskedStoreSDNode(dl.getIROrder(),
4994                                                     dl.getDebugLoc(), Ops, 4,
4995                                                     VTs, isTrunc, MemVT, MMO);
4996   CSEMap.InsertNode(N, IP);
4997   InsertNode(N);
4998   return SDValue(N, 0);
4999 }
5000
5001 SDValue SelectionDAG::getVAArg(EVT VT, SDLoc dl,
5002                                SDValue Chain, SDValue Ptr,
5003                                SDValue SV,
5004                                unsigned Align) {
5005   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, MVT::i32) };
5006   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
5007 }
5008
5009 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
5010                               ArrayRef<SDUse> Ops) {
5011   switch (Ops.size()) {
5012   case 0: return getNode(Opcode, DL, VT);
5013   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
5014   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
5015   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
5016   default: break;
5017   }
5018
5019   // Copy from an SDUse array into an SDValue array for use with
5020   // the regular getNode logic.
5021   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
5022   return getNode(Opcode, DL, VT, NewOps);
5023 }
5024
5025 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
5026                               ArrayRef<SDValue> Ops) {
5027   unsigned NumOps = Ops.size();
5028   switch (NumOps) {
5029   case 0: return getNode(Opcode, DL, VT);
5030   case 1: return getNode(Opcode, DL, VT, Ops[0]);
5031   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
5032   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
5033   default: break;
5034   }
5035
5036   switch (Opcode) {
5037   default: break;
5038   case ISD::SELECT_CC: {
5039     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
5040     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
5041            "LHS and RHS of condition must have same type!");
5042     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
5043            "True and False arms of SelectCC must have same type!");
5044     assert(Ops[2].getValueType() == VT &&
5045            "select_cc node must be of same type as true and false value!");
5046     break;
5047   }
5048   case ISD::BR_CC: {
5049     assert(NumOps == 5 && "BR_CC takes 5 operands!");
5050     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
5051            "LHS/RHS of comparison should match types!");
5052     break;
5053   }
5054   }
5055
5056   // Memoize nodes.
5057   SDNode *N;
5058   SDVTList VTs = getVTList(VT);
5059
5060   if (VT != MVT::Glue) {
5061     FoldingSetNodeID ID;
5062     AddNodeIDNode(ID, Opcode, VTs, Ops);
5063     void *IP = nullptr;
5064
5065     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
5066       return SDValue(E, 0);
5067
5068     N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(),
5069                                    VTs, Ops);
5070     CSEMap.InsertNode(N, IP);
5071   } else {
5072     N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(),
5073                                    VTs, Ops);
5074   }
5075
5076   InsertNode(N);
5077   return SDValue(N, 0);
5078 }
5079
5080 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL,
5081                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
5082   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
5083 }
5084
5085 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
5086                               ArrayRef<SDValue> Ops) {
5087   if (VTList.NumVTs == 1)
5088     return getNode(Opcode, DL, VTList.VTs[0], Ops);
5089
5090 #if 0
5091   switch (Opcode) {
5092   // FIXME: figure out how to safely handle things like
5093   // int foo(int x) { return 1 << (x & 255); }
5094   // int bar() { return foo(256); }
5095   case ISD::SRA_PARTS:
5096   case ISD::SRL_PARTS:
5097   case ISD::SHL_PARTS:
5098     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5099         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
5100       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
5101     else if (N3.getOpcode() == ISD::AND)
5102       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
5103         // If the and is only masking out bits that cannot effect the shift,
5104         // eliminate the and.
5105         unsigned NumBits = VT.getScalarType().getSizeInBits()*2;
5106         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
5107           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
5108       }
5109     break;
5110   }
5111 #endif
5112
5113   // Memoize the node unless it returns a flag.
5114   SDNode *N;
5115   unsigned NumOps = Ops.size();
5116   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
5117     FoldingSetNodeID ID;
5118     AddNodeIDNode(ID, Opcode, VTList, Ops);
5119     void *IP = nullptr;
5120     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
5121       return SDValue(E, 0);
5122
5123     if (NumOps == 1) {
5124       N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(),
5125                                           DL.getDebugLoc(), VTList, Ops[0]);
5126     } else if (NumOps == 2) {
5127       N = new (NodeAllocator) BinarySDNode(Opcode, DL.getIROrder(),
5128                                            DL.getDebugLoc(), VTList, Ops[0],
5129                                            Ops[1]);
5130     } else if (NumOps == 3) {
5131       N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(),
5132                                             DL.getDebugLoc(), VTList, Ops[0],
5133                                             Ops[1], Ops[2]);
5134     } else {
5135       N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(),
5136                                      VTList, Ops);
5137     }
5138     CSEMap.InsertNode(N, IP);
5139   } else {
5140     if (NumOps == 1) {
5141       N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(),
5142                                           DL.getDebugLoc(), VTList, Ops[0]);
5143     } else if (NumOps == 2) {
5144       N = new (NodeAllocator) BinarySDNode(Opcode, DL.getIROrder(),
5145                                            DL.getDebugLoc(), VTList, Ops[0],
5146                                            Ops[1]);
5147     } else if (NumOps == 3) {
5148       N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(),
5149                                             DL.getDebugLoc(), VTList, Ops[0],
5150                                             Ops[1], Ops[2]);
5151     } else {
5152       N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(),
5153                                      VTList, Ops);
5154     }
5155   }
5156   InsertNode(N);
5157   return SDValue(N, 0);
5158 }
5159
5160 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList) {
5161   return getNode(Opcode, DL, VTList, None);
5162 }
5163
5164 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
5165                               SDValue N1) {
5166   SDValue Ops[] = { N1 };
5167   return getNode(Opcode, DL, VTList, Ops);
5168 }
5169
5170 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
5171                               SDValue N1, SDValue N2) {
5172   SDValue Ops[] = { N1, N2 };
5173   return getNode(Opcode, DL, VTList, Ops);
5174 }
5175
5176 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
5177                               SDValue N1, SDValue N2, SDValue N3) {
5178   SDValue Ops[] = { N1, N2, N3 };
5179   return getNode(Opcode, DL, VTList, Ops);
5180 }
5181
5182 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
5183                               SDValue N1, SDValue N2, SDValue N3,
5184                               SDValue N4) {
5185   SDValue Ops[] = { N1, N2, N3, N4 };
5186   return getNode(Opcode, DL, VTList, Ops);
5187 }
5188
5189 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
5190                               SDValue N1, SDValue N2, SDValue N3,
5191                               SDValue N4, SDValue N5) {
5192   SDValue Ops[] = { N1, N2, N3, N4, N5 };
5193   return getNode(Opcode, DL, VTList, Ops);
5194 }
5195
5196 SDVTList SelectionDAG::getVTList(EVT VT) {
5197   return makeVTList(SDNode::getValueTypeList(VT), 1);
5198 }
5199
5200 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
5201   FoldingSetNodeID ID;
5202   ID.AddInteger(2U);
5203   ID.AddInteger(VT1.getRawBits());
5204   ID.AddInteger(VT2.getRawBits());
5205
5206   void *IP = nullptr;
5207   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
5208   if (!Result) {
5209     EVT *Array = Allocator.Allocate<EVT>(2);
5210     Array[0] = VT1;
5211     Array[1] = VT2;
5212     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
5213     VTListMap.InsertNode(Result, IP);
5214   }
5215   return Result->getSDVTList();
5216 }
5217
5218 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
5219   FoldingSetNodeID ID;
5220   ID.AddInteger(3U);
5221   ID.AddInteger(VT1.getRawBits());
5222   ID.AddInteger(VT2.getRawBits());
5223   ID.AddInteger(VT3.getRawBits());
5224
5225   void *IP = nullptr;
5226   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
5227   if (!Result) {
5228     EVT *Array = Allocator.Allocate<EVT>(3);
5229     Array[0] = VT1;
5230     Array[1] = VT2;
5231     Array[2] = VT3;
5232     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
5233     VTListMap.InsertNode(Result, IP);
5234   }
5235   return Result->getSDVTList();
5236 }
5237
5238 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
5239   FoldingSetNodeID ID;
5240   ID.AddInteger(4U);
5241   ID.AddInteger(VT1.getRawBits());
5242   ID.AddInteger(VT2.getRawBits());
5243   ID.AddInteger(VT3.getRawBits());
5244   ID.AddInteger(VT4.getRawBits());
5245
5246   void *IP = nullptr;
5247   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
5248   if (!Result) {
5249     EVT *Array = Allocator.Allocate<EVT>(4);
5250     Array[0] = VT1;
5251     Array[1] = VT2;
5252     Array[2] = VT3;
5253     Array[3] = VT4;
5254     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
5255     VTListMap.InsertNode(Result, IP);
5256   }
5257   return Result->getSDVTList();
5258 }
5259
5260 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
5261   unsigned NumVTs = VTs.size();
5262   FoldingSetNodeID ID;
5263   ID.AddInteger(NumVTs);
5264   for (unsigned index = 0; index < NumVTs; index++) {
5265     ID.AddInteger(VTs[index].getRawBits());
5266   }
5267
5268   void *IP = nullptr;
5269   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
5270   if (!Result) {
5271     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
5272     std::copy(VTs.begin(), VTs.end(), Array);
5273     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
5274     VTListMap.InsertNode(Result, IP);
5275   }
5276   return Result->getSDVTList();
5277 }
5278
5279
5280 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
5281 /// specified operands.  If the resultant node already exists in the DAG,
5282 /// this does not modify the specified node, instead it returns the node that
5283 /// already exists.  If the resultant node does not exist in the DAG, the
5284 /// input node is returned.  As a degenerate case, if you specify the same
5285 /// input operands as the node already has, the input node is returned.
5286 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
5287   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
5288
5289   // Check to see if there is no change.
5290   if (Op == N->getOperand(0)) return N;
5291
5292   // See if the modified node already exists.
5293   void *InsertPos = nullptr;
5294   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
5295     return Existing;
5296
5297   // Nope it doesn't.  Remove the node from its current place in the maps.
5298   if (InsertPos)
5299     if (!RemoveNodeFromCSEMaps(N))
5300       InsertPos = nullptr;
5301
5302   // Now we update the operands.
5303   N->OperandList[0].set(Op);
5304
5305   // If this gets put into a CSE map, add it.
5306   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
5307   return N;
5308 }
5309
5310 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
5311   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
5312
5313   // Check to see if there is no change.
5314   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
5315     return N;   // No operands changed, just return the input node.
5316
5317   // See if the modified node already exists.
5318   void *InsertPos = nullptr;
5319   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
5320     return Existing;
5321
5322   // Nope it doesn't.  Remove the node from its current place in the maps.
5323   if (InsertPos)
5324     if (!RemoveNodeFromCSEMaps(N))
5325       InsertPos = nullptr;
5326
5327   // Now we update the operands.
5328   if (N->OperandList[0] != Op1)
5329     N->OperandList[0].set(Op1);
5330   if (N->OperandList[1] != Op2)
5331     N->OperandList[1].set(Op2);
5332
5333   // If this gets put into a CSE map, add it.
5334   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
5335   return N;
5336 }
5337
5338 SDNode *SelectionDAG::
5339 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
5340   SDValue Ops[] = { Op1, Op2, Op3 };
5341   return UpdateNodeOperands(N, Ops);
5342 }
5343
5344 SDNode *SelectionDAG::
5345 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
5346                    SDValue Op3, SDValue Op4) {
5347   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
5348   return UpdateNodeOperands(N, Ops);
5349 }
5350
5351 SDNode *SelectionDAG::
5352 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
5353                    SDValue Op3, SDValue Op4, SDValue Op5) {
5354   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
5355   return UpdateNodeOperands(N, Ops);
5356 }
5357
5358 SDNode *SelectionDAG::
5359 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
5360   unsigned NumOps = Ops.size();
5361   assert(N->getNumOperands() == NumOps &&
5362          "Update with wrong number of operands");
5363
5364   // Check to see if there is no change.
5365   bool AnyChange = false;
5366   for (unsigned i = 0; i != NumOps; ++i) {
5367     if (Ops[i] != N->getOperand(i)) {
5368       AnyChange = true;
5369       break;
5370     }
5371   }
5372
5373   // No operands changed, just return the input node.
5374   if (!AnyChange) return N;
5375
5376   // See if the modified node already exists.
5377   void *InsertPos = nullptr;
5378   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
5379     return Existing;
5380
5381   // Nope it doesn't.  Remove the node from its current place in the maps.
5382   if (InsertPos)
5383     if (!RemoveNodeFromCSEMaps(N))
5384       InsertPos = nullptr;
5385
5386   // Now we update the operands.
5387   for (unsigned i = 0; i != NumOps; ++i)
5388     if (N->OperandList[i] != Ops[i])
5389       N->OperandList[i].set(Ops[i]);
5390
5391   // If this gets put into a CSE map, add it.
5392   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
5393   return N;
5394 }
5395
5396 /// DropOperands - Release the operands and set this node to have
5397 /// zero operands.
5398 void SDNode::DropOperands() {
5399   // Unlike the code in MorphNodeTo that does this, we don't need to
5400   // watch for dead nodes here.
5401   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
5402     SDUse &Use = *I++;
5403     Use.set(SDValue());
5404   }
5405 }
5406
5407 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
5408 /// machine opcode.
5409 ///
5410 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5411                                    EVT VT) {
5412   SDVTList VTs = getVTList(VT);
5413   return SelectNodeTo(N, MachineOpc, VTs, None);
5414 }
5415
5416 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5417                                    EVT VT, SDValue Op1) {
5418   SDVTList VTs = getVTList(VT);
5419   SDValue Ops[] = { Op1 };
5420   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5421 }
5422
5423 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5424                                    EVT VT, SDValue Op1,
5425                                    SDValue Op2) {
5426   SDVTList VTs = getVTList(VT);
5427   SDValue Ops[] = { Op1, Op2 };
5428   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5429 }
5430
5431 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5432                                    EVT VT, SDValue Op1,
5433                                    SDValue Op2, SDValue Op3) {
5434   SDVTList VTs = getVTList(VT);
5435   SDValue Ops[] = { Op1, Op2, Op3 };
5436   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5437 }
5438
5439 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5440                                    EVT VT, ArrayRef<SDValue> Ops) {
5441   SDVTList VTs = getVTList(VT);
5442   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5443 }
5444
5445 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5446                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
5447   SDVTList VTs = getVTList(VT1, VT2);
5448   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5449 }
5450
5451 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5452                                    EVT VT1, EVT VT2) {
5453   SDVTList VTs = getVTList(VT1, VT2);
5454   return SelectNodeTo(N, MachineOpc, VTs, None);
5455 }
5456
5457 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5458                                    EVT VT1, EVT VT2, EVT VT3,
5459                                    ArrayRef<SDValue> Ops) {
5460   SDVTList VTs = getVTList(VT1, VT2, VT3);
5461   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5462 }
5463
5464 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5465                                    EVT VT1, EVT VT2, EVT VT3, EVT VT4,
5466                                    ArrayRef<SDValue> Ops) {
5467   SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
5468   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5469 }
5470
5471 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5472                                    EVT VT1, EVT VT2,
5473                                    SDValue Op1) {
5474   SDVTList VTs = getVTList(VT1, VT2);
5475   SDValue Ops[] = { Op1 };
5476   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5477 }
5478
5479 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5480                                    EVT VT1, EVT VT2,
5481                                    SDValue Op1, SDValue Op2) {
5482   SDVTList VTs = getVTList(VT1, VT2);
5483   SDValue Ops[] = { Op1, Op2 };
5484   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5485 }
5486
5487 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5488                                    EVT VT1, EVT VT2,
5489                                    SDValue Op1, SDValue Op2,
5490                                    SDValue Op3) {
5491   SDVTList VTs = getVTList(VT1, VT2);
5492   SDValue Ops[] = { Op1, Op2, Op3 };
5493   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5494 }
5495
5496 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5497                                    EVT VT1, EVT VT2, EVT VT3,
5498                                    SDValue Op1, SDValue Op2,
5499                                    SDValue Op3) {
5500   SDVTList VTs = getVTList(VT1, VT2, VT3);
5501   SDValue Ops[] = { Op1, Op2, Op3 };
5502   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5503 }
5504
5505 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5506                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
5507   N = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
5508   // Reset the NodeID to -1.
5509   N->setNodeId(-1);
5510   return N;
5511 }
5512
5513 /// UpdadeSDLocOnMergedSDNode - If the opt level is -O0 then it throws away
5514 /// the line number information on the merged node since it is not possible to
5515 /// preserve the information that operation is associated with multiple lines.
5516 /// This will make the debugger working better at -O0, were there is a higher
5517 /// probability having other instructions associated with that line.
5518 ///
5519 /// For IROrder, we keep the smaller of the two
5520 SDNode *SelectionDAG::UpdadeSDLocOnMergedSDNode(SDNode *N, SDLoc OLoc) {
5521   DebugLoc NLoc = N->getDebugLoc();
5522   if (!(NLoc.isUnknown()) && (OptLevel == CodeGenOpt::None) &&
5523     (OLoc.getDebugLoc() != NLoc)) {
5524     N->setDebugLoc(DebugLoc());
5525   }
5526   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
5527   N->setIROrder(Order);
5528   return N;
5529 }
5530
5531 /// MorphNodeTo - This *mutates* the specified node to have the specified
5532 /// return type, opcode, and operands.
5533 ///
5534 /// Note that MorphNodeTo returns the resultant node.  If there is already a
5535 /// node of the specified opcode and operands, it returns that node instead of
5536 /// the current one.  Note that the SDLoc need not be the same.
5537 ///
5538 /// Using MorphNodeTo is faster than creating a new node and swapping it in
5539 /// with ReplaceAllUsesWith both because it often avoids allocating a new
5540 /// node, and because it doesn't require CSE recalculation for any of
5541 /// the node's users.
5542 ///
5543 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
5544 /// As a consequence it isn't appropriate to use from within the DAG combiner or
5545 /// the legalizer which maintain worklists that would need to be updated when
5546 /// deleting things.
5547 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
5548                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
5549   unsigned NumOps = Ops.size();
5550   // If an identical node already exists, use it.
5551   void *IP = nullptr;
5552   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
5553     FoldingSetNodeID ID;
5554     AddNodeIDNode(ID, Opc, VTs, Ops);
5555     if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
5556       return UpdadeSDLocOnMergedSDNode(ON, SDLoc(N));
5557   }
5558
5559   if (!RemoveNodeFromCSEMaps(N))
5560     IP = nullptr;
5561
5562   // Start the morphing.
5563   N->NodeType = Opc;
5564   N->ValueList = VTs.VTs;
5565   N->NumValues = VTs.NumVTs;
5566
5567   // Clear the operands list, updating used nodes to remove this from their
5568   // use list.  Keep track of any operands that become dead as a result.
5569   SmallPtrSet<SDNode*, 16> DeadNodeSet;
5570   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
5571     SDUse &Use = *I++;
5572     SDNode *Used = Use.getNode();
5573     Use.set(SDValue());
5574     if (Used->use_empty())
5575       DeadNodeSet.insert(Used);
5576   }
5577
5578   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) {
5579     // Initialize the memory references information.
5580     MN->setMemRefs(nullptr, nullptr);
5581     // If NumOps is larger than the # of operands we can have in a
5582     // MachineSDNode, reallocate the operand list.
5583     if (NumOps > MN->NumOperands || !MN->OperandsNeedDelete) {
5584       if (MN->OperandsNeedDelete)
5585         delete[] MN->OperandList;
5586       if (NumOps > array_lengthof(MN->LocalOperands))
5587         // We're creating a final node that will live unmorphed for the
5588         // remainder of the current SelectionDAG iteration, so we can allocate
5589         // the operands directly out of a pool with no recycling metadata.
5590         MN->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
5591                          Ops.data(), NumOps);
5592       else
5593         MN->InitOperands(MN->LocalOperands, Ops.data(), NumOps);
5594       MN->OperandsNeedDelete = false;
5595     } else
5596       MN->InitOperands(MN->OperandList, Ops.data(), NumOps);
5597   } else {
5598     // If NumOps is larger than the # of operands we currently have, reallocate
5599     // the operand list.
5600     if (NumOps > N->NumOperands) {
5601       if (N->OperandsNeedDelete)
5602         delete[] N->OperandList;
5603       N->InitOperands(new SDUse[NumOps], Ops.data(), NumOps);
5604       N->OperandsNeedDelete = true;
5605     } else
5606       N->InitOperands(N->OperandList, Ops.data(), NumOps);
5607   }
5608
5609   // Delete any nodes that are still dead after adding the uses for the
5610   // new operands.
5611   if (!DeadNodeSet.empty()) {
5612     SmallVector<SDNode *, 16> DeadNodes;
5613     for (SDNode *N : DeadNodeSet)
5614       if (N->use_empty())
5615         DeadNodes.push_back(N);
5616     RemoveDeadNodes(DeadNodes);
5617   }
5618
5619   if (IP)
5620     CSEMap.InsertNode(N, IP);   // Memoize the new node.
5621   return N;
5622 }
5623
5624
5625 /// getMachineNode - These are used for target selectors to create a new node
5626 /// with specified return type(s), MachineInstr opcode, and operands.
5627 ///
5628 /// Note that getMachineNode returns the resultant node.  If there is already a
5629 /// node of the specified opcode and operands, it returns that node instead of
5630 /// the current one.
5631 MachineSDNode *
5632 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT) {
5633   SDVTList VTs = getVTList(VT);
5634   return getMachineNode(Opcode, dl, VTs, None);
5635 }
5636
5637 MachineSDNode *
5638 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT, SDValue Op1) {
5639   SDVTList VTs = getVTList(VT);
5640   SDValue Ops[] = { Op1 };
5641   return getMachineNode(Opcode, dl, VTs, Ops);
5642 }
5643
5644 MachineSDNode *
5645 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT,
5646                              SDValue Op1, SDValue Op2) {
5647   SDVTList VTs = getVTList(VT);
5648   SDValue Ops[] = { Op1, Op2 };
5649   return getMachineNode(Opcode, dl, VTs, Ops);
5650 }
5651
5652 MachineSDNode *
5653 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT,
5654                              SDValue Op1, SDValue Op2, SDValue Op3) {
5655   SDVTList VTs = getVTList(VT);
5656   SDValue Ops[] = { Op1, Op2, Op3 };
5657   return getMachineNode(Opcode, dl, VTs, Ops);
5658 }
5659
5660 MachineSDNode *
5661 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT,
5662                              ArrayRef<SDValue> Ops) {
5663   SDVTList VTs = getVTList(VT);
5664   return getMachineNode(Opcode, dl, VTs, Ops);
5665 }
5666
5667 MachineSDNode *
5668 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1, EVT VT2) {
5669   SDVTList VTs = getVTList(VT1, VT2);
5670   return getMachineNode(Opcode, dl, VTs, None);
5671 }
5672
5673 MachineSDNode *
5674 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5675                              EVT VT1, EVT VT2, SDValue Op1) {
5676   SDVTList VTs = getVTList(VT1, VT2);
5677   SDValue Ops[] = { Op1 };
5678   return getMachineNode(Opcode, dl, VTs, Ops);
5679 }
5680
5681 MachineSDNode *
5682 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5683                              EVT VT1, EVT VT2, SDValue Op1, SDValue Op2) {
5684   SDVTList VTs = getVTList(VT1, VT2);
5685   SDValue Ops[] = { Op1, Op2 };
5686   return getMachineNode(Opcode, dl, VTs, Ops);
5687 }
5688
5689 MachineSDNode *
5690 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5691                              EVT VT1, EVT VT2, SDValue Op1,
5692                              SDValue Op2, SDValue Op3) {
5693   SDVTList VTs = getVTList(VT1, VT2);
5694   SDValue Ops[] = { Op1, Op2, Op3 };
5695   return getMachineNode(Opcode, dl, VTs, Ops);
5696 }
5697
5698 MachineSDNode *
5699 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5700                              EVT VT1, EVT VT2,
5701                              ArrayRef<SDValue> Ops) {
5702   SDVTList VTs = getVTList(VT1, VT2);
5703   return getMachineNode(Opcode, dl, VTs, Ops);
5704 }
5705
5706 MachineSDNode *
5707 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5708                              EVT VT1, EVT VT2, EVT VT3,
5709                              SDValue Op1, SDValue Op2) {
5710   SDVTList VTs = getVTList(VT1, VT2, VT3);
5711   SDValue Ops[] = { Op1, Op2 };
5712   return getMachineNode(Opcode, dl, VTs, Ops);
5713 }
5714
5715 MachineSDNode *
5716 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5717                              EVT VT1, EVT VT2, EVT VT3,
5718                              SDValue Op1, SDValue Op2, SDValue Op3) {
5719   SDVTList VTs = getVTList(VT1, VT2, VT3);
5720   SDValue Ops[] = { Op1, Op2, Op3 };
5721   return getMachineNode(Opcode, dl, VTs, Ops);
5722 }
5723
5724 MachineSDNode *
5725 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5726                              EVT VT1, EVT VT2, EVT VT3,
5727                              ArrayRef<SDValue> Ops) {
5728   SDVTList VTs = getVTList(VT1, VT2, VT3);
5729   return getMachineNode(Opcode, dl, VTs, Ops);
5730 }
5731
5732 MachineSDNode *
5733 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1,
5734                              EVT VT2, EVT VT3, EVT VT4,
5735                              ArrayRef<SDValue> Ops) {
5736   SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
5737   return getMachineNode(Opcode, dl, VTs, Ops);
5738 }
5739
5740 MachineSDNode *
5741 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5742                              ArrayRef<EVT> ResultTys,
5743                              ArrayRef<SDValue> Ops) {
5744   SDVTList VTs = getVTList(ResultTys);
5745   return getMachineNode(Opcode, dl, VTs, Ops);
5746 }
5747
5748 MachineSDNode *
5749 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc DL, SDVTList VTs,
5750                              ArrayRef<SDValue> OpsArray) {
5751   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
5752   MachineSDNode *N;
5753   void *IP = nullptr;
5754   const SDValue *Ops = OpsArray.data();
5755   unsigned NumOps = OpsArray.size();
5756
5757   if (DoCSE) {
5758     FoldingSetNodeID ID;
5759     AddNodeIDNode(ID, ~Opcode, VTs, OpsArray);
5760     IP = nullptr;
5761     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
5762       return cast<MachineSDNode>(UpdadeSDLocOnMergedSDNode(E, DL));
5763     }
5764   }
5765
5766   // Allocate a new MachineSDNode.
5767   N = new (NodeAllocator) MachineSDNode(~Opcode, DL.getIROrder(),
5768                                         DL.getDebugLoc(), VTs);
5769
5770   // Initialize the operands list.
5771   if (NumOps > array_lengthof(N->LocalOperands))
5772     // We're creating a final node that will live unmorphed for the
5773     // remainder of the current SelectionDAG iteration, so we can allocate
5774     // the operands directly out of a pool with no recycling metadata.
5775     N->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
5776                     Ops, NumOps);
5777   else
5778     N->InitOperands(N->LocalOperands, Ops, NumOps);
5779   N->OperandsNeedDelete = false;
5780
5781   if (DoCSE)
5782     CSEMap.InsertNode(N, IP);
5783
5784   InsertNode(N);
5785   return N;
5786 }
5787
5788 /// getTargetExtractSubreg - A convenience function for creating
5789 /// TargetOpcode::EXTRACT_SUBREG nodes.
5790 SDValue
5791 SelectionDAG::getTargetExtractSubreg(int SRIdx, SDLoc DL, EVT VT,
5792                                      SDValue Operand) {
5793   SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
5794   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
5795                                   VT, Operand, SRIdxVal);
5796   return SDValue(Subreg, 0);
5797 }
5798
5799 /// getTargetInsertSubreg - A convenience function for creating
5800 /// TargetOpcode::INSERT_SUBREG nodes.
5801 SDValue
5802 SelectionDAG::getTargetInsertSubreg(int SRIdx, SDLoc DL, EVT VT,
5803                                     SDValue Operand, SDValue Subreg) {
5804   SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
5805   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
5806                                   VT, Operand, Subreg, SRIdxVal);
5807   return SDValue(Result, 0);
5808 }
5809
5810 /// getNodeIfExists - Get the specified node if it's already available, or
5811 /// else return NULL.
5812 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
5813                                       ArrayRef<SDValue> Ops, bool nuw, bool nsw,
5814                                       bool exact) {
5815   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
5816     FoldingSetNodeID ID;
5817     AddNodeIDNode(ID, Opcode, VTList, Ops);
5818     if (isBinOpWithFlags(Opcode))
5819       AddBinaryNodeIDCustom(ID, nuw, nsw, exact);
5820     void *IP = nullptr;
5821     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
5822       return E;
5823   }
5824   return nullptr;
5825 }
5826
5827 /// getDbgValue - Creates a SDDbgValue node.
5828 ///
5829 /// SDNode
5830 SDDbgValue *SelectionDAG::getDbgValue(MDNode *Var, MDNode *Expr, SDNode *N,
5831                                       unsigned R, bool IsIndirect, uint64_t Off,
5832                                       DebugLoc DL, unsigned O) {
5833   return new (Allocator) SDDbgValue(Var, Expr, N, R, IsIndirect, Off, DL, O);
5834 }
5835
5836 /// Constant
5837 SDDbgValue *SelectionDAG::getConstantDbgValue(MDNode *Var, MDNode *Expr,
5838                                               const Value *C, uint64_t Off,
5839                                               DebugLoc DL, unsigned O) {
5840   return new (Allocator) SDDbgValue(Var, Expr, C, Off, DL, O);
5841 }
5842
5843 /// FrameIndex
5844 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(MDNode *Var, MDNode *Expr,
5845                                                 unsigned FI, uint64_t Off,
5846                                                 DebugLoc DL, unsigned O) {
5847   return new (Allocator) SDDbgValue(Var, Expr, FI, Off, DL, O);
5848 }
5849
5850 namespace {
5851
5852 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
5853 /// pointed to by a use iterator is deleted, increment the use iterator
5854 /// so that it doesn't dangle.
5855 ///
5856 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
5857   SDNode::use_iterator &UI;
5858   SDNode::use_iterator &UE;
5859
5860   void NodeDeleted(SDNode *N, SDNode *E) override {
5861     // Increment the iterator as needed.
5862     while (UI != UE && N == *UI)
5863       ++UI;
5864   }
5865
5866 public:
5867   RAUWUpdateListener(SelectionDAG &d,
5868                      SDNode::use_iterator &ui,
5869                      SDNode::use_iterator &ue)
5870     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
5871 };
5872
5873 }
5874
5875 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5876 /// This can cause recursive merging of nodes in the DAG.
5877 ///
5878 /// This version assumes From has a single result value.
5879 ///
5880 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
5881   SDNode *From = FromN.getNode();
5882   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
5883          "Cannot replace with this method!");
5884   assert(From != To.getNode() && "Cannot replace uses of with self");
5885
5886   // Iterate over all the existing uses of From. New uses will be added
5887   // to the beginning of the use list, which we avoid visiting.
5888   // This specifically avoids visiting uses of From that arise while the
5889   // replacement is happening, because any such uses would be the result
5890   // of CSE: If an existing node looks like From after one of its operands
5891   // is replaced by To, we don't want to replace of all its users with To
5892   // too. See PR3018 for more info.
5893   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5894   RAUWUpdateListener Listener(*this, UI, UE);
5895   while (UI != UE) {
5896     SDNode *User = *UI;
5897
5898     // This node is about to morph, remove its old self from the CSE maps.
5899     RemoveNodeFromCSEMaps(User);
5900
5901     // A user can appear in a use list multiple times, and when this
5902     // happens the uses are usually next to each other in the list.
5903     // To help reduce the number of CSE recomputations, process all
5904     // the uses of this user that we can find this way.
5905     do {
5906       SDUse &Use = UI.getUse();
5907       ++UI;
5908       Use.set(To);
5909     } while (UI != UE && *UI == User);
5910
5911     // Now that we have modified User, add it back to the CSE maps.  If it
5912     // already exists there, recursively merge the results together.
5913     AddModifiedNodeToCSEMaps(User);
5914   }
5915
5916   // If we just RAUW'd the root, take note.
5917   if (FromN == getRoot())
5918     setRoot(To);
5919 }
5920
5921 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5922 /// This can cause recursive merging of nodes in the DAG.
5923 ///
5924 /// This version assumes that for each value of From, there is a
5925 /// corresponding value in To in the same position with the same type.
5926 ///
5927 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
5928 #ifndef NDEBUG
5929   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
5930     assert((!From->hasAnyUseOfValue(i) ||
5931             From->getValueType(i) == To->getValueType(i)) &&
5932            "Cannot use this version of ReplaceAllUsesWith!");
5933 #endif
5934
5935   // Handle the trivial case.
5936   if (From == To)
5937     return;
5938
5939   // Iterate over just the existing users of From. See the comments in
5940   // the ReplaceAllUsesWith above.
5941   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5942   RAUWUpdateListener Listener(*this, UI, UE);
5943   while (UI != UE) {
5944     SDNode *User = *UI;
5945
5946     // This node is about to morph, remove its old self from the CSE maps.
5947     RemoveNodeFromCSEMaps(User);
5948
5949     // A user can appear in a use list multiple times, and when this
5950     // happens the uses are usually next to each other in the list.
5951     // To help reduce the number of CSE recomputations, process all
5952     // the uses of this user that we can find this way.
5953     do {
5954       SDUse &Use = UI.getUse();
5955       ++UI;
5956       Use.setNode(To);
5957     } while (UI != UE && *UI == User);
5958
5959     // Now that we have modified User, add it back to the CSE maps.  If it
5960     // already exists there, recursively merge the results together.
5961     AddModifiedNodeToCSEMaps(User);
5962   }
5963
5964   // If we just RAUW'd the root, take note.
5965   if (From == getRoot().getNode())
5966     setRoot(SDValue(To, getRoot().getResNo()));
5967 }
5968
5969 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5970 /// This can cause recursive merging of nodes in the DAG.
5971 ///
5972 /// This version can replace From with any result values.  To must match the
5973 /// number and types of values returned by From.
5974 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
5975   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
5976     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
5977
5978   // Iterate over just the existing users of From. See the comments in
5979   // the ReplaceAllUsesWith above.
5980   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5981   RAUWUpdateListener Listener(*this, UI, UE);
5982   while (UI != UE) {
5983     SDNode *User = *UI;
5984
5985     // This node is about to morph, remove its old self from the CSE maps.
5986     RemoveNodeFromCSEMaps(User);
5987
5988     // A user can appear in a use list multiple times, and when this
5989     // happens the uses are usually next to each other in the list.
5990     // To help reduce the number of CSE recomputations, process all
5991     // the uses of this user that we can find this way.
5992     do {
5993       SDUse &Use = UI.getUse();
5994       const SDValue &ToOp = To[Use.getResNo()];
5995       ++UI;
5996       Use.set(ToOp);
5997     } while (UI != UE && *UI == User);
5998
5999     // Now that we have modified User, add it back to the CSE maps.  If it
6000     // already exists there, recursively merge the results together.
6001     AddModifiedNodeToCSEMaps(User);
6002   }
6003
6004   // If we just RAUW'd the root, take note.
6005   if (From == getRoot().getNode())
6006     setRoot(SDValue(To[getRoot().getResNo()]));
6007 }
6008
6009 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
6010 /// uses of other values produced by From.getNode() alone.  The Deleted
6011 /// vector is handled the same way as for ReplaceAllUsesWith.
6012 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
6013   // Handle the really simple, really trivial case efficiently.
6014   if (From == To) return;
6015
6016   // Handle the simple, trivial, case efficiently.
6017   if (From.getNode()->getNumValues() == 1) {
6018     ReplaceAllUsesWith(From, To);
6019     return;
6020   }
6021
6022   // Iterate over just the existing users of From. See the comments in
6023   // the ReplaceAllUsesWith above.
6024   SDNode::use_iterator UI = From.getNode()->use_begin(),
6025                        UE = From.getNode()->use_end();
6026   RAUWUpdateListener Listener(*this, UI, UE);
6027   while (UI != UE) {
6028     SDNode *User = *UI;
6029     bool UserRemovedFromCSEMaps = false;
6030
6031     // A user can appear in a use list multiple times, and when this
6032     // happens the uses are usually next to each other in the list.
6033     // To help reduce the number of CSE recomputations, process all
6034     // the uses of this user that we can find this way.
6035     do {
6036       SDUse &Use = UI.getUse();
6037
6038       // Skip uses of different values from the same node.
6039       if (Use.getResNo() != From.getResNo()) {
6040         ++UI;
6041         continue;
6042       }
6043
6044       // If this node hasn't been modified yet, it's still in the CSE maps,
6045       // so remove its old self from the CSE maps.
6046       if (!UserRemovedFromCSEMaps) {
6047         RemoveNodeFromCSEMaps(User);
6048         UserRemovedFromCSEMaps = true;
6049       }
6050
6051       ++UI;
6052       Use.set(To);
6053     } while (UI != UE && *UI == User);
6054
6055     // We are iterating over all uses of the From node, so if a use
6056     // doesn't use the specific value, no changes are made.
6057     if (!UserRemovedFromCSEMaps)
6058       continue;
6059
6060     // Now that we have modified User, add it back to the CSE maps.  If it
6061     // already exists there, recursively merge the results together.
6062     AddModifiedNodeToCSEMaps(User);
6063   }
6064
6065   // If we just RAUW'd the root, take note.
6066   if (From == getRoot())
6067     setRoot(To);
6068 }
6069
6070 namespace {
6071   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
6072   /// to record information about a use.
6073   struct UseMemo {
6074     SDNode *User;
6075     unsigned Index;
6076     SDUse *Use;
6077   };
6078
6079   /// operator< - Sort Memos by User.
6080   bool operator<(const UseMemo &L, const UseMemo &R) {
6081     return (intptr_t)L.User < (intptr_t)R.User;
6082   }
6083 }
6084
6085 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
6086 /// uses of other values produced by From.getNode() alone.  The same value
6087 /// may appear in both the From and To list.  The Deleted vector is
6088 /// handled the same way as for ReplaceAllUsesWith.
6089 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
6090                                               const SDValue *To,
6091                                               unsigned Num){
6092   // Handle the simple, trivial case efficiently.
6093   if (Num == 1)
6094     return ReplaceAllUsesOfValueWith(*From, *To);
6095
6096   // Read up all the uses and make records of them. This helps
6097   // processing new uses that are introduced during the
6098   // replacement process.
6099   SmallVector<UseMemo, 4> Uses;
6100   for (unsigned i = 0; i != Num; ++i) {
6101     unsigned FromResNo = From[i].getResNo();
6102     SDNode *FromNode = From[i].getNode();
6103     for (SDNode::use_iterator UI = FromNode->use_begin(),
6104          E = FromNode->use_end(); UI != E; ++UI) {
6105       SDUse &Use = UI.getUse();
6106       if (Use.getResNo() == FromResNo) {
6107         UseMemo Memo = { *UI, i, &Use };
6108         Uses.push_back(Memo);
6109       }
6110     }
6111   }
6112
6113   // Sort the uses, so that all the uses from a given User are together.
6114   std::sort(Uses.begin(), Uses.end());
6115
6116   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
6117        UseIndex != UseIndexEnd; ) {
6118     // We know that this user uses some value of From.  If it is the right
6119     // value, update it.
6120     SDNode *User = Uses[UseIndex].User;
6121
6122     // This node is about to morph, remove its old self from the CSE maps.
6123     RemoveNodeFromCSEMaps(User);
6124
6125     // The Uses array is sorted, so all the uses for a given User
6126     // are next to each other in the list.
6127     // To help reduce the number of CSE recomputations, process all
6128     // the uses of this user that we can find this way.
6129     do {
6130       unsigned i = Uses[UseIndex].Index;
6131       SDUse &Use = *Uses[UseIndex].Use;
6132       ++UseIndex;
6133
6134       Use.set(To[i]);
6135     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
6136
6137     // Now that we have modified User, add it back to the CSE maps.  If it
6138     // already exists there, recursively merge the results together.
6139     AddModifiedNodeToCSEMaps(User);
6140   }
6141 }
6142
6143 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
6144 /// based on their topological order. It returns the maximum id and a vector
6145 /// of the SDNodes* in assigned order by reference.
6146 unsigned SelectionDAG::AssignTopologicalOrder() {
6147
6148   unsigned DAGSize = 0;
6149
6150   // SortedPos tracks the progress of the algorithm. Nodes before it are
6151   // sorted, nodes after it are unsorted. When the algorithm completes
6152   // it is at the end of the list.
6153   allnodes_iterator SortedPos = allnodes_begin();
6154
6155   // Visit all the nodes. Move nodes with no operands to the front of
6156   // the list immediately. Annotate nodes that do have operands with their
6157   // operand count. Before we do this, the Node Id fields of the nodes
6158   // may contain arbitrary values. After, the Node Id fields for nodes
6159   // before SortedPos will contain the topological sort index, and the
6160   // Node Id fields for nodes At SortedPos and after will contain the
6161   // count of outstanding operands.
6162   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
6163     SDNode *N = I++;
6164     checkForCycles(N, this);
6165     unsigned Degree = N->getNumOperands();
6166     if (Degree == 0) {
6167       // A node with no uses, add it to the result array immediately.
6168       N->setNodeId(DAGSize++);
6169       allnodes_iterator Q = N;
6170       if (Q != SortedPos)
6171         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
6172       assert(SortedPos != AllNodes.end() && "Overran node list");
6173       ++SortedPos;
6174     } else {
6175       // Temporarily use the Node Id as scratch space for the degree count.
6176       N->setNodeId(Degree);
6177     }
6178   }
6179
6180   // Visit all the nodes. As we iterate, move nodes into sorted order,
6181   // such that by the time the end is reached all nodes will be sorted.
6182   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
6183     SDNode *N = I;
6184     checkForCycles(N, this);
6185     // N is in sorted position, so all its uses have one less operand
6186     // that needs to be sorted.
6187     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6188          UI != UE; ++UI) {
6189       SDNode *P = *UI;
6190       unsigned Degree = P->getNodeId();
6191       assert(Degree != 0 && "Invalid node degree");
6192       --Degree;
6193       if (Degree == 0) {
6194         // All of P's operands are sorted, so P may sorted now.
6195         P->setNodeId(DAGSize++);
6196         if (P != SortedPos)
6197           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
6198         assert(SortedPos != AllNodes.end() && "Overran node list");
6199         ++SortedPos;
6200       } else {
6201         // Update P's outstanding operand count.
6202         P->setNodeId(Degree);
6203       }
6204     }
6205     if (I == SortedPos) {
6206 #ifndef NDEBUG
6207       SDNode *S = ++I;
6208       dbgs() << "Overran sorted position:\n";
6209       S->dumprFull(this); dbgs() << "\n";
6210       dbgs() << "Checking if this is due to cycles\n";
6211       checkForCycles(this, true);
6212 #endif
6213       llvm_unreachable(nullptr);
6214     }
6215   }
6216
6217   assert(SortedPos == AllNodes.end() &&
6218          "Topological sort incomplete!");
6219   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
6220          "First node in topological sort is not the entry token!");
6221   assert(AllNodes.front().getNodeId() == 0 &&
6222          "First node in topological sort has non-zero id!");
6223   assert(AllNodes.front().getNumOperands() == 0 &&
6224          "First node in topological sort has operands!");
6225   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
6226          "Last node in topologic sort has unexpected id!");
6227   assert(AllNodes.back().use_empty() &&
6228          "Last node in topologic sort has users!");
6229   assert(DAGSize == allnodes_size() && "Node count mismatch!");
6230   return DAGSize;
6231 }
6232
6233 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
6234 /// value is produced by SD.
6235 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
6236   if (SD) {
6237     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
6238     SD->setHasDebugValue(true);
6239   }
6240   DbgInfo->add(DB, SD, isParameter);
6241 }
6242
6243 /// TransferDbgValues - Transfer SDDbgValues.
6244 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) {
6245   if (From == To || !From.getNode()->getHasDebugValue())
6246     return;
6247   SDNode *FromNode = From.getNode();
6248   SDNode *ToNode = To.getNode();
6249   ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode);
6250   SmallVector<SDDbgValue *, 2> ClonedDVs;
6251   for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end();
6252        I != E; ++I) {
6253     SDDbgValue *Dbg = *I;
6254     if (Dbg->getKind() == SDDbgValue::SDNODE) {
6255       SDDbgValue *Clone =
6256           getDbgValue(Dbg->getVariable(), Dbg->getExpression(), ToNode,
6257                       To.getResNo(), Dbg->isIndirect(), Dbg->getOffset(),
6258                       Dbg->getDebugLoc(), Dbg->getOrder());
6259       ClonedDVs.push_back(Clone);
6260     }
6261   }
6262   for (SmallVectorImpl<SDDbgValue *>::iterator I = ClonedDVs.begin(),
6263          E = ClonedDVs.end(); I != E; ++I)
6264     AddDbgValue(*I, ToNode, false);
6265 }
6266
6267 //===----------------------------------------------------------------------===//
6268 //                              SDNode Class
6269 //===----------------------------------------------------------------------===//
6270
6271 HandleSDNode::~HandleSDNode() {
6272   DropOperands();
6273 }
6274
6275 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
6276                                          DebugLoc DL, const GlobalValue *GA,
6277                                          EVT VT, int64_t o, unsigned char TF)
6278   : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
6279   TheGlobal = GA;
6280 }
6281
6282 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, DebugLoc dl, EVT VT,
6283                                          SDValue X, unsigned SrcAS,
6284                                          unsigned DestAS)
6285  : UnarySDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT), X),
6286    SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
6287
6288 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
6289                      EVT memvt, MachineMemOperand *mmo)
6290  : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
6291   SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
6292                                       MMO->isNonTemporal(), MMO->isInvariant());
6293   assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
6294   assert(isNonTemporal() == MMO->isNonTemporal() &&
6295          "Non-temporal encoding error!");
6296   // We check here that the size of the memory operand fits within the size of
6297   // the MMO. This is because the MMO might indicate only a possible address
6298   // range instead of specifying the affected memory addresses precisely.
6299   assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
6300 }
6301
6302 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
6303                      ArrayRef<SDValue> Ops, EVT memvt, MachineMemOperand *mmo)
6304    : SDNode(Opc, Order, dl, VTs, Ops),
6305      MemoryVT(memvt), MMO(mmo) {
6306   SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
6307                                       MMO->isNonTemporal(), MMO->isInvariant());
6308   assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
6309   assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
6310 }
6311
6312 /// Profile - Gather unique data for the node.
6313 ///
6314 void SDNode::Profile(FoldingSetNodeID &ID) const {
6315   AddNodeIDNode(ID, this);
6316 }
6317
6318 namespace {
6319   struct EVTArray {
6320     std::vector<EVT> VTs;
6321
6322     EVTArray() {
6323       VTs.reserve(MVT::LAST_VALUETYPE);
6324       for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
6325         VTs.push_back(MVT((MVT::SimpleValueType)i));
6326     }
6327   };
6328 }
6329
6330 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
6331 static ManagedStatic<EVTArray> SimpleVTArray;
6332 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
6333
6334 /// getValueTypeList - Return a pointer to the specified value type.
6335 ///
6336 const EVT *SDNode::getValueTypeList(EVT VT) {
6337   if (VT.isExtended()) {
6338     sys::SmartScopedLock<true> Lock(*VTMutex);
6339     return &(*EVTs->insert(VT).first);
6340   } else {
6341     assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
6342            "Value type out of range!");
6343     return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
6344   }
6345 }
6346
6347 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
6348 /// indicated value.  This method ignores uses of other values defined by this
6349 /// operation.
6350 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
6351   assert(Value < getNumValues() && "Bad value!");
6352
6353   // TODO: Only iterate over uses of a given value of the node
6354   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
6355     if (UI.getUse().getResNo() == Value) {
6356       if (NUses == 0)
6357         return false;
6358       --NUses;
6359     }
6360   }
6361
6362   // Found exactly the right number of uses?
6363   return NUses == 0;
6364 }
6365
6366
6367 /// hasAnyUseOfValue - Return true if there are any use of the indicated
6368 /// value. This method ignores uses of other values defined by this operation.
6369 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
6370   assert(Value < getNumValues() && "Bad value!");
6371
6372   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
6373     if (UI.getUse().getResNo() == Value)
6374       return true;
6375
6376   return false;
6377 }
6378
6379
6380 /// isOnlyUserOf - Return true if this node is the only use of N.
6381 ///
6382 bool SDNode::isOnlyUserOf(SDNode *N) const {
6383   bool Seen = false;
6384   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
6385     SDNode *User = *I;
6386     if (User == this)
6387       Seen = true;
6388     else
6389       return false;
6390   }
6391
6392   return Seen;
6393 }
6394
6395 /// isOperand - Return true if this node is an operand of N.
6396 ///
6397 bool SDValue::isOperandOf(SDNode *N) const {
6398   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
6399     if (*this == N->getOperand(i))
6400       return true;
6401   return false;
6402 }
6403
6404 bool SDNode::isOperandOf(SDNode *N) const {
6405   for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
6406     if (this == N->OperandList[i].getNode())
6407       return true;
6408   return false;
6409 }
6410
6411 /// reachesChainWithoutSideEffects - Return true if this operand (which must
6412 /// be a chain) reaches the specified operand without crossing any
6413 /// side-effecting instructions on any chain path.  In practice, this looks
6414 /// through token factors and non-volatile loads.  In order to remain efficient,
6415 /// this only looks a couple of nodes in, it does not do an exhaustive search.
6416 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
6417                                                unsigned Depth) const {
6418   if (*this == Dest) return true;
6419
6420   // Don't search too deeply, we just want to be able to see through
6421   // TokenFactor's etc.
6422   if (Depth == 0) return false;
6423
6424   // If this is a token factor, all inputs to the TF happen in parallel.  If any
6425   // of the operands of the TF does not reach dest, then we cannot do the xform.
6426   if (getOpcode() == ISD::TokenFactor) {
6427     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
6428       if (!getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
6429         return false;
6430     return true;
6431   }
6432
6433   // Loads don't have side effects, look through them.
6434   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
6435     if (!Ld->isVolatile())
6436       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
6437   }
6438   return false;
6439 }
6440
6441 /// hasPredecessor - Return true if N is a predecessor of this node.
6442 /// N is either an operand of this node, or can be reached by recursively
6443 /// traversing up the operands.
6444 /// NOTE: This is an expensive method. Use it carefully.
6445 bool SDNode::hasPredecessor(const SDNode *N) const {
6446   SmallPtrSet<const SDNode *, 32> Visited;
6447   SmallVector<const SDNode *, 16> Worklist;
6448   return hasPredecessorHelper(N, Visited, Worklist);
6449 }
6450
6451 bool
6452 SDNode::hasPredecessorHelper(const SDNode *N,
6453                              SmallPtrSetImpl<const SDNode *> &Visited,
6454                              SmallVectorImpl<const SDNode *> &Worklist) const {
6455   if (Visited.empty()) {
6456     Worklist.push_back(this);
6457   } else {
6458     // Take a look in the visited set. If we've already encountered this node
6459     // we needn't search further.
6460     if (Visited.count(N))
6461       return true;
6462   }
6463
6464   // Haven't visited N yet. Continue the search.
6465   while (!Worklist.empty()) {
6466     const SDNode *M = Worklist.pop_back_val();
6467     for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
6468       SDNode *Op = M->getOperand(i).getNode();
6469       if (Visited.insert(Op).second)
6470         Worklist.push_back(Op);
6471       if (Op == N)
6472         return true;
6473     }
6474   }
6475
6476   return false;
6477 }
6478
6479 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
6480   assert(Num < NumOperands && "Invalid child # of SDNode!");
6481   return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
6482 }
6483
6484 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
6485   assert(N->getNumValues() == 1 &&
6486          "Can't unroll a vector with multiple results!");
6487
6488   EVT VT = N->getValueType(0);
6489   unsigned NE = VT.getVectorNumElements();
6490   EVT EltVT = VT.getVectorElementType();
6491   SDLoc dl(N);
6492
6493   SmallVector<SDValue, 8> Scalars;
6494   SmallVector<SDValue, 4> Operands(N->getNumOperands());
6495
6496   // If ResNE is 0, fully unroll the vector op.
6497   if (ResNE == 0)
6498     ResNE = NE;
6499   else if (NE > ResNE)
6500     NE = ResNE;
6501
6502   unsigned i;
6503   for (i= 0; i != NE; ++i) {
6504     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
6505       SDValue Operand = N->getOperand(j);
6506       EVT OperandVT = Operand.getValueType();
6507       if (OperandVT.isVector()) {
6508         // A vector operand; extract a single element.
6509         EVT OperandEltVT = OperandVT.getVectorElementType();
6510         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl,
6511                               OperandEltVT,
6512                               Operand,
6513                               getConstant(i, TLI->getVectorIdxTy()));
6514       } else {
6515         // A scalar operand; just use it as is.
6516         Operands[j] = Operand;
6517       }
6518     }
6519
6520     switch (N->getOpcode()) {
6521     default:
6522       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands));
6523       break;
6524     case ISD::VSELECT:
6525       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
6526       break;
6527     case ISD::SHL:
6528     case ISD::SRA:
6529     case ISD::SRL:
6530     case ISD::ROTL:
6531     case ISD::ROTR:
6532       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
6533                                getShiftAmountOperand(Operands[0].getValueType(),
6534                                                      Operands[1])));
6535       break;
6536     case ISD::SIGN_EXTEND_INREG:
6537     case ISD::FP_ROUND_INREG: {
6538       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
6539       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6540                                 Operands[0],
6541                                 getValueType(ExtVT)));
6542     }
6543     }
6544   }
6545
6546   for (; i < ResNE; ++i)
6547     Scalars.push_back(getUNDEF(EltVT));
6548
6549   return getNode(ISD::BUILD_VECTOR, dl,
6550                  EVT::getVectorVT(*getContext(), EltVT, ResNE), Scalars);
6551 }
6552
6553
6554 /// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a
6555 /// location that is 'Dist' units away from the location that the 'Base' load
6556 /// is loading from.
6557 bool SelectionDAG::isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base,
6558                                      unsigned Bytes, int Dist) const {
6559   if (LD->getChain() != Base->getChain())
6560     return false;
6561   EVT VT = LD->getValueType(0);
6562   if (VT.getSizeInBits() / 8 != Bytes)
6563     return false;
6564
6565   SDValue Loc = LD->getOperand(1);
6566   SDValue BaseLoc = Base->getOperand(1);
6567   if (Loc.getOpcode() == ISD::FrameIndex) {
6568     if (BaseLoc.getOpcode() != ISD::FrameIndex)
6569       return false;
6570     const MachineFrameInfo *MFI = getMachineFunction().getFrameInfo();
6571     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
6572     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
6573     int FS  = MFI->getObjectSize(FI);
6574     int BFS = MFI->getObjectSize(BFI);
6575     if (FS != BFS || FS != (int)Bytes) return false;
6576     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
6577   }
6578
6579   // Handle X + C.
6580   if (isBaseWithConstantOffset(Loc)) {
6581     int64_t LocOffset = cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
6582     if (Loc.getOperand(0) == BaseLoc) {
6583       // If the base location is a simple address with no offset itself, then
6584       // the second load's first add operand should be the base address.
6585       if (LocOffset == Dist * (int)Bytes)
6586         return true;
6587     } else if (isBaseWithConstantOffset(BaseLoc)) {
6588       // The base location itself has an offset, so subtract that value from the
6589       // second load's offset before comparing to distance * size.
6590       int64_t BOffset =
6591         cast<ConstantSDNode>(BaseLoc.getOperand(1))->getSExtValue();
6592       if (Loc.getOperand(0) == BaseLoc.getOperand(0)) {
6593         if ((LocOffset - BOffset) == Dist * (int)Bytes)
6594           return true;
6595       }
6596     }
6597   }
6598   const GlobalValue *GV1 = nullptr;
6599   const GlobalValue *GV2 = nullptr;
6600   int64_t Offset1 = 0;
6601   int64_t Offset2 = 0;
6602   bool isGA1 = TLI->isGAPlusOffset(Loc.getNode(), GV1, Offset1);
6603   bool isGA2 = TLI->isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
6604   if (isGA1 && isGA2 && GV1 == GV2)
6605     return Offset1 == (Offset2 + Dist*Bytes);
6606   return false;
6607 }
6608
6609
6610 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
6611 /// it cannot be inferred.
6612 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
6613   // If this is a GlobalAddress + cst, return the alignment.
6614   const GlobalValue *GV;
6615   int64_t GVOffset = 0;
6616   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
6617     unsigned PtrWidth = TLI->getPointerTypeSizeInBits(GV->getType());
6618     APInt KnownZero(PtrWidth, 0), KnownOne(PtrWidth, 0);
6619     llvm::computeKnownBits(const_cast<GlobalValue*>(GV), KnownZero, KnownOne,
6620                            TLI->getDataLayout());
6621     unsigned AlignBits = KnownZero.countTrailingOnes();
6622     unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
6623     if (Align)
6624       return MinAlign(Align, GVOffset);
6625   }
6626
6627   // If this is a direct reference to a stack slot, use information about the
6628   // stack slot's alignment.
6629   int FrameIdx = 1 << 31;
6630   int64_t FrameOffset = 0;
6631   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
6632     FrameIdx = FI->getIndex();
6633   } else if (isBaseWithConstantOffset(Ptr) &&
6634              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
6635     // Handle FI+Cst
6636     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6637     FrameOffset = Ptr.getConstantOperandVal(1);
6638   }
6639
6640   if (FrameIdx != (1 << 31)) {
6641     const MachineFrameInfo &MFI = *getMachineFunction().getFrameInfo();
6642     unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
6643                                     FrameOffset);
6644     return FIInfoAlign;
6645   }
6646
6647   return 0;
6648 }
6649
6650 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
6651 /// which is split (or expanded) into two not necessarily identical pieces.
6652 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
6653   // Currently all types are split in half.
6654   EVT LoVT, HiVT;
6655   if (!VT.isVector()) {
6656     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
6657   } else {
6658     unsigned NumElements = VT.getVectorNumElements();
6659     assert(!(NumElements & 1) && "Splitting vector, but not in half!");
6660     LoVT = HiVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
6661                                    NumElements/2);
6662   }
6663   return std::make_pair(LoVT, HiVT);
6664 }
6665
6666 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
6667 /// low/high part.
6668 std::pair<SDValue, SDValue>
6669 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
6670                           const EVT &HiVT) {
6671   assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
6672          N.getValueType().getVectorNumElements() &&
6673          "More vector elements requested than available!");
6674   SDValue Lo, Hi;
6675   Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
6676                getConstant(0, TLI->getVectorIdxTy()));
6677   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
6678                getConstant(LoVT.getVectorNumElements(), TLI->getVectorIdxTy()));
6679   return std::make_pair(Lo, Hi);
6680 }
6681
6682 void SelectionDAG::ExtractVectorElements(SDValue Op,
6683                                          SmallVectorImpl<SDValue> &Args,
6684                                          unsigned Start, unsigned Count) {
6685   EVT VT = Op.getValueType();
6686   if (Count == 0)
6687     Count = VT.getVectorNumElements();
6688
6689   EVT EltVT = VT.getVectorElementType();
6690   EVT IdxTy = TLI->getVectorIdxTy();
6691   SDLoc SL(Op);
6692   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
6693     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
6694                            Op, getConstant(i, IdxTy)));
6695   }
6696 }
6697
6698 // getAddressSpace - Return the address space this GlobalAddress belongs to.
6699 unsigned GlobalAddressSDNode::getAddressSpace() const {
6700   return getGlobal()->getType()->getAddressSpace();
6701 }
6702
6703
6704 Type *ConstantPoolSDNode::getType() const {
6705   if (isMachineConstantPoolEntry())
6706     return Val.MachineCPVal->getType();
6707   return Val.ConstVal->getType();
6708 }
6709
6710 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
6711                                         APInt &SplatUndef,
6712                                         unsigned &SplatBitSize,
6713                                         bool &HasAnyUndefs,
6714                                         unsigned MinSplatBits,
6715                                         bool isBigEndian) const {
6716   EVT VT = getValueType(0);
6717   assert(VT.isVector() && "Expected a vector type");
6718   unsigned sz = VT.getSizeInBits();
6719   if (MinSplatBits > sz)
6720     return false;
6721
6722   SplatValue = APInt(sz, 0);
6723   SplatUndef = APInt(sz, 0);
6724
6725   // Get the bits.  Bits with undefined values (when the corresponding element
6726   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
6727   // in SplatValue.  If any of the values are not constant, give up and return
6728   // false.
6729   unsigned int nOps = getNumOperands();
6730   assert(nOps > 0 && "isConstantSplat has 0-size build vector");
6731   unsigned EltBitSize = VT.getVectorElementType().getSizeInBits();
6732
6733   for (unsigned j = 0; j < nOps; ++j) {
6734     unsigned i = isBigEndian ? nOps-1-j : j;
6735     SDValue OpVal = getOperand(i);
6736     unsigned BitPos = j * EltBitSize;
6737
6738     if (OpVal.getOpcode() == ISD::UNDEF)
6739       SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos + EltBitSize);
6740     else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
6741       SplatValue |= CN->getAPIntValue().zextOrTrunc(EltBitSize).
6742                     zextOrTrunc(sz) << BitPos;
6743     else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
6744       SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
6745      else
6746       return false;
6747   }
6748
6749   // The build_vector is all constants or undefs.  Find the smallest element
6750   // size that splats the vector.
6751
6752   HasAnyUndefs = (SplatUndef != 0);
6753   while (sz > 8) {
6754
6755     unsigned HalfSize = sz / 2;
6756     APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
6757     APInt LowValue = SplatValue.trunc(HalfSize);
6758     APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
6759     APInt LowUndef = SplatUndef.trunc(HalfSize);
6760
6761     // If the two halves do not match (ignoring undef bits), stop here.
6762     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
6763         MinSplatBits > HalfSize)
6764       break;
6765
6766     SplatValue = HighValue | LowValue;
6767     SplatUndef = HighUndef & LowUndef;
6768
6769     sz = HalfSize;
6770   }
6771
6772   SplatBitSize = sz;
6773   return true;
6774 }
6775
6776 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
6777   if (UndefElements) {
6778     UndefElements->clear();
6779     UndefElements->resize(getNumOperands());
6780   }
6781   SDValue Splatted;
6782   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
6783     SDValue Op = getOperand(i);
6784     if (Op.getOpcode() == ISD::UNDEF) {
6785       if (UndefElements)
6786         (*UndefElements)[i] = true;
6787     } else if (!Splatted) {
6788       Splatted = Op;
6789     } else if (Splatted != Op) {
6790       return SDValue();
6791     }
6792   }
6793
6794   if (!Splatted) {
6795     assert(getOperand(0).getOpcode() == ISD::UNDEF &&
6796            "Can only have a splat without a constant for all undefs.");
6797     return getOperand(0);
6798   }
6799
6800   return Splatted;
6801 }
6802
6803 ConstantSDNode *
6804 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
6805   return dyn_cast_or_null<ConstantSDNode>(
6806       getSplatValue(UndefElements).getNode());
6807 }
6808
6809 ConstantFPSDNode *
6810 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
6811   return dyn_cast_or_null<ConstantFPSDNode>(
6812       getSplatValue(UndefElements).getNode());
6813 }
6814
6815 bool BuildVectorSDNode::isConstant() const {
6816   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
6817     unsigned Opc = getOperand(i).getOpcode();
6818     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
6819       return false;
6820   }
6821   return true;
6822 }
6823
6824 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
6825   // Find the first non-undef value in the shuffle mask.
6826   unsigned i, e;
6827   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
6828     /* search */;
6829
6830   assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
6831
6832   // Make sure all remaining elements are either undef or the same as the first
6833   // non-undef value.
6834   for (int Idx = Mask[i]; i != e; ++i)
6835     if (Mask[i] >= 0 && Mask[i] != Idx)
6836       return false;
6837   return true;
6838 }
6839
6840 #ifndef NDEBUG
6841 static void checkForCyclesHelper(const SDNode *N,
6842                                  SmallPtrSetImpl<const SDNode*> &Visited,
6843                                  SmallPtrSetImpl<const SDNode*> &Checked,
6844                                  const llvm::SelectionDAG *DAG) {
6845   // If this node has already been checked, don't check it again.
6846   if (Checked.count(N))
6847     return;
6848
6849   // If a node has already been visited on this depth-first walk, reject it as
6850   // a cycle.
6851   if (!Visited.insert(N).second) {
6852     errs() << "Detected cycle in SelectionDAG\n";
6853     dbgs() << "Offending node:\n";
6854     N->dumprFull(DAG); dbgs() << "\n";
6855     abort();
6856   }
6857
6858   for(unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
6859     checkForCyclesHelper(N->getOperand(i).getNode(), Visited, Checked, DAG);
6860
6861   Checked.insert(N);
6862   Visited.erase(N);
6863 }
6864 #endif
6865
6866 void llvm::checkForCycles(const llvm::SDNode *N,
6867                           const llvm::SelectionDAG *DAG,
6868                           bool force) {
6869 #ifndef NDEBUG
6870   bool check = force;
6871 #ifdef XDEBUG
6872   check = true;
6873 #endif  // XDEBUG
6874   if (check) {
6875     assert(N && "Checking nonexistent SDNode");
6876     SmallPtrSet<const SDNode*, 32> visited;
6877     SmallPtrSet<const SDNode*, 32> checked;
6878     checkForCyclesHelper(N, visited, checked, DAG);
6879   }
6880 #endif  // !NDEBUG
6881 }
6882
6883 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
6884   checkForCycles(DAG->getRoot().getNode(), DAG, force);
6885 }