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