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