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