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