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