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