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