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