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