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