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