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