]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r306325, 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   const DataLayout &DL = DAG.getDataLayout();
4901   LLVMContext &C = *DAG.getContext();
4902   std::vector<EVT> MemOps;
4903   bool DstAlignCanChange = false;
4904   MachineFunction &MF = DAG.getMachineFunction();
4905   MachineFrameInfo &MFI = MF.getFrameInfo();
4906   bool OptSize = shouldLowerMemFuncForSize(MF);
4907   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4908   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
4909     DstAlignCanChange = true;
4910   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
4911   if (Align > SrcAlign)
4912     SrcAlign = Align;
4913   ConstantDataArraySlice Slice;
4914   bool CopyFromConstant = isMemSrcFromConstant(Src, Slice);
4915   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
4916   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
4917
4918   if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
4919                                 (DstAlignCanChange ? 0 : Align),
4920                                 (isZeroConstant ? 0 : SrcAlign),
4921                                 false, false, CopyFromConstant, true,
4922                                 DstPtrInfo.getAddrSpace(),
4923                                 SrcPtrInfo.getAddrSpace(),
4924                                 DAG, TLI))
4925     return SDValue();
4926
4927   if (DstAlignCanChange) {
4928     Type *Ty = MemOps[0].getTypeForEVT(C);
4929     unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
4930
4931     // Don't promote to an alignment that would require dynamic stack
4932     // realignment.
4933     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
4934     if (!TRI->needsStackRealignment(MF))
4935       while (NewAlign > Align &&
4936              DL.exceedsNaturalStackAlignment(NewAlign))
4937           NewAlign /= 2;
4938
4939     if (NewAlign > Align) {
4940       // Give the stack frame object a larger alignment if needed.
4941       if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
4942         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
4943       Align = NewAlign;
4944     }
4945   }
4946
4947   MachineMemOperand::Flags MMOFlags =
4948       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
4949   SmallVector<SDValue, 8> OutChains;
4950   unsigned NumMemOps = MemOps.size();
4951   uint64_t SrcOff = 0, DstOff = 0;
4952   for (unsigned i = 0; i != NumMemOps; ++i) {
4953     EVT VT = MemOps[i];
4954     unsigned VTSize = VT.getSizeInBits() / 8;
4955     SDValue Value, Store;
4956
4957     if (VTSize > Size) {
4958       // Issuing an unaligned load / store pair  that overlaps with the previous
4959       // pair. Adjust the offset accordingly.
4960       assert(i == NumMemOps-1 && i != 0);
4961       SrcOff -= VTSize - Size;
4962       DstOff -= VTSize - Size;
4963     }
4964
4965     if (CopyFromConstant &&
4966         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
4967       // It's unlikely a store of a vector immediate can be done in a single
4968       // instruction. It would require a load from a constantpool first.
4969       // We only handle zero vectors here.
4970       // FIXME: Handle other cases where store of vector immediate is done in
4971       // a single instruction.
4972       ConstantDataArraySlice SubSlice;
4973       if (SrcOff < Slice.Length) {
4974         SubSlice = Slice;
4975         SubSlice.move(SrcOff);
4976       } else {
4977         // This is an out-of-bounds access and hence UB. Pretend we read zero.
4978         SubSlice.Array = nullptr;
4979         SubSlice.Offset = 0;
4980         SubSlice.Length = VTSize;
4981       }
4982       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
4983       if (Value.getNode())
4984         Store = DAG.getStore(Chain, dl, Value,
4985                              DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4986                              DstPtrInfo.getWithOffset(DstOff), Align,
4987                              MMOFlags);
4988     }
4989
4990     if (!Store.getNode()) {
4991       // The type might not be legal for the target.  This should only happen
4992       // if the type is smaller than a legal type, as on PPC, so the right
4993       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
4994       // to Load/Store if NVT==VT.
4995       // FIXME does the case above also need this?
4996       EVT NVT = TLI.getTypeToTransformTo(C, VT);
4997       assert(NVT.bitsGE(VT));
4998
4999       bool isDereferenceable =
5000         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
5001       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
5002       if (isDereferenceable)
5003         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
5004
5005       Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
5006                              DAG.getMemBasePlusOffset(Src, SrcOff, dl),
5007                              SrcPtrInfo.getWithOffset(SrcOff), VT,
5008                              MinAlign(SrcAlign, SrcOff), SrcMMOFlags);
5009       OutChains.push_back(Value.getValue(1));
5010       Store = DAG.getTruncStore(
5011           Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5012           DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags);
5013     }
5014     OutChains.push_back(Store);
5015     SrcOff += VTSize;
5016     DstOff += VTSize;
5017     Size -= VTSize;
5018   }
5019
5020   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5021 }
5022
5023 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
5024                                         SDValue Chain, SDValue Dst, SDValue Src,
5025                                         uint64_t Size, unsigned Align,
5026                                         bool isVol, bool AlwaysInline,
5027                                         MachinePointerInfo DstPtrInfo,
5028                                         MachinePointerInfo SrcPtrInfo) {
5029   // Turn a memmove of undef to nop.
5030   if (Src.isUndef())
5031     return Chain;
5032
5033   // Expand memmove to a series of load and store ops if the size operand falls
5034   // below a certain threshold.
5035   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5036   const DataLayout &DL = DAG.getDataLayout();
5037   LLVMContext &C = *DAG.getContext();
5038   std::vector<EVT> MemOps;
5039   bool DstAlignCanChange = false;
5040   MachineFunction &MF = DAG.getMachineFunction();
5041   MachineFrameInfo &MFI = MF.getFrameInfo();
5042   bool OptSize = shouldLowerMemFuncForSize(MF);
5043   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5044   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5045     DstAlignCanChange = true;
5046   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
5047   if (Align > SrcAlign)
5048     SrcAlign = Align;
5049   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
5050
5051   if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
5052                                 (DstAlignCanChange ? 0 : Align), SrcAlign,
5053                                 false, false, false, false,
5054                                 DstPtrInfo.getAddrSpace(),
5055                                 SrcPtrInfo.getAddrSpace(),
5056                                 DAG, TLI))
5057     return SDValue();
5058
5059   if (DstAlignCanChange) {
5060     Type *Ty = MemOps[0].getTypeForEVT(C);
5061     unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
5062     if (NewAlign > Align) {
5063       // Give the stack frame object a larger alignment if needed.
5064       if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5065         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5066       Align = NewAlign;
5067     }
5068   }
5069
5070   MachineMemOperand::Flags MMOFlags =
5071       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
5072   uint64_t SrcOff = 0, DstOff = 0;
5073   SmallVector<SDValue, 8> LoadValues;
5074   SmallVector<SDValue, 8> LoadChains;
5075   SmallVector<SDValue, 8> OutChains;
5076   unsigned NumMemOps = MemOps.size();
5077   for (unsigned i = 0; i < NumMemOps; i++) {
5078     EVT VT = MemOps[i];
5079     unsigned VTSize = VT.getSizeInBits() / 8;
5080     SDValue Value;
5081
5082     bool isDereferenceable =
5083       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
5084     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
5085     if (isDereferenceable)
5086       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
5087
5088     Value =
5089         DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl),
5090                     SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, SrcMMOFlags);
5091     LoadValues.push_back(Value);
5092     LoadChains.push_back(Value.getValue(1));
5093     SrcOff += VTSize;
5094   }
5095   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
5096   OutChains.clear();
5097   for (unsigned i = 0; i < NumMemOps; i++) {
5098     EVT VT = MemOps[i];
5099     unsigned VTSize = VT.getSizeInBits() / 8;
5100     SDValue Store;
5101
5102     Store = DAG.getStore(Chain, dl, LoadValues[i],
5103                          DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5104                          DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
5105     OutChains.push_back(Store);
5106     DstOff += VTSize;
5107   }
5108
5109   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5110 }
5111
5112 /// \brief Lower the call to 'memset' intrinsic function into a series of store
5113 /// operations.
5114 ///
5115 /// \param DAG Selection DAG where lowered code is placed.
5116 /// \param dl Link to corresponding IR location.
5117 /// \param Chain Control flow dependency.
5118 /// \param Dst Pointer to destination memory location.
5119 /// \param Src Value of byte to write into the memory.
5120 /// \param Size Number of bytes to write.
5121 /// \param Align Alignment of the destination in bytes.
5122 /// \param isVol True if destination is volatile.
5123 /// \param DstPtrInfo IR information on the memory pointer.
5124 /// \returns New head in the control flow, if lowering was successful, empty
5125 /// SDValue otherwise.
5126 ///
5127 /// The function tries to replace 'llvm.memset' intrinsic with several store
5128 /// operations and value calculation code. This is usually profitable for small
5129 /// memory size.
5130 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
5131                                SDValue Chain, SDValue Dst, SDValue Src,
5132                                uint64_t Size, unsigned Align, bool isVol,
5133                                MachinePointerInfo DstPtrInfo) {
5134   // Turn a memset of undef to nop.
5135   if (Src.isUndef())
5136     return Chain;
5137
5138   // Expand memset to a series of load/store ops if the size operand
5139   // falls below a certain threshold.
5140   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5141   std::vector<EVT> MemOps;
5142   bool DstAlignCanChange = false;
5143   MachineFunction &MF = DAG.getMachineFunction();
5144   MachineFrameInfo &MFI = MF.getFrameInfo();
5145   bool OptSize = shouldLowerMemFuncForSize(MF);
5146   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5147   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5148     DstAlignCanChange = true;
5149   bool IsZeroVal =
5150     isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
5151   if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
5152                                 Size, (DstAlignCanChange ? 0 : Align), 0,
5153                                 true, IsZeroVal, false, true,
5154                                 DstPtrInfo.getAddrSpace(), ~0u,
5155                                 DAG, TLI))
5156     return SDValue();
5157
5158   if (DstAlignCanChange) {
5159     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
5160     unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
5161     if (NewAlign > Align) {
5162       // Give the stack frame object a larger alignment if needed.
5163       if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5164         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5165       Align = NewAlign;
5166     }
5167   }
5168
5169   SmallVector<SDValue, 8> OutChains;
5170   uint64_t DstOff = 0;
5171   unsigned NumMemOps = MemOps.size();
5172
5173   // Find the largest store and generate the bit pattern for it.
5174   EVT LargestVT = MemOps[0];
5175   for (unsigned i = 1; i < NumMemOps; i++)
5176     if (MemOps[i].bitsGT(LargestVT))
5177       LargestVT = MemOps[i];
5178   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
5179
5180   for (unsigned i = 0; i < NumMemOps; i++) {
5181     EVT VT = MemOps[i];
5182     unsigned VTSize = VT.getSizeInBits() / 8;
5183     if (VTSize > Size) {
5184       // Issuing an unaligned load / store pair  that overlaps with the previous
5185       // pair. Adjust the offset accordingly.
5186       assert(i == NumMemOps-1 && i != 0);
5187       DstOff -= VTSize - Size;
5188     }
5189
5190     // If this store is smaller than the largest store see whether we can get
5191     // the smaller value for free with a truncate.
5192     SDValue Value = MemSetValue;
5193     if (VT.bitsLT(LargestVT)) {
5194       if (!LargestVT.isVector() && !VT.isVector() &&
5195           TLI.isTruncateFree(LargestVT, VT))
5196         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
5197       else
5198         Value = getMemsetValue(Src, VT, DAG, dl);
5199     }
5200     assert(Value.getValueType() == VT && "Value with wrong type.");
5201     SDValue Store = DAG.getStore(
5202         Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5203         DstPtrInfo.getWithOffset(DstOff), Align,
5204         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
5205     OutChains.push_back(Store);
5206     DstOff += VT.getSizeInBits() / 8;
5207     Size -= VTSize;
5208   }
5209
5210   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5211 }
5212
5213 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
5214                                             unsigned AS) {
5215   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
5216   // pointer operands can be losslessly bitcasted to pointers of address space 0
5217   if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) {
5218     report_fatal_error("cannot lower memory intrinsic in address space " +
5219                        Twine(AS));
5220   }
5221 }
5222
5223 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
5224                                 SDValue Src, SDValue Size, unsigned Align,
5225                                 bool isVol, bool AlwaysInline, bool isTailCall,
5226                                 MachinePointerInfo DstPtrInfo,
5227                                 MachinePointerInfo SrcPtrInfo) {
5228   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5229
5230   // Check to see if we should lower the memcpy to loads and stores first.
5231   // For cases within the target-specified limits, this is the best choice.
5232   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5233   if (ConstantSize) {
5234     // Memcpy with size zero? Just return the original chain.
5235     if (ConstantSize->isNullValue())
5236       return Chain;
5237
5238     SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
5239                                              ConstantSize->getZExtValue(),Align,
5240                                 isVol, false, DstPtrInfo, SrcPtrInfo);
5241     if (Result.getNode())
5242       return Result;
5243   }
5244
5245   // Then check to see if we should lower the memcpy with target-specific
5246   // code. If the target chooses to do this, this is the next best.
5247   if (TSI) {
5248     SDValue Result = TSI->EmitTargetCodeForMemcpy(
5249         *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline,
5250         DstPtrInfo, SrcPtrInfo);
5251     if (Result.getNode())
5252       return Result;
5253   }
5254
5255   // If we really need inline code and the target declined to provide it,
5256   // use a (potentially long) sequence of loads and stores.
5257   if (AlwaysInline) {
5258     assert(ConstantSize && "AlwaysInline requires a constant size!");
5259     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
5260                                    ConstantSize->getZExtValue(), Align, isVol,
5261                                    true, DstPtrInfo, SrcPtrInfo);
5262   }
5263
5264   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5265   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
5266
5267   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
5268   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
5269   // respect volatile, so they may do things like read or write memory
5270   // beyond the given memory regions. But fixing this isn't easy, and most
5271   // people don't care.
5272
5273   // Emit a library call.
5274   TargetLowering::ArgListTy Args;
5275   TargetLowering::ArgListEntry Entry;
5276   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5277   Entry.Node = Dst; Args.push_back(Entry);
5278   Entry.Node = Src; Args.push_back(Entry);
5279   Entry.Node = Size; Args.push_back(Entry);
5280   // FIXME: pass in SDLoc
5281   TargetLowering::CallLoweringInfo CLI(*this);
5282   CLI.setDebugLoc(dl)
5283       .setChain(Chain)
5284       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
5285                     Dst.getValueType().getTypeForEVT(*getContext()),
5286                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
5287                                       TLI->getPointerTy(getDataLayout())),
5288                     std::move(Args))
5289       .setDiscardResult()
5290       .setTailCall(isTailCall);
5291
5292   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5293   return CallResult.second;
5294 }
5295
5296 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
5297                                  SDValue Src, SDValue Size, unsigned Align,
5298                                  bool isVol, bool isTailCall,
5299                                  MachinePointerInfo DstPtrInfo,
5300                                  MachinePointerInfo SrcPtrInfo) {
5301   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5302
5303   // Check to see if we should lower the memmove to loads and stores first.
5304   // For cases within the target-specified limits, this is the best choice.
5305   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5306   if (ConstantSize) {
5307     // Memmove with size zero? Just return the original chain.
5308     if (ConstantSize->isNullValue())
5309       return Chain;
5310
5311     SDValue Result =
5312       getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
5313                                ConstantSize->getZExtValue(), Align, isVol,
5314                                false, DstPtrInfo, SrcPtrInfo);
5315     if (Result.getNode())
5316       return Result;
5317   }
5318
5319   // Then check to see if we should lower the memmove with target-specific
5320   // code. If the target chooses to do this, this is the next best.
5321   if (TSI) {
5322     SDValue Result = TSI->EmitTargetCodeForMemmove(
5323         *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
5324     if (Result.getNode())
5325       return Result;
5326   }
5327
5328   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5329   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
5330
5331   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
5332   // not be safe.  See memcpy above for more details.
5333
5334   // Emit a library call.
5335   TargetLowering::ArgListTy Args;
5336   TargetLowering::ArgListEntry Entry;
5337   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5338   Entry.Node = Dst; Args.push_back(Entry);
5339   Entry.Node = Src; Args.push_back(Entry);
5340   Entry.Node = Size; Args.push_back(Entry);
5341   // FIXME:  pass in SDLoc
5342   TargetLowering::CallLoweringInfo CLI(*this);
5343   CLI.setDebugLoc(dl)
5344       .setChain(Chain)
5345       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
5346                     Dst.getValueType().getTypeForEVT(*getContext()),
5347                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
5348                                       TLI->getPointerTy(getDataLayout())),
5349                     std::move(Args))
5350       .setDiscardResult()
5351       .setTailCall(isTailCall);
5352
5353   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5354   return CallResult.second;
5355 }
5356
5357 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
5358                                 SDValue Src, SDValue Size, unsigned Align,
5359                                 bool isVol, bool isTailCall,
5360                                 MachinePointerInfo DstPtrInfo) {
5361   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5362
5363   // Check to see if we should lower the memset to stores first.
5364   // For cases within the target-specified limits, this is the best choice.
5365   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5366   if (ConstantSize) {
5367     // Memset with size zero? Just return the original chain.
5368     if (ConstantSize->isNullValue())
5369       return Chain;
5370
5371     SDValue Result =
5372       getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
5373                       Align, isVol, DstPtrInfo);
5374
5375     if (Result.getNode())
5376       return Result;
5377   }
5378
5379   // Then check to see if we should lower the memset with target-specific
5380   // code. If the target chooses to do this, this is the next best.
5381   if (TSI) {
5382     SDValue Result = TSI->EmitTargetCodeForMemset(
5383         *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo);
5384     if (Result.getNode())
5385       return Result;
5386   }
5387
5388   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5389
5390   // Emit a library call.
5391   Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext());
5392   TargetLowering::ArgListTy Args;
5393   TargetLowering::ArgListEntry Entry;
5394   Entry.Node = Dst; Entry.Ty = IntPtrTy;
5395   Args.push_back(Entry);
5396   Entry.Node = Src;
5397   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
5398   Args.push_back(Entry);
5399   Entry.Node = Size;
5400   Entry.Ty = IntPtrTy;
5401   Args.push_back(Entry);
5402
5403   // FIXME: pass in SDLoc
5404   TargetLowering::CallLoweringInfo CLI(*this);
5405   CLI.setDebugLoc(dl)
5406       .setChain(Chain)
5407       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
5408                     Dst.getValueType().getTypeForEVT(*getContext()),
5409                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
5410                                       TLI->getPointerTy(getDataLayout())),
5411                     std::move(Args))
5412       .setDiscardResult()
5413       .setTailCall(isTailCall);
5414
5415   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5416   return CallResult.second;
5417 }
5418
5419 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5420                                 SDVTList VTList, ArrayRef<SDValue> Ops,
5421                                 MachineMemOperand *MMO) {
5422   FoldingSetNodeID ID;
5423   ID.AddInteger(MemVT.getRawBits());
5424   AddNodeIDNode(ID, Opcode, VTList, Ops);
5425   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5426   void* IP = nullptr;
5427   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5428     cast<AtomicSDNode>(E)->refineAlignment(MMO);
5429     return SDValue(E, 0);
5430   }
5431
5432   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5433                                     VTList, MemVT, MMO);
5434   createOperands(N, Ops);
5435
5436   CSEMap.InsertNode(N, IP);
5437   InsertNode(N);
5438   return SDValue(N, 0);
5439 }
5440
5441 SDValue SelectionDAG::getAtomicCmpSwap(
5442     unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain,
5443     SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo,
5444     unsigned Alignment, AtomicOrdering SuccessOrdering,
5445     AtomicOrdering FailureOrdering, SynchronizationScope SynchScope) {
5446   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
5447          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
5448   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
5449
5450   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
5451     Alignment = getEVTAlignment(MemVT);
5452
5453   MachineFunction &MF = getMachineFunction();
5454
5455   // FIXME: Volatile isn't really correct; we should keep track of atomic
5456   // orderings in the memoperand.
5457   auto Flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad |
5458                MachineMemOperand::MOStore;
5459   MachineMemOperand *MMO =
5460     MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment,
5461                             AAMDNodes(), nullptr, SynchScope, SuccessOrdering,
5462                             FailureOrdering);
5463
5464   return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO);
5465 }
5466
5467 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
5468                                        EVT MemVT, SDVTList VTs, SDValue Chain,
5469                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
5470                                        MachineMemOperand *MMO) {
5471   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
5472          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
5473   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
5474
5475   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
5476   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5477 }
5478
5479 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5480                                 SDValue Chain, SDValue Ptr, SDValue Val,
5481                                 const Value *PtrVal, unsigned Alignment,
5482                                 AtomicOrdering Ordering,
5483                                 SynchronizationScope SynchScope) {
5484   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
5485     Alignment = getEVTAlignment(MemVT);
5486
5487   MachineFunction &MF = getMachineFunction();
5488   // An atomic store does not load. An atomic load does not store.
5489   // (An atomicrmw obviously both loads and stores.)
5490   // For now, atomics are considered to be volatile always, and they are
5491   // chained as such.
5492   // FIXME: Volatile isn't really correct; we should keep track of atomic
5493   // orderings in the memoperand.
5494   auto Flags = MachineMemOperand::MOVolatile;
5495   if (Opcode != ISD::ATOMIC_STORE)
5496     Flags |= MachineMemOperand::MOLoad;
5497   if (Opcode != ISD::ATOMIC_LOAD)
5498     Flags |= MachineMemOperand::MOStore;
5499
5500   MachineMemOperand *MMO =
5501     MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
5502                             MemVT.getStoreSize(), Alignment, AAMDNodes(),
5503                             nullptr, SynchScope, Ordering);
5504
5505   return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
5506 }
5507
5508 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5509                                 SDValue Chain, SDValue Ptr, SDValue Val,
5510                                 MachineMemOperand *MMO) {
5511   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
5512           Opcode == ISD::ATOMIC_LOAD_SUB ||
5513           Opcode == ISD::ATOMIC_LOAD_AND ||
5514           Opcode == ISD::ATOMIC_LOAD_OR ||
5515           Opcode == ISD::ATOMIC_LOAD_XOR ||
5516           Opcode == ISD::ATOMIC_LOAD_NAND ||
5517           Opcode == ISD::ATOMIC_LOAD_MIN ||
5518           Opcode == ISD::ATOMIC_LOAD_MAX ||
5519           Opcode == ISD::ATOMIC_LOAD_UMIN ||
5520           Opcode == ISD::ATOMIC_LOAD_UMAX ||
5521           Opcode == ISD::ATOMIC_SWAP ||
5522           Opcode == ISD::ATOMIC_STORE) &&
5523          "Invalid Atomic Op");
5524
5525   EVT VT = Val.getValueType();
5526
5527   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
5528                                                getVTList(VT, MVT::Other);
5529   SDValue Ops[] = {Chain, Ptr, Val};
5530   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5531 }
5532
5533 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5534                                 EVT VT, SDValue Chain, SDValue Ptr,
5535                                 MachineMemOperand *MMO) {
5536   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
5537
5538   SDVTList VTs = getVTList(VT, MVT::Other);
5539   SDValue Ops[] = {Chain, Ptr};
5540   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5541 }
5542
5543 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
5544 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
5545   if (Ops.size() == 1)
5546     return Ops[0];
5547
5548   SmallVector<EVT, 4> VTs;
5549   VTs.reserve(Ops.size());
5550   for (unsigned i = 0; i < Ops.size(); ++i)
5551     VTs.push_back(Ops[i].getValueType());
5552   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
5553 }
5554
5555 SDValue SelectionDAG::getMemIntrinsicNode(
5556     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
5557     EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align, bool Vol,
5558     bool ReadMem, bool WriteMem, unsigned Size) {
5559   if (Align == 0)  // Ensure that codegen never sees alignment 0
5560     Align = getEVTAlignment(MemVT);
5561
5562   MachineFunction &MF = getMachineFunction();
5563   auto Flags = MachineMemOperand::MONone;
5564   if (WriteMem)
5565     Flags |= MachineMemOperand::MOStore;
5566   if (ReadMem)
5567     Flags |= MachineMemOperand::MOLoad;
5568   if (Vol)
5569     Flags |= MachineMemOperand::MOVolatile;
5570   if (!Size)
5571     Size = MemVT.getStoreSize();
5572   MachineMemOperand *MMO =
5573     MF.getMachineMemOperand(PtrInfo, Flags, Size, Align);
5574
5575   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
5576 }
5577
5578 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
5579                                           SDVTList VTList,
5580                                           ArrayRef<SDValue> Ops, EVT MemVT,
5581                                           MachineMemOperand *MMO) {
5582   assert((Opcode == ISD::INTRINSIC_VOID ||
5583           Opcode == ISD::INTRINSIC_W_CHAIN ||
5584           Opcode == ISD::PREFETCH ||
5585           Opcode == ISD::LIFETIME_START ||
5586           Opcode == ISD::LIFETIME_END ||
5587           ((int)Opcode <= std::numeric_limits<int>::max() &&
5588            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
5589          "Opcode is not a memory-accessing opcode!");
5590
5591   // Memoize the node unless it returns a flag.
5592   MemIntrinsicSDNode *N;
5593   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
5594     FoldingSetNodeID ID;
5595     AddNodeIDNode(ID, Opcode, VTList, Ops);
5596     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5597     void *IP = nullptr;
5598     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5599       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
5600       return SDValue(E, 0);
5601     }
5602
5603     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5604                                       VTList, MemVT, MMO);
5605     createOperands(N, Ops);
5606
5607   CSEMap.InsertNode(N, IP);
5608   } else {
5609     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5610                                       VTList, MemVT, MMO);
5611     createOperands(N, Ops);
5612   }
5613   InsertNode(N);
5614   return SDValue(N, 0);
5615 }
5616
5617 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5618 /// MachinePointerInfo record from it.  This is particularly useful because the
5619 /// code generator has many cases where it doesn't bother passing in a
5620 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5621 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5622                                            int64_t Offset = 0) {
5623   // If this is FI+Offset, we can model it.
5624   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
5625     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
5626                                              FI->getIndex(), Offset);
5627
5628   // If this is (FI+Offset1)+Offset2, we can model it.
5629   if (Ptr.getOpcode() != ISD::ADD ||
5630       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
5631       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
5632     return MachinePointerInfo();
5633
5634   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5635   return MachinePointerInfo::getFixedStack(
5636       DAG.getMachineFunction(), FI,
5637       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
5638 }
5639
5640 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5641 /// MachinePointerInfo record from it.  This is particularly useful because the
5642 /// code generator has many cases where it doesn't bother passing in a
5643 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5644 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5645                                            SDValue OffsetOp) {
5646   // If the 'Offset' value isn't a constant, we can't handle this.
5647   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
5648     return InferPointerInfo(DAG, Ptr, OffsetNode->getSExtValue());
5649   if (OffsetOp.isUndef())
5650     return InferPointerInfo(DAG, Ptr);
5651   return MachinePointerInfo();
5652 }
5653
5654 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5655                               EVT VT, const SDLoc &dl, SDValue Chain,
5656                               SDValue Ptr, SDValue Offset,
5657                               MachinePointerInfo PtrInfo, EVT MemVT,
5658                               unsigned Alignment,
5659                               MachineMemOperand::Flags MMOFlags,
5660                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
5661   assert(Chain.getValueType() == MVT::Other &&
5662         "Invalid chain type");
5663   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
5664     Alignment = getEVTAlignment(MemVT);
5665
5666   MMOFlags |= MachineMemOperand::MOLoad;
5667   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
5668   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
5669   // clients.
5670   if (PtrInfo.V.isNull())
5671     PtrInfo = InferPointerInfo(*this, Ptr, Offset);
5672
5673   MachineFunction &MF = getMachineFunction();
5674   MachineMemOperand *MMO = MF.getMachineMemOperand(
5675       PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges);
5676   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
5677 }
5678
5679 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5680                               EVT VT, const SDLoc &dl, SDValue Chain,
5681                               SDValue Ptr, SDValue Offset, EVT MemVT,
5682                               MachineMemOperand *MMO) {
5683   if (VT == MemVT) {
5684     ExtType = ISD::NON_EXTLOAD;
5685   } else if (ExtType == ISD::NON_EXTLOAD) {
5686     assert(VT == MemVT && "Non-extending load from different memory type!");
5687   } else {
5688     // Extending load.
5689     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
5690            "Should only be an extending load, not truncating!");
5691     assert(VT.isInteger() == MemVT.isInteger() &&
5692            "Cannot convert from FP to Int or Int -> FP!");
5693     assert(VT.isVector() == MemVT.isVector() &&
5694            "Cannot use an ext load to convert to or from a vector!");
5695     assert((!VT.isVector() ||
5696             VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
5697            "Cannot use an ext load to change the number of vector elements!");
5698   }
5699
5700   bool Indexed = AM != ISD::UNINDEXED;
5701   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
5702
5703   SDVTList VTs = Indexed ?
5704     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
5705   SDValue Ops[] = { Chain, Ptr, Offset };
5706   FoldingSetNodeID ID;
5707   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
5708   ID.AddInteger(MemVT.getRawBits());
5709   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
5710       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
5711   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5712   void *IP = nullptr;
5713   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5714     cast<LoadSDNode>(E)->refineAlignment(MMO);
5715     return SDValue(E, 0);
5716   }
5717   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5718                                   ExtType, MemVT, MMO);
5719   createOperands(N, Ops);
5720
5721   CSEMap.InsertNode(N, IP);
5722   InsertNode(N);
5723   return SDValue(N, 0);
5724 }
5725
5726 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5727                               SDValue Ptr, MachinePointerInfo PtrInfo,
5728                               unsigned Alignment,
5729                               MachineMemOperand::Flags MMOFlags,
5730                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
5731   SDValue Undef = getUNDEF(Ptr.getValueType());
5732   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5733                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
5734 }
5735
5736 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5737                               SDValue Ptr, MachineMemOperand *MMO) {
5738   SDValue Undef = getUNDEF(Ptr.getValueType());
5739   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5740                  VT, MMO);
5741 }
5742
5743 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5744                                  EVT VT, SDValue Chain, SDValue Ptr,
5745                                  MachinePointerInfo PtrInfo, EVT MemVT,
5746                                  unsigned Alignment,
5747                                  MachineMemOperand::Flags MMOFlags,
5748                                  const AAMDNodes &AAInfo) {
5749   SDValue Undef = getUNDEF(Ptr.getValueType());
5750   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
5751                  MemVT, Alignment, MMOFlags, AAInfo);
5752 }
5753
5754 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5755                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
5756                                  MachineMemOperand *MMO) {
5757   SDValue Undef = getUNDEF(Ptr.getValueType());
5758   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
5759                  MemVT, MMO);
5760 }
5761
5762 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
5763                                      SDValue Base, SDValue Offset,
5764                                      ISD::MemIndexedMode AM) {
5765   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
5766   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
5767   // Don't propagate the invariant or dereferenceable flags.
5768   auto MMOFlags =
5769       LD->getMemOperand()->getFlags() &
5770       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
5771   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
5772                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
5773                  LD->getMemoryVT(), LD->getAlignment(), MMOFlags,
5774                  LD->getAAInfo());
5775 }
5776
5777 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5778                                SDValue Ptr, MachinePointerInfo PtrInfo,
5779                                unsigned Alignment,
5780                                MachineMemOperand::Flags MMOFlags,
5781                                const AAMDNodes &AAInfo) {
5782   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
5783   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
5784     Alignment = getEVTAlignment(Val.getValueType());
5785
5786   MMOFlags |= MachineMemOperand::MOStore;
5787   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5788
5789   if (PtrInfo.V.isNull())
5790     PtrInfo = InferPointerInfo(*this, Ptr);
5791
5792   MachineFunction &MF = getMachineFunction();
5793   MachineMemOperand *MMO = MF.getMachineMemOperand(
5794       PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo);
5795   return getStore(Chain, dl, Val, Ptr, MMO);
5796 }
5797
5798 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5799                                SDValue Ptr, MachineMemOperand *MMO) {
5800   assert(Chain.getValueType() == MVT::Other &&
5801         "Invalid chain type");
5802   EVT VT = Val.getValueType();
5803   SDVTList VTs = getVTList(MVT::Other);
5804   SDValue Undef = getUNDEF(Ptr.getValueType());
5805   SDValue Ops[] = { Chain, Val, Ptr, Undef };
5806   FoldingSetNodeID ID;
5807   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5808   ID.AddInteger(VT.getRawBits());
5809   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
5810       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
5811   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5812   void *IP = nullptr;
5813   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5814     cast<StoreSDNode>(E)->refineAlignment(MMO);
5815     return SDValue(E, 0);
5816   }
5817   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5818                                    ISD::UNINDEXED, false, VT, MMO);
5819   createOperands(N, Ops);
5820
5821   CSEMap.InsertNode(N, IP);
5822   InsertNode(N);
5823   return SDValue(N, 0);
5824 }
5825
5826 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5827                                     SDValue Ptr, MachinePointerInfo PtrInfo,
5828                                     EVT SVT, unsigned Alignment,
5829                                     MachineMemOperand::Flags MMOFlags,
5830                                     const AAMDNodes &AAInfo) {
5831   assert(Chain.getValueType() == MVT::Other &&
5832         "Invalid chain type");
5833   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
5834     Alignment = getEVTAlignment(SVT);
5835
5836   MMOFlags |= MachineMemOperand::MOStore;
5837   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5838
5839   if (PtrInfo.V.isNull())
5840     PtrInfo = InferPointerInfo(*this, Ptr);
5841
5842   MachineFunction &MF = getMachineFunction();
5843   MachineMemOperand *MMO = MF.getMachineMemOperand(
5844       PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
5845   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
5846 }
5847
5848 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5849                                     SDValue Ptr, EVT SVT,
5850                                     MachineMemOperand *MMO) {
5851   EVT VT = Val.getValueType();
5852
5853   assert(Chain.getValueType() == MVT::Other &&
5854         "Invalid chain type");
5855   if (VT == SVT)
5856     return getStore(Chain, dl, Val, Ptr, MMO);
5857
5858   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
5859          "Should only be a truncating store, not extending!");
5860   assert(VT.isInteger() == SVT.isInteger() &&
5861          "Can't do FP-INT conversion!");
5862   assert(VT.isVector() == SVT.isVector() &&
5863          "Cannot use trunc store to convert to or from a vector!");
5864   assert((!VT.isVector() ||
5865           VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
5866          "Cannot use trunc store to change the number of vector elements!");
5867
5868   SDVTList VTs = getVTList(MVT::Other);
5869   SDValue Undef = getUNDEF(Ptr.getValueType());
5870   SDValue Ops[] = { Chain, Val, Ptr, Undef };
5871   FoldingSetNodeID ID;
5872   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5873   ID.AddInteger(SVT.getRawBits());
5874   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
5875       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
5876   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5877   void *IP = nullptr;
5878   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5879     cast<StoreSDNode>(E)->refineAlignment(MMO);
5880     return SDValue(E, 0);
5881   }
5882   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5883                                    ISD::UNINDEXED, true, SVT, MMO);
5884   createOperands(N, Ops);
5885
5886   CSEMap.InsertNode(N, IP);
5887   InsertNode(N);
5888   return SDValue(N, 0);
5889 }
5890
5891 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
5892                                       SDValue Base, SDValue Offset,
5893                                       ISD::MemIndexedMode AM) {
5894   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
5895   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
5896   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
5897   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
5898   FoldingSetNodeID ID;
5899   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5900   ID.AddInteger(ST->getMemoryVT().getRawBits());
5901   ID.AddInteger(ST->getRawSubclassData());
5902   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
5903   void *IP = nullptr;
5904   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
5905     return SDValue(E, 0);
5906
5907   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5908                                    ST->isTruncatingStore(), ST->getMemoryVT(),
5909                                    ST->getMemOperand());
5910   createOperands(N, Ops);
5911
5912   CSEMap.InsertNode(N, IP);
5913   InsertNode(N);
5914   return SDValue(N, 0);
5915 }
5916
5917 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5918                                     SDValue Ptr, SDValue Mask, SDValue Src0,
5919                                     EVT MemVT, MachineMemOperand *MMO,
5920                                     ISD::LoadExtType ExtTy, bool isExpanding) {
5921   SDVTList VTs = getVTList(VT, MVT::Other);
5922   SDValue Ops[] = { Chain, Ptr, Mask, Src0 };
5923   FoldingSetNodeID ID;
5924   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
5925   ID.AddInteger(VT.getRawBits());
5926   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
5927       dl.getIROrder(), VTs, ExtTy, isExpanding, MemVT, MMO));
5928   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5929   void *IP = nullptr;
5930   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5931     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
5932     return SDValue(E, 0);
5933   }
5934   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5935                                         ExtTy, isExpanding, MemVT, MMO);
5936   createOperands(N, Ops);
5937
5938   CSEMap.InsertNode(N, IP);
5939   InsertNode(N);
5940   return SDValue(N, 0);
5941 }
5942
5943 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
5944                                      SDValue Val, SDValue Ptr, SDValue Mask,
5945                                      EVT MemVT, MachineMemOperand *MMO,
5946                                      bool IsTruncating, bool IsCompressing) {
5947   assert(Chain.getValueType() == MVT::Other &&
5948         "Invalid chain type");
5949   EVT VT = Val.getValueType();
5950   SDVTList VTs = getVTList(MVT::Other);
5951   SDValue Ops[] = { Chain, Ptr, Mask, Val };
5952   FoldingSetNodeID ID;
5953   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
5954   ID.AddInteger(VT.getRawBits());
5955   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
5956       dl.getIROrder(), VTs, IsTruncating, IsCompressing, MemVT, MMO));
5957   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5958   void *IP = nullptr;
5959   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5960     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
5961     return SDValue(E, 0);
5962   }
5963   auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5964                                          IsTruncating, IsCompressing, MemVT, MMO);
5965   createOperands(N, Ops);
5966
5967   CSEMap.InsertNode(N, IP);
5968   InsertNode(N);
5969   return SDValue(N, 0);
5970 }
5971
5972 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
5973                                       ArrayRef<SDValue> Ops,
5974                                       MachineMemOperand *MMO) {
5975   assert(Ops.size() == 5 && "Incompatible number of operands");
5976
5977   FoldingSetNodeID ID;
5978   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
5979   ID.AddInteger(VT.getRawBits());
5980   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
5981       dl.getIROrder(), VTs, VT, MMO));
5982   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5983   void *IP = nullptr;
5984   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5985     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
5986     return SDValue(E, 0);
5987   }
5988
5989   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
5990                                           VTs, VT, MMO);
5991   createOperands(N, Ops);
5992
5993   assert(N->getValue().getValueType() == N->getValueType(0) &&
5994          "Incompatible type of the PassThru value in MaskedGatherSDNode");
5995   assert(N->getMask().getValueType().getVectorNumElements() ==
5996              N->getValueType(0).getVectorNumElements() &&
5997          "Vector width mismatch between mask and data");
5998   assert(N->getIndex().getValueType().getVectorNumElements() ==
5999              N->getValueType(0).getVectorNumElements() &&
6000          "Vector width mismatch between index and data");
6001
6002   CSEMap.InsertNode(N, IP);
6003   InsertNode(N);
6004   return SDValue(N, 0);
6005 }
6006
6007 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
6008                                        ArrayRef<SDValue> Ops,
6009                                        MachineMemOperand *MMO) {
6010   assert(Ops.size() == 5 && "Incompatible number of operands");
6011
6012   FoldingSetNodeID ID;
6013   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
6014   ID.AddInteger(VT.getRawBits());
6015   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
6016       dl.getIROrder(), VTs, VT, MMO));
6017   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6018   void *IP = nullptr;
6019   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6020     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
6021     return SDValue(E, 0);
6022   }
6023   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
6024                                            VTs, VT, MMO);
6025   createOperands(N, Ops);
6026
6027   assert(N->getMask().getValueType().getVectorNumElements() ==
6028              N->getValue().getValueType().getVectorNumElements() &&
6029          "Vector width mismatch between mask and data");
6030   assert(N->getIndex().getValueType().getVectorNumElements() ==
6031              N->getValue().getValueType().getVectorNumElements() &&
6032          "Vector width mismatch between index and data");
6033
6034   CSEMap.InsertNode(N, IP);
6035   InsertNode(N);
6036   return SDValue(N, 0);
6037 }
6038
6039 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
6040                                SDValue Ptr, SDValue SV, unsigned Align) {
6041   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
6042   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
6043 }
6044
6045 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6046                               ArrayRef<SDUse> Ops) {
6047   switch (Ops.size()) {
6048   case 0: return getNode(Opcode, DL, VT);
6049   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
6050   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
6051   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
6052   default: break;
6053   }
6054
6055   // Copy from an SDUse array into an SDValue array for use with
6056   // the regular getNode logic.
6057   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
6058   return getNode(Opcode, DL, VT, NewOps);
6059 }
6060
6061 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6062                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
6063   unsigned NumOps = Ops.size();
6064   switch (NumOps) {
6065   case 0: return getNode(Opcode, DL, VT);
6066   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
6067   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
6068   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
6069   default: break;
6070   }
6071
6072   switch (Opcode) {
6073   default: break;
6074   case ISD::CONCAT_VECTORS:
6075     // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
6076     if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
6077       return V;
6078     break;
6079   case ISD::SELECT_CC:
6080     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
6081     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
6082            "LHS and RHS of condition must have same type!");
6083     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
6084            "True and False arms of SelectCC must have same type!");
6085     assert(Ops[2].getValueType() == VT &&
6086            "select_cc node must be of same type as true and false value!");
6087     break;
6088   case ISD::BR_CC:
6089     assert(NumOps == 5 && "BR_CC takes 5 operands!");
6090     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
6091            "LHS/RHS of comparison should match types!");
6092     break;
6093   }
6094
6095   // Memoize nodes.
6096   SDNode *N;
6097   SDVTList VTs = getVTList(VT);
6098
6099   if (VT != MVT::Glue) {
6100     FoldingSetNodeID ID;
6101     AddNodeIDNode(ID, Opcode, VTs, Ops);
6102     void *IP = nullptr;
6103
6104     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6105       return SDValue(E, 0);
6106
6107     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6108     createOperands(N, Ops);
6109
6110     CSEMap.InsertNode(N, IP);
6111   } else {
6112     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6113     createOperands(N, Ops);
6114   }
6115
6116   InsertNode(N);
6117   return SDValue(N, 0);
6118 }
6119
6120 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
6121                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
6122   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
6123 }
6124
6125 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6126                               ArrayRef<SDValue> Ops) {
6127   if (VTList.NumVTs == 1)
6128     return getNode(Opcode, DL, VTList.VTs[0], Ops);
6129
6130 #if 0
6131   switch (Opcode) {
6132   // FIXME: figure out how to safely handle things like
6133   // int foo(int x) { return 1 << (x & 255); }
6134   // int bar() { return foo(256); }
6135   case ISD::SRA_PARTS:
6136   case ISD::SRL_PARTS:
6137   case ISD::SHL_PARTS:
6138     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6139         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
6140       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
6141     else if (N3.getOpcode() == ISD::AND)
6142       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
6143         // If the and is only masking out bits that cannot effect the shift,
6144         // eliminate the and.
6145         unsigned NumBits = VT.getScalarSizeInBits()*2;
6146         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
6147           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
6148       }
6149     break;
6150   }
6151 #endif
6152
6153   // Memoize the node unless it returns a flag.
6154   SDNode *N;
6155   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
6156     FoldingSetNodeID ID;
6157     AddNodeIDNode(ID, Opcode, VTList, Ops);
6158     void *IP = nullptr;
6159     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6160       return SDValue(E, 0);
6161
6162     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
6163     createOperands(N, Ops);
6164     CSEMap.InsertNode(N, IP);
6165   } else {
6166     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
6167     createOperands(N, Ops);
6168   }
6169   InsertNode(N);
6170   return SDValue(N, 0);
6171 }
6172
6173 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
6174                               SDVTList VTList) {
6175   return getNode(Opcode, DL, VTList, None);
6176 }
6177
6178 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6179                               SDValue N1) {
6180   SDValue Ops[] = { N1 };
6181   return getNode(Opcode, DL, VTList, Ops);
6182 }
6183
6184 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6185                               SDValue N1, SDValue N2) {
6186   SDValue Ops[] = { N1, N2 };
6187   return getNode(Opcode, DL, VTList, Ops);
6188 }
6189
6190 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6191                               SDValue N1, SDValue N2, SDValue N3) {
6192   SDValue Ops[] = { N1, N2, N3 };
6193   return getNode(Opcode, DL, VTList, Ops);
6194 }
6195
6196 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6197                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6198   SDValue Ops[] = { N1, N2, N3, N4 };
6199   return getNode(Opcode, DL, VTList, Ops);
6200 }
6201
6202 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6203                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6204                               SDValue N5) {
6205   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6206   return getNode(Opcode, DL, VTList, Ops);
6207 }
6208
6209 SDVTList SelectionDAG::getVTList(EVT VT) {
6210   return makeVTList(SDNode::getValueTypeList(VT), 1);
6211 }
6212
6213 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
6214   FoldingSetNodeID ID;
6215   ID.AddInteger(2U);
6216   ID.AddInteger(VT1.getRawBits());
6217   ID.AddInteger(VT2.getRawBits());
6218
6219   void *IP = nullptr;
6220   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6221   if (!Result) {
6222     EVT *Array = Allocator.Allocate<EVT>(2);
6223     Array[0] = VT1;
6224     Array[1] = VT2;
6225     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
6226     VTListMap.InsertNode(Result, IP);
6227   }
6228   return Result->getSDVTList();
6229 }
6230
6231 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
6232   FoldingSetNodeID ID;
6233   ID.AddInteger(3U);
6234   ID.AddInteger(VT1.getRawBits());
6235   ID.AddInteger(VT2.getRawBits());
6236   ID.AddInteger(VT3.getRawBits());
6237
6238   void *IP = nullptr;
6239   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6240   if (!Result) {
6241     EVT *Array = Allocator.Allocate<EVT>(3);
6242     Array[0] = VT1;
6243     Array[1] = VT2;
6244     Array[2] = VT3;
6245     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
6246     VTListMap.InsertNode(Result, IP);
6247   }
6248   return Result->getSDVTList();
6249 }
6250
6251 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
6252   FoldingSetNodeID ID;
6253   ID.AddInteger(4U);
6254   ID.AddInteger(VT1.getRawBits());
6255   ID.AddInteger(VT2.getRawBits());
6256   ID.AddInteger(VT3.getRawBits());
6257   ID.AddInteger(VT4.getRawBits());
6258
6259   void *IP = nullptr;
6260   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6261   if (!Result) {
6262     EVT *Array = Allocator.Allocate<EVT>(4);
6263     Array[0] = VT1;
6264     Array[1] = VT2;
6265     Array[2] = VT3;
6266     Array[3] = VT4;
6267     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
6268     VTListMap.InsertNode(Result, IP);
6269   }
6270   return Result->getSDVTList();
6271 }
6272
6273 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
6274   unsigned NumVTs = VTs.size();
6275   FoldingSetNodeID ID;
6276   ID.AddInteger(NumVTs);
6277   for (unsigned index = 0; index < NumVTs; index++) {
6278     ID.AddInteger(VTs[index].getRawBits());
6279   }
6280
6281   void *IP = nullptr;
6282   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6283   if (!Result) {
6284     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
6285     std::copy(VTs.begin(), VTs.end(), Array);
6286     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
6287     VTListMap.InsertNode(Result, IP);
6288   }
6289   return Result->getSDVTList();
6290 }
6291
6292
6293 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
6294 /// specified operands.  If the resultant node already exists in the DAG,
6295 /// this does not modify the specified node, instead it returns the node that
6296 /// already exists.  If the resultant node does not exist in the DAG, the
6297 /// input node is returned.  As a degenerate case, if you specify the same
6298 /// input operands as the node already has, the input node is returned.
6299 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
6300   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
6301
6302   // Check to see if there is no change.
6303   if (Op == N->getOperand(0)) return N;
6304
6305   // See if the modified node already exists.
6306   void *InsertPos = nullptr;
6307   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
6308     return Existing;
6309
6310   // Nope it doesn't.  Remove the node from its current place in the maps.
6311   if (InsertPos)
6312     if (!RemoveNodeFromCSEMaps(N))
6313       InsertPos = nullptr;
6314
6315   // Now we update the operands.
6316   N->OperandList[0].set(Op);
6317
6318   // If this gets put into a CSE map, add it.
6319   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6320   return N;
6321 }
6322
6323 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
6324   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
6325
6326   // Check to see if there is no change.
6327   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
6328     return N;   // No operands changed, just return the input node.
6329
6330   // See if the modified node already exists.
6331   void *InsertPos = nullptr;
6332   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
6333     return Existing;
6334
6335   // Nope it doesn't.  Remove the node from its current place in the maps.
6336   if (InsertPos)
6337     if (!RemoveNodeFromCSEMaps(N))
6338       InsertPos = nullptr;
6339
6340   // Now we update the operands.
6341   if (N->OperandList[0] != Op1)
6342     N->OperandList[0].set(Op1);
6343   if (N->OperandList[1] != Op2)
6344     N->OperandList[1].set(Op2);
6345
6346   // If this gets put into a CSE map, add it.
6347   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6348   return N;
6349 }
6350
6351 SDNode *SelectionDAG::
6352 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
6353   SDValue Ops[] = { Op1, Op2, Op3 };
6354   return UpdateNodeOperands(N, Ops);
6355 }
6356
6357 SDNode *SelectionDAG::
6358 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
6359                    SDValue Op3, SDValue Op4) {
6360   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
6361   return UpdateNodeOperands(N, Ops);
6362 }
6363
6364 SDNode *SelectionDAG::
6365 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
6366                    SDValue Op3, SDValue Op4, SDValue Op5) {
6367   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
6368   return UpdateNodeOperands(N, Ops);
6369 }
6370
6371 SDNode *SelectionDAG::
6372 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
6373   unsigned NumOps = Ops.size();
6374   assert(N->getNumOperands() == NumOps &&
6375          "Update with wrong number of operands");
6376
6377   // If no operands changed just return the input node.
6378   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
6379     return N;
6380
6381   // See if the modified node already exists.
6382   void *InsertPos = nullptr;
6383   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
6384     return Existing;
6385
6386   // Nope it doesn't.  Remove the node from its current place in the maps.
6387   if (InsertPos)
6388     if (!RemoveNodeFromCSEMaps(N))
6389       InsertPos = nullptr;
6390
6391   // Now we update the operands.
6392   for (unsigned i = 0; i != NumOps; ++i)
6393     if (N->OperandList[i] != Ops[i])
6394       N->OperandList[i].set(Ops[i]);
6395
6396   // If this gets put into a CSE map, add it.
6397   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6398   return N;
6399 }
6400
6401 /// DropOperands - Release the operands and set this node to have
6402 /// zero operands.
6403 void SDNode::DropOperands() {
6404   // Unlike the code in MorphNodeTo that does this, we don't need to
6405   // watch for dead nodes here.
6406   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
6407     SDUse &Use = *I++;
6408     Use.set(SDValue());
6409   }
6410 }
6411
6412 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
6413 /// machine opcode.
6414 ///
6415 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6416                                    EVT VT) {
6417   SDVTList VTs = getVTList(VT);
6418   return SelectNodeTo(N, MachineOpc, VTs, None);
6419 }
6420
6421 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6422                                    EVT VT, SDValue Op1) {
6423   SDVTList VTs = getVTList(VT);
6424   SDValue Ops[] = { Op1 };
6425   return SelectNodeTo(N, MachineOpc, VTs, Ops);
6426 }
6427
6428 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6429                                    EVT VT, SDValue Op1,
6430                                    SDValue Op2) {
6431   SDVTList VTs = getVTList(VT);
6432   SDValue Ops[] = { Op1, Op2 };
6433   return SelectNodeTo(N, MachineOpc, VTs, Ops);
6434 }
6435
6436 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6437                                    EVT VT, SDValue Op1,
6438                                    SDValue Op2, SDValue Op3) {
6439   SDVTList VTs = getVTList(VT);
6440   SDValue Ops[] = { Op1, Op2, Op3 };
6441   return SelectNodeTo(N, MachineOpc, VTs, Ops);
6442 }
6443
6444 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6445                                    EVT VT, ArrayRef<SDValue> Ops) {
6446   SDVTList VTs = getVTList(VT);
6447   return SelectNodeTo(N, MachineOpc, VTs, Ops);
6448 }
6449
6450 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6451                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
6452   SDVTList VTs = getVTList(VT1, VT2);
6453   return SelectNodeTo(N, MachineOpc, VTs, Ops);
6454 }
6455
6456 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6457                                    EVT VT1, EVT VT2) {
6458   SDVTList VTs = getVTList(VT1, VT2);
6459   return SelectNodeTo(N, MachineOpc, VTs, None);
6460 }
6461
6462 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6463                                    EVT VT1, EVT VT2, EVT VT3,
6464                                    ArrayRef<SDValue> Ops) {
6465   SDVTList VTs = getVTList(VT1, VT2, VT3);
6466   return SelectNodeTo(N, MachineOpc, VTs, Ops);
6467 }
6468
6469 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6470                                    EVT VT1, EVT VT2,
6471                                    SDValue Op1, SDValue Op2) {
6472   SDVTList VTs = getVTList(VT1, VT2);
6473   SDValue Ops[] = { Op1, Op2 };
6474   return SelectNodeTo(N, MachineOpc, VTs, Ops);
6475 }
6476
6477 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6478                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
6479   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
6480   // Reset the NodeID to -1.
6481   New->setNodeId(-1);
6482   if (New != N) {
6483     ReplaceAllUsesWith(N, New);
6484     RemoveDeadNode(N);
6485   }
6486   return New;
6487 }
6488
6489 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
6490 /// the line number information on the merged node since it is not possible to
6491 /// preserve the information that operation is associated with multiple lines.
6492 /// This will make the debugger working better at -O0, were there is a higher
6493 /// probability having other instructions associated with that line.
6494 ///
6495 /// For IROrder, we keep the smaller of the two
6496 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
6497   DebugLoc NLoc = N->getDebugLoc();
6498   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
6499     N->setDebugLoc(DebugLoc());
6500   }
6501   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
6502   N->setIROrder(Order);
6503   return N;
6504 }
6505
6506 /// MorphNodeTo - This *mutates* the specified node to have the specified
6507 /// return type, opcode, and operands.
6508 ///
6509 /// Note that MorphNodeTo returns the resultant node.  If there is already a
6510 /// node of the specified opcode and operands, it returns that node instead of
6511 /// the current one.  Note that the SDLoc need not be the same.
6512 ///
6513 /// Using MorphNodeTo is faster than creating a new node and swapping it in
6514 /// with ReplaceAllUsesWith both because it often avoids allocating a new
6515 /// node, and because it doesn't require CSE recalculation for any of
6516 /// the node's users.
6517 ///
6518 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
6519 /// As a consequence it isn't appropriate to use from within the DAG combiner or
6520 /// the legalizer which maintain worklists that would need to be updated when
6521 /// deleting things.
6522 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
6523                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
6524   // If an identical node already exists, use it.
6525   void *IP = nullptr;
6526   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
6527     FoldingSetNodeID ID;
6528     AddNodeIDNode(ID, Opc, VTs, Ops);
6529     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
6530       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
6531   }
6532
6533   if (!RemoveNodeFromCSEMaps(N))
6534     IP = nullptr;
6535
6536   // Start the morphing.
6537   N->NodeType = Opc;
6538   N->ValueList = VTs.VTs;
6539   N->NumValues = VTs.NumVTs;
6540
6541   // Clear the operands list, updating used nodes to remove this from their
6542   // use list.  Keep track of any operands that become dead as a result.
6543   SmallPtrSet<SDNode*, 16> DeadNodeSet;
6544   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
6545     SDUse &Use = *I++;
6546     SDNode *Used = Use.getNode();
6547     Use.set(SDValue());
6548     if (Used->use_empty())
6549       DeadNodeSet.insert(Used);
6550   }
6551
6552   // For MachineNode, initialize the memory references information.
6553   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
6554     MN->setMemRefs(nullptr, nullptr);
6555
6556   // Swap for an appropriately sized array from the recycler.
6557   removeOperands(N);
6558   createOperands(N, Ops);
6559
6560   // Delete any nodes that are still dead after adding the uses for the
6561   // new operands.
6562   if (!DeadNodeSet.empty()) {
6563     SmallVector<SDNode *, 16> DeadNodes;
6564     for (SDNode *N : DeadNodeSet)
6565       if (N->use_empty())
6566         DeadNodes.push_back(N);
6567     RemoveDeadNodes(DeadNodes);
6568   }
6569
6570   if (IP)
6571     CSEMap.InsertNode(N, IP);   // Memoize the new node.
6572   return N;
6573 }
6574
6575 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
6576   unsigned OrigOpc = Node->getOpcode();
6577   unsigned NewOpc;
6578   bool IsUnary = false;
6579   switch (OrigOpc) {
6580   default: 
6581     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
6582   case ISD::STRICT_FADD: NewOpc = ISD::FADD; break;
6583   case ISD::STRICT_FSUB: NewOpc = ISD::FSUB; break;
6584   case ISD::STRICT_FMUL: NewOpc = ISD::FMUL; break;
6585   case ISD::STRICT_FDIV: NewOpc = ISD::FDIV; break;
6586   case ISD::STRICT_FREM: NewOpc = ISD::FREM; break;
6587   case ISD::STRICT_FSQRT: NewOpc = ISD::FSQRT; IsUnary = true; break;
6588   case ISD::STRICT_FPOW: NewOpc = ISD::FPOW; break;
6589   case ISD::STRICT_FPOWI: NewOpc = ISD::FPOWI; break;
6590   case ISD::STRICT_FSIN: NewOpc = ISD::FSIN; IsUnary = true; break;
6591   case ISD::STRICT_FCOS: NewOpc = ISD::FCOS; IsUnary = true; break;
6592   case ISD::STRICT_FEXP: NewOpc = ISD::FEXP; IsUnary = true; break;
6593   case ISD::STRICT_FEXP2: NewOpc = ISD::FEXP2; IsUnary = true; break;
6594   case ISD::STRICT_FLOG: NewOpc = ISD::FLOG; IsUnary = true; break;
6595   case ISD::STRICT_FLOG10: NewOpc = ISD::FLOG10; IsUnary = true; break;
6596   case ISD::STRICT_FLOG2: NewOpc = ISD::FLOG2; IsUnary = true; break;
6597   case ISD::STRICT_FRINT: NewOpc = ISD::FRINT; IsUnary = true; break;
6598   case ISD::STRICT_FNEARBYINT:
6599     NewOpc = ISD::FNEARBYINT;
6600     IsUnary = true;
6601     break;
6602   }
6603
6604   // We're taking this node out of the chain, so we need to re-link things.
6605   SDValue InputChain = Node->getOperand(0);
6606   SDValue OutputChain = SDValue(Node, 1);
6607   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
6608
6609   SDVTList VTs = getVTList(Node->getOperand(1).getValueType());
6610   SDNode *Res = nullptr;
6611   if (IsUnary)
6612     Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1) });
6613   else
6614     Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1),
6615                                            Node->getOperand(2) });
6616   
6617   // MorphNodeTo can operate in two ways: if an existing node with the
6618   // specified operands exists, it can just return it.  Otherwise, it
6619   // updates the node in place to have the requested operands.
6620   if (Res == Node) {
6621     // If we updated the node in place, reset the node ID.  To the isel,
6622     // this should be just like a newly allocated machine node.
6623     Res->setNodeId(-1);
6624   } else {
6625     ReplaceAllUsesWith(Node, Res);
6626     RemoveDeadNode(Node);
6627   }
6628
6629   return Res; 
6630 }
6631
6632 /// getMachineNode - These are used for target selectors to create a new node
6633 /// with specified return type(s), MachineInstr opcode, and operands.
6634 ///
6635 /// Note that getMachineNode returns the resultant node.  If there is already a
6636 /// node of the specified opcode and operands, it returns that node instead of
6637 /// the current one.
6638 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6639                                             EVT VT) {
6640   SDVTList VTs = getVTList(VT);
6641   return getMachineNode(Opcode, dl, VTs, None);
6642 }
6643
6644 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6645                                             EVT VT, SDValue Op1) {
6646   SDVTList VTs = getVTList(VT);
6647   SDValue Ops[] = { Op1 };
6648   return getMachineNode(Opcode, dl, VTs, Ops);
6649 }
6650
6651 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6652                                             EVT VT, SDValue Op1, SDValue Op2) {
6653   SDVTList VTs = getVTList(VT);
6654   SDValue Ops[] = { Op1, Op2 };
6655   return getMachineNode(Opcode, dl, VTs, Ops);
6656 }
6657
6658 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6659                                             EVT VT, SDValue Op1, SDValue Op2,
6660                                             SDValue Op3) {
6661   SDVTList VTs = getVTList(VT);
6662   SDValue Ops[] = { Op1, Op2, Op3 };
6663   return getMachineNode(Opcode, dl, VTs, Ops);
6664 }
6665
6666 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6667                                             EVT VT, ArrayRef<SDValue> Ops) {
6668   SDVTList VTs = getVTList(VT);
6669   return getMachineNode(Opcode, dl, VTs, Ops);
6670 }
6671
6672 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6673                                             EVT VT1, EVT VT2, SDValue Op1,
6674                                             SDValue Op2) {
6675   SDVTList VTs = getVTList(VT1, VT2);
6676   SDValue Ops[] = { Op1, Op2 };
6677   return getMachineNode(Opcode, dl, VTs, Ops);
6678 }
6679
6680 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6681                                             EVT VT1, EVT VT2, SDValue Op1,
6682                                             SDValue Op2, SDValue Op3) {
6683   SDVTList VTs = getVTList(VT1, VT2);
6684   SDValue Ops[] = { Op1, Op2, Op3 };
6685   return getMachineNode(Opcode, dl, VTs, Ops);
6686 }
6687
6688 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6689                                             EVT VT1, EVT VT2,
6690                                             ArrayRef<SDValue> Ops) {
6691   SDVTList VTs = getVTList(VT1, VT2);
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                                             SDValue Op1, SDValue Op2) {
6698   SDVTList VTs = getVTList(VT1, VT2, VT3);
6699   SDValue Ops[] = { Op1, Op2 };
6700   return getMachineNode(Opcode, dl, VTs, Ops);
6701 }
6702
6703 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6704                                             EVT VT1, EVT VT2, EVT VT3,
6705                                             SDValue Op1, SDValue Op2,
6706                                             SDValue Op3) {
6707   SDVTList VTs = getVTList(VT1, VT2, VT3);
6708   SDValue Ops[] = { Op1, Op2, Op3 };
6709   return getMachineNode(Opcode, dl, VTs, Ops);
6710 }
6711
6712 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6713                                             EVT VT1, EVT VT2, EVT VT3,
6714                                             ArrayRef<SDValue> Ops) {
6715   SDVTList VTs = getVTList(VT1, VT2, VT3);
6716   return getMachineNode(Opcode, dl, VTs, Ops);
6717 }
6718
6719 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6720                                             ArrayRef<EVT> ResultTys,
6721                                             ArrayRef<SDValue> Ops) {
6722   SDVTList VTs = getVTList(ResultTys);
6723   return getMachineNode(Opcode, dl, VTs, Ops);
6724 }
6725
6726 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
6727                                             SDVTList VTs,
6728                                             ArrayRef<SDValue> Ops) {
6729   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
6730   MachineSDNode *N;
6731   void *IP = nullptr;
6732
6733   if (DoCSE) {
6734     FoldingSetNodeID ID;
6735     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
6736     IP = nullptr;
6737     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6738       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
6739     }
6740   }
6741
6742   // Allocate a new MachineSDNode.
6743   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6744   createOperands(N, Ops);
6745
6746   if (DoCSE)
6747     CSEMap.InsertNode(N, IP);
6748
6749   InsertNode(N);
6750   return N;
6751 }
6752
6753 /// getTargetExtractSubreg - A convenience function for creating
6754 /// TargetOpcode::EXTRACT_SUBREG nodes.
6755 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6756                                              SDValue Operand) {
6757   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6758   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
6759                                   VT, Operand, SRIdxVal);
6760   return SDValue(Subreg, 0);
6761 }
6762
6763 /// getTargetInsertSubreg - A convenience function for creating
6764 /// TargetOpcode::INSERT_SUBREG nodes.
6765 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6766                                             SDValue Operand, SDValue Subreg) {
6767   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6768   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
6769                                   VT, Operand, Subreg, SRIdxVal);
6770   return SDValue(Result, 0);
6771 }
6772
6773 /// getNodeIfExists - Get the specified node if it's already available, or
6774 /// else return NULL.
6775 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
6776                                       ArrayRef<SDValue> Ops,
6777                                       const SDNodeFlags Flags) {
6778   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
6779     FoldingSetNodeID ID;
6780     AddNodeIDNode(ID, Opcode, VTList, Ops);
6781     void *IP = nullptr;
6782     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
6783       E->intersectFlagsWith(Flags);
6784       return E;
6785     }
6786   }
6787   return nullptr;
6788 }
6789
6790 /// getDbgValue - Creates a SDDbgValue node.
6791 ///
6792 /// SDNode
6793 SDDbgValue *SelectionDAG::getDbgValue(MDNode *Var, MDNode *Expr, SDNode *N,
6794                                       unsigned R, bool IsIndirect, uint64_t Off,
6795                                       const DebugLoc &DL, unsigned O) {
6796   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6797          "Expected inlined-at fields to agree");
6798   return new (DbgInfo->getAlloc())
6799       SDDbgValue(Var, Expr, N, R, IsIndirect, Off, DL, O);
6800 }
6801
6802 /// Constant
6803 SDDbgValue *SelectionDAG::getConstantDbgValue(MDNode *Var, MDNode *Expr,
6804                                               const Value *C, uint64_t Off,
6805                                               const DebugLoc &DL, unsigned O) {
6806   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6807          "Expected inlined-at fields to agree");
6808   return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, Off, DL, O);
6809 }
6810
6811 /// FrameIndex
6812 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(MDNode *Var, MDNode *Expr,
6813                                                 unsigned FI, uint64_t Off,
6814                                                 const DebugLoc &DL,
6815                                                 unsigned O) {
6816   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6817          "Expected inlined-at fields to agree");
6818   return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, FI, Off, DL, O);
6819 }
6820
6821 namespace {
6822
6823 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
6824 /// pointed to by a use iterator is deleted, increment the use iterator
6825 /// so that it doesn't dangle.
6826 ///
6827 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
6828   SDNode::use_iterator &UI;
6829   SDNode::use_iterator &UE;
6830
6831   void NodeDeleted(SDNode *N, SDNode *E) override {
6832     // Increment the iterator as needed.
6833     while (UI != UE && N == *UI)
6834       ++UI;
6835   }
6836
6837 public:
6838   RAUWUpdateListener(SelectionDAG &d,
6839                      SDNode::use_iterator &ui,
6840                      SDNode::use_iterator &ue)
6841     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
6842 };
6843
6844 } // end anonymous namespace
6845
6846 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6847 /// This can cause recursive merging of nodes in the DAG.
6848 ///
6849 /// This version assumes From has a single result value.
6850 ///
6851 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
6852   SDNode *From = FromN.getNode();
6853   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
6854          "Cannot replace with this method!");
6855   assert(From != To.getNode() && "Cannot replace uses of with self");
6856
6857   // Preserve Debug Values
6858   TransferDbgValues(FromN, To);
6859
6860   // Iterate over all the existing uses of From. New uses will be added
6861   // to the beginning of the use list, which we avoid visiting.
6862   // This specifically avoids visiting uses of From that arise while the
6863   // replacement is happening, because any such uses would be the result
6864   // of CSE: If an existing node looks like From after one of its operands
6865   // is replaced by To, we don't want to replace of all its users with To
6866   // too. See PR3018 for more info.
6867   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6868   RAUWUpdateListener Listener(*this, UI, UE);
6869   while (UI != UE) {
6870     SDNode *User = *UI;
6871
6872     // This node is about to morph, remove its old self from the CSE maps.
6873     RemoveNodeFromCSEMaps(User);
6874
6875     // A user can appear in a use list multiple times, and when this
6876     // happens the uses are usually next to each other in the list.
6877     // To help reduce the number of CSE recomputations, process all
6878     // the uses of this user that we can find this way.
6879     do {
6880       SDUse &Use = UI.getUse();
6881       ++UI;
6882       Use.set(To);
6883     } while (UI != UE && *UI == User);
6884
6885     // Now that we have modified User, add it back to the CSE maps.  If it
6886     // already exists there, recursively merge the results together.
6887     AddModifiedNodeToCSEMaps(User);
6888   }
6889
6890   // If we just RAUW'd the root, take note.
6891   if (FromN == getRoot())
6892     setRoot(To);
6893 }
6894
6895 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6896 /// This can cause recursive merging of nodes in the DAG.
6897 ///
6898 /// This version assumes that for each value of From, there is a
6899 /// corresponding value in To in the same position with the same type.
6900 ///
6901 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
6902 #ifndef NDEBUG
6903   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6904     assert((!From->hasAnyUseOfValue(i) ||
6905             From->getValueType(i) == To->getValueType(i)) &&
6906            "Cannot use this version of ReplaceAllUsesWith!");
6907 #endif
6908
6909   // Handle the trivial case.
6910   if (From == To)
6911     return;
6912
6913   // Preserve Debug Info. Only do this if there's a use.
6914   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6915     if (From->hasAnyUseOfValue(i)) {
6916       assert((i < To->getNumValues()) && "Invalid To location");
6917       TransferDbgValues(SDValue(From, i), SDValue(To, i));
6918     }
6919
6920   // Iterate over just the existing users of From. See the comments in
6921   // the ReplaceAllUsesWith above.
6922   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6923   RAUWUpdateListener Listener(*this, UI, UE);
6924   while (UI != UE) {
6925     SDNode *User = *UI;
6926
6927     // This node is about to morph, remove its old self from the CSE maps.
6928     RemoveNodeFromCSEMaps(User);
6929
6930     // A user can appear in a use list multiple times, and when this
6931     // happens the uses are usually next to each other in the list.
6932     // To help reduce the number of CSE recomputations, process all
6933     // the uses of this user that we can find this way.
6934     do {
6935       SDUse &Use = UI.getUse();
6936       ++UI;
6937       Use.setNode(To);
6938     } while (UI != UE && *UI == User);
6939
6940     // Now that we have modified User, add it back to the CSE maps.  If it
6941     // already exists there, recursively merge the results together.
6942     AddModifiedNodeToCSEMaps(User);
6943   }
6944
6945   // If we just RAUW'd the root, take note.
6946   if (From == getRoot().getNode())
6947     setRoot(SDValue(To, getRoot().getResNo()));
6948 }
6949
6950 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6951 /// This can cause recursive merging of nodes in the DAG.
6952 ///
6953 /// This version can replace From with any result values.  To must match the
6954 /// number and types of values returned by From.
6955 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
6956   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
6957     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
6958
6959   // Preserve Debug Info.
6960   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6961     TransferDbgValues(SDValue(From, i), *To);
6962
6963   // Iterate over just the existing users of From. See the comments in
6964   // the ReplaceAllUsesWith above.
6965   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6966   RAUWUpdateListener Listener(*this, UI, UE);
6967   while (UI != UE) {
6968     SDNode *User = *UI;
6969
6970     // This node is about to morph, remove its old self from the CSE maps.
6971     RemoveNodeFromCSEMaps(User);
6972
6973     // A user can appear in a use list multiple times, and when this
6974     // happens the uses are usually next to each other in the list.
6975     // To help reduce the number of CSE recomputations, process all
6976     // the uses of this user that we can find this way.
6977     do {
6978       SDUse &Use = UI.getUse();
6979       const SDValue &ToOp = To[Use.getResNo()];
6980       ++UI;
6981       Use.set(ToOp);
6982     } while (UI != UE && *UI == User);
6983
6984     // Now that we have modified User, add it back to the CSE maps.  If it
6985     // already exists there, recursively merge the results together.
6986     AddModifiedNodeToCSEMaps(User);
6987   }
6988
6989   // If we just RAUW'd the root, take note.
6990   if (From == getRoot().getNode())
6991     setRoot(SDValue(To[getRoot().getResNo()]));
6992 }
6993
6994 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
6995 /// uses of other values produced by From.getNode() alone.  The Deleted
6996 /// vector is handled the same way as for ReplaceAllUsesWith.
6997 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
6998   // Handle the really simple, really trivial case efficiently.
6999   if (From == To) return;
7000
7001   // Handle the simple, trivial, case efficiently.
7002   if (From.getNode()->getNumValues() == 1) {
7003     ReplaceAllUsesWith(From, To);
7004     return;
7005   }
7006
7007   // Preserve Debug Info.
7008   TransferDbgValues(From, To);
7009
7010   // Iterate over just the existing users of From. See the comments in
7011   // the ReplaceAllUsesWith above.
7012   SDNode::use_iterator UI = From.getNode()->use_begin(),
7013                        UE = From.getNode()->use_end();
7014   RAUWUpdateListener Listener(*this, UI, UE);
7015   while (UI != UE) {
7016     SDNode *User = *UI;
7017     bool UserRemovedFromCSEMaps = false;
7018
7019     // A user can appear in a use list multiple times, and when this
7020     // happens the uses are usually next to each other in the list.
7021     // To help reduce the number of CSE recomputations, process all
7022     // the uses of this user that we can find this way.
7023     do {
7024       SDUse &Use = UI.getUse();
7025
7026       // Skip uses of different values from the same node.
7027       if (Use.getResNo() != From.getResNo()) {
7028         ++UI;
7029         continue;
7030       }
7031
7032       // If this node hasn't been modified yet, it's still in the CSE maps,
7033       // so remove its old self from the CSE maps.
7034       if (!UserRemovedFromCSEMaps) {
7035         RemoveNodeFromCSEMaps(User);
7036         UserRemovedFromCSEMaps = true;
7037       }
7038
7039       ++UI;
7040       Use.set(To);
7041     } while (UI != UE && *UI == User);
7042
7043     // We are iterating over all uses of the From node, so if a use
7044     // doesn't use the specific value, no changes are made.
7045     if (!UserRemovedFromCSEMaps)
7046       continue;
7047
7048     // Now that we have modified User, add it back to the CSE maps.  If it
7049     // already exists there, recursively merge the results together.
7050     AddModifiedNodeToCSEMaps(User);
7051   }
7052
7053   // If we just RAUW'd the root, take note.
7054   if (From == getRoot())
7055     setRoot(To);
7056 }
7057
7058 namespace {
7059
7060   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
7061   /// to record information about a use.
7062   struct UseMemo {
7063     SDNode *User;
7064     unsigned Index;
7065     SDUse *Use;
7066   };
7067
7068   /// operator< - Sort Memos by User.
7069   bool operator<(const UseMemo &L, const UseMemo &R) {
7070     return (intptr_t)L.User < (intptr_t)R.User;
7071   }
7072
7073 } // end anonymous namespace
7074
7075 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
7076 /// uses of other values produced by From.getNode() alone.  The same value
7077 /// may appear in both the From and To list.  The Deleted vector is
7078 /// handled the same way as for ReplaceAllUsesWith.
7079 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
7080                                               const SDValue *To,
7081                                               unsigned Num){
7082   // Handle the simple, trivial case efficiently.
7083   if (Num == 1)
7084     return ReplaceAllUsesOfValueWith(*From, *To);
7085
7086   TransferDbgValues(*From, *To);
7087
7088   // Read up all the uses and make records of them. This helps
7089   // processing new uses that are introduced during the
7090   // replacement process.
7091   SmallVector<UseMemo, 4> Uses;
7092   for (unsigned i = 0; i != Num; ++i) {
7093     unsigned FromResNo = From[i].getResNo();
7094     SDNode *FromNode = From[i].getNode();
7095     for (SDNode::use_iterator UI = FromNode->use_begin(),
7096          E = FromNode->use_end(); UI != E; ++UI) {
7097       SDUse &Use = UI.getUse();
7098       if (Use.getResNo() == FromResNo) {
7099         UseMemo Memo = { *UI, i, &Use };
7100         Uses.push_back(Memo);
7101       }
7102     }
7103   }
7104
7105   // Sort the uses, so that all the uses from a given User are together.
7106   std::sort(Uses.begin(), Uses.end());
7107
7108   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
7109        UseIndex != UseIndexEnd; ) {
7110     // We know that this user uses some value of From.  If it is the right
7111     // value, update it.
7112     SDNode *User = Uses[UseIndex].User;
7113
7114     // This node is about to morph, remove its old self from the CSE maps.
7115     RemoveNodeFromCSEMaps(User);
7116
7117     // The Uses array is sorted, so all the uses for a given User
7118     // are next to each other in the list.
7119     // To help reduce the number of CSE recomputations, process all
7120     // the uses of this user that we can find this way.
7121     do {
7122       unsigned i = Uses[UseIndex].Index;
7123       SDUse &Use = *Uses[UseIndex].Use;
7124       ++UseIndex;
7125
7126       Use.set(To[i]);
7127     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
7128
7129     // Now that we have modified User, add it back to the CSE maps.  If it
7130     // already exists there, recursively merge the results together.
7131     AddModifiedNodeToCSEMaps(User);
7132   }
7133 }
7134
7135 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
7136 /// based on their topological order. It returns the maximum id and a vector
7137 /// of the SDNodes* in assigned order by reference.
7138 unsigned SelectionDAG::AssignTopologicalOrder() {
7139   unsigned DAGSize = 0;
7140
7141   // SortedPos tracks the progress of the algorithm. Nodes before it are
7142   // sorted, nodes after it are unsorted. When the algorithm completes
7143   // it is at the end of the list.
7144   allnodes_iterator SortedPos = allnodes_begin();
7145
7146   // Visit all the nodes. Move nodes with no operands to the front of
7147   // the list immediately. Annotate nodes that do have operands with their
7148   // operand count. Before we do this, the Node Id fields of the nodes
7149   // may contain arbitrary values. After, the Node Id fields for nodes
7150   // before SortedPos will contain the topological sort index, and the
7151   // Node Id fields for nodes At SortedPos and after will contain the
7152   // count of outstanding operands.
7153   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
7154     SDNode *N = &*I++;
7155     checkForCycles(N, this);
7156     unsigned Degree = N->getNumOperands();
7157     if (Degree == 0) {
7158       // A node with no uses, add it to the result array immediately.
7159       N->setNodeId(DAGSize++);
7160       allnodes_iterator Q(N);
7161       if (Q != SortedPos)
7162         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
7163       assert(SortedPos != AllNodes.end() && "Overran node list");
7164       ++SortedPos;
7165     } else {
7166       // Temporarily use the Node Id as scratch space for the degree count.
7167       N->setNodeId(Degree);
7168     }
7169   }
7170
7171   // Visit all the nodes. As we iterate, move nodes into sorted order,
7172   // such that by the time the end is reached all nodes will be sorted.
7173   for (SDNode &Node : allnodes()) {
7174     SDNode *N = &Node;
7175     checkForCycles(N, this);
7176     // N is in sorted position, so all its uses have one less operand
7177     // that needs to be sorted.
7178     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7179          UI != UE; ++UI) {
7180       SDNode *P = *UI;
7181       unsigned Degree = P->getNodeId();
7182       assert(Degree != 0 && "Invalid node degree");
7183       --Degree;
7184       if (Degree == 0) {
7185         // All of P's operands are sorted, so P may sorted now.
7186         P->setNodeId(DAGSize++);
7187         if (P->getIterator() != SortedPos)
7188           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
7189         assert(SortedPos != AllNodes.end() && "Overran node list");
7190         ++SortedPos;
7191       } else {
7192         // Update P's outstanding operand count.
7193         P->setNodeId(Degree);
7194       }
7195     }
7196     if (Node.getIterator() == SortedPos) {
7197 #ifndef NDEBUG
7198       allnodes_iterator I(N);
7199       SDNode *S = &*++I;
7200       dbgs() << "Overran sorted position:\n";
7201       S->dumprFull(this); dbgs() << "\n";
7202       dbgs() << "Checking if this is due to cycles\n";
7203       checkForCycles(this, true);
7204 #endif
7205       llvm_unreachable(nullptr);
7206     }
7207   }
7208
7209   assert(SortedPos == AllNodes.end() &&
7210          "Topological sort incomplete!");
7211   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
7212          "First node in topological sort is not the entry token!");
7213   assert(AllNodes.front().getNodeId() == 0 &&
7214          "First node in topological sort has non-zero id!");
7215   assert(AllNodes.front().getNumOperands() == 0 &&
7216          "First node in topological sort has operands!");
7217   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
7218          "Last node in topologic sort has unexpected id!");
7219   assert(AllNodes.back().use_empty() &&
7220          "Last node in topologic sort has users!");
7221   assert(DAGSize == allnodes_size() && "Node count mismatch!");
7222   return DAGSize;
7223 }
7224
7225 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
7226 /// value is produced by SD.
7227 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
7228   if (SD) {
7229     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
7230     SD->setHasDebugValue(true);
7231   }
7232   DbgInfo->add(DB, SD, isParameter);
7233 }
7234
7235 /// TransferDbgValues - Transfer SDDbgValues. Called in replace nodes.
7236 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) {
7237   if (From == To || !From.getNode()->getHasDebugValue())
7238     return;
7239   SDNode *FromNode = From.getNode();
7240   SDNode *ToNode = To.getNode();
7241   ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode);
7242   SmallVector<SDDbgValue *, 2> ClonedDVs;
7243   for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end();
7244        I != E; ++I) {
7245     SDDbgValue *Dbg = *I;
7246     // Only add Dbgvalues attached to same ResNo.
7247     if (Dbg->getKind() == SDDbgValue::SDNODE &&
7248         Dbg->getSDNode() == From.getNode() &&
7249         Dbg->getResNo() == From.getResNo() && !Dbg->isInvalidated()) {
7250       assert(FromNode != ToNode &&
7251              "Should not transfer Debug Values intranode");
7252       SDDbgValue *Clone =
7253           getDbgValue(Dbg->getVariable(), Dbg->getExpression(), ToNode,
7254                       To.getResNo(), Dbg->isIndirect(), Dbg->getOffset(),
7255                       Dbg->getDebugLoc(), Dbg->getOrder());
7256       ClonedDVs.push_back(Clone);
7257       Dbg->setIsInvalidated();
7258     }
7259   }
7260   for (SDDbgValue *I : ClonedDVs)
7261     AddDbgValue(I, ToNode, false);
7262 }
7263
7264 void SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
7265                                                 SDValue NewMemOp) {
7266   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
7267   if (!OldLoad->hasAnyUseOfValue(1))
7268     return;
7269
7270   // The new memory operation must have the same position as the old load in
7271   // terms of memory dependency. Create a TokenFactor for the old load and new
7272   // memory operation and update uses of the old load's output chain to use that
7273   // TokenFactor.
7274   SDValue OldChain = SDValue(OldLoad, 1);
7275   SDValue NewChain = SDValue(NewMemOp.getNode(), 1);
7276   SDValue TokenFactor =
7277       getNode(ISD::TokenFactor, SDLoc(OldLoad), MVT::Other, OldChain, NewChain);
7278   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
7279   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewChain);
7280 }
7281
7282 //===----------------------------------------------------------------------===//
7283 //                              SDNode Class
7284 //===----------------------------------------------------------------------===//
7285
7286 bool llvm::isNullConstant(SDValue V) {
7287   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7288   return Const != nullptr && Const->isNullValue();
7289 }
7290
7291 bool llvm::isNullFPConstant(SDValue V) {
7292   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
7293   return Const != nullptr && Const->isZero() && !Const->isNegative();
7294 }
7295
7296 bool llvm::isAllOnesConstant(SDValue V) {
7297   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7298   return Const != nullptr && Const->isAllOnesValue();
7299 }
7300
7301 bool llvm::isOneConstant(SDValue V) {
7302   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7303   return Const != nullptr && Const->isOne();
7304 }
7305
7306 bool llvm::isBitwiseNot(SDValue V) {
7307   return V.getOpcode() == ISD::XOR && isAllOnesConstant(V.getOperand(1));
7308 }
7309
7310 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N) {
7311   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
7312     return CN;
7313
7314   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
7315     BitVector UndefElements;
7316     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
7317
7318     // BuildVectors can truncate their operands. Ignore that case here.
7319     // FIXME: We blindly ignore splats which include undef which is overly
7320     // pessimistic.
7321     if (CN && UndefElements.none() &&
7322         CN->getValueType(0) == N.getValueType().getScalarType())
7323       return CN;
7324   }
7325
7326   return nullptr;
7327 }
7328
7329 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N) {
7330   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
7331     return CN;
7332
7333   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
7334     BitVector UndefElements;
7335     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
7336
7337     if (CN && UndefElements.none())
7338       return CN;
7339   }
7340
7341   return nullptr;
7342 }
7343
7344 HandleSDNode::~HandleSDNode() {
7345   DropOperands();
7346 }
7347
7348 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
7349                                          const DebugLoc &DL,
7350                                          const GlobalValue *GA, EVT VT,
7351                                          int64_t o, unsigned char TF)
7352     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
7353   TheGlobal = GA;
7354 }
7355
7356 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
7357                                          EVT VT, unsigned SrcAS,
7358                                          unsigned DestAS)
7359     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
7360       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
7361
7362 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
7363                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
7364     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
7365   MemSDNodeBits.IsVolatile = MMO->isVolatile();
7366   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
7367   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
7368   MemSDNodeBits.IsInvariant = MMO->isInvariant();
7369
7370   // We check here that the size of the memory operand fits within the size of
7371   // the MMO. This is because the MMO might indicate only a possible address
7372   // range instead of specifying the affected memory addresses precisely.
7373   assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
7374 }
7375
7376 /// Profile - Gather unique data for the node.
7377 ///
7378 void SDNode::Profile(FoldingSetNodeID &ID) const {
7379   AddNodeIDNode(ID, this);
7380 }
7381
7382 namespace {
7383
7384   struct EVTArray {
7385     std::vector<EVT> VTs;
7386
7387     EVTArray() {
7388       VTs.reserve(MVT::LAST_VALUETYPE);
7389       for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
7390         VTs.push_back(MVT((MVT::SimpleValueType)i));
7391     }
7392   };
7393
7394 } // end anonymous namespace
7395
7396 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
7397 static ManagedStatic<EVTArray> SimpleVTArray;
7398 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
7399
7400 /// getValueTypeList - Return a pointer to the specified value type.
7401 ///
7402 const EVT *SDNode::getValueTypeList(EVT VT) {
7403   if (VT.isExtended()) {
7404     sys::SmartScopedLock<true> Lock(*VTMutex);
7405     return &(*EVTs->insert(VT).first);
7406   } else {
7407     assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
7408            "Value type out of range!");
7409     return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
7410   }
7411 }
7412
7413 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
7414 /// indicated value.  This method ignores uses of other values defined by this
7415 /// operation.
7416 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
7417   assert(Value < getNumValues() && "Bad value!");
7418
7419   // TODO: Only iterate over uses of a given value of the node
7420   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
7421     if (UI.getUse().getResNo() == Value) {
7422       if (NUses == 0)
7423         return false;
7424       --NUses;
7425     }
7426   }
7427
7428   // Found exactly the right number of uses?
7429   return NUses == 0;
7430 }
7431
7432 /// hasAnyUseOfValue - Return true if there are any use of the indicated
7433 /// value. This method ignores uses of other values defined by this operation.
7434 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
7435   assert(Value < getNumValues() && "Bad value!");
7436
7437   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
7438     if (UI.getUse().getResNo() == Value)
7439       return true;
7440
7441   return false;
7442 }
7443
7444 /// isOnlyUserOf - Return true if this node is the only use of N.
7445 bool SDNode::isOnlyUserOf(const SDNode *N) const {
7446   bool Seen = false;
7447   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
7448     SDNode *User = *I;
7449     if (User == this)
7450       Seen = true;
7451     else
7452       return false;
7453   }
7454
7455   return Seen;
7456 }
7457
7458 /// Return true if the only users of N are contained in Nodes.
7459 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
7460   bool Seen = false;
7461   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
7462     SDNode *User = *I;
7463     if (llvm::any_of(Nodes,
7464                      [&User](const SDNode *Node) { return User == Node; }))
7465       Seen = true;
7466     else
7467       return false;
7468   }
7469
7470   return Seen;
7471 }
7472
7473 /// isOperand - Return true if this node is an operand of N.
7474 bool SDValue::isOperandOf(const SDNode *N) const {
7475   for (const SDValue &Op : N->op_values())
7476     if (*this == Op)
7477       return true;
7478   return false;
7479 }
7480
7481 bool SDNode::isOperandOf(const SDNode *N) const {
7482   for (const SDValue &Op : N->op_values())
7483     if (this == Op.getNode())
7484       return true;
7485   return false;
7486 }
7487
7488 /// reachesChainWithoutSideEffects - Return true if this operand (which must
7489 /// be a chain) reaches the specified operand without crossing any
7490 /// side-effecting instructions on any chain path.  In practice, this looks
7491 /// through token factors and non-volatile loads.  In order to remain efficient,
7492 /// this only looks a couple of nodes in, it does not do an exhaustive search.
7493 ///
7494 /// Note that we only need to examine chains when we're searching for
7495 /// side-effects; SelectionDAG requires that all side-effects are represented
7496 /// by chains, even if another operand would force a specific ordering. This
7497 /// constraint is necessary to allow transformations like splitting loads.
7498 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
7499                                              unsigned Depth) const {
7500   if (*this == Dest) return true;
7501
7502   // Don't search too deeply, we just want to be able to see through
7503   // TokenFactor's etc.
7504   if (Depth == 0) return false;
7505
7506   // If this is a token factor, all inputs to the TF happen in parallel.
7507   if (getOpcode() == ISD::TokenFactor) {
7508     // First, try a shallow search.
7509     if (is_contained((*this)->ops(), Dest)) {
7510       // We found the chain we want as an operand of this TokenFactor.
7511       // Essentially, we reach the chain without side-effects if we could
7512       // serialize the TokenFactor into a simple chain of operations with
7513       // Dest as the last operation. This is automatically true if the
7514       // chain has one use: there are no other ordering constraints.
7515       // If the chain has more than one use, we give up: some other
7516       // use of Dest might force a side-effect between Dest and the current
7517       // node.
7518       if (Dest.hasOneUse())
7519         return true;
7520     }
7521     // Next, try a deep search: check whether every operand of the TokenFactor
7522     // reaches Dest.
7523     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
7524       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
7525     });
7526   }
7527
7528   // Loads don't have side effects, look through them.
7529   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
7530     if (!Ld->isVolatile())
7531       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
7532   }
7533   return false;
7534 }
7535
7536 bool SDNode::hasPredecessor(const SDNode *N) const {
7537   SmallPtrSet<const SDNode *, 32> Visited;
7538   SmallVector<const SDNode *, 16> Worklist;
7539   Worklist.push_back(this);
7540   return hasPredecessorHelper(N, Visited, Worklist);
7541 }
7542
7543 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
7544   this->Flags.intersectWith(Flags);
7545 }
7546
7547 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
7548   assert(N->getNumValues() == 1 &&
7549          "Can't unroll a vector with multiple results!");
7550
7551   EVT VT = N->getValueType(0);
7552   unsigned NE = VT.getVectorNumElements();
7553   EVT EltVT = VT.getVectorElementType();
7554   SDLoc dl(N);
7555
7556   SmallVector<SDValue, 8> Scalars;
7557   SmallVector<SDValue, 4> Operands(N->getNumOperands());
7558
7559   // If ResNE is 0, fully unroll the vector op.
7560   if (ResNE == 0)
7561     ResNE = NE;
7562   else if (NE > ResNE)
7563     NE = ResNE;
7564
7565   unsigned i;
7566   for (i= 0; i != NE; ++i) {
7567     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
7568       SDValue Operand = N->getOperand(j);
7569       EVT OperandVT = Operand.getValueType();
7570       if (OperandVT.isVector()) {
7571         // A vector operand; extract a single element.
7572         EVT OperandEltVT = OperandVT.getVectorElementType();
7573         Operands[j] =
7574             getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand,
7575                     getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout())));
7576       } else {
7577         // A scalar operand; just use it as is.
7578         Operands[j] = Operand;
7579       }
7580     }
7581
7582     switch (N->getOpcode()) {
7583     default: {
7584       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
7585                                 N->getFlags()));
7586       break;
7587     }
7588     case ISD::VSELECT:
7589       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
7590       break;
7591     case ISD::SHL:
7592     case ISD::SRA:
7593     case ISD::SRL:
7594     case ISD::ROTL:
7595     case ISD::ROTR:
7596       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
7597                                getShiftAmountOperand(Operands[0].getValueType(),
7598                                                      Operands[1])));
7599       break;
7600     case ISD::SIGN_EXTEND_INREG:
7601     case ISD::FP_ROUND_INREG: {
7602       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
7603       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
7604                                 Operands[0],
7605                                 getValueType(ExtVT)));
7606     }
7607     }
7608   }
7609
7610   for (; i < ResNE; ++i)
7611     Scalars.push_back(getUNDEF(EltVT));
7612
7613   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
7614   return getBuildVector(VecVT, dl, Scalars);
7615 }
7616
7617 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
7618                                                   LoadSDNode *Base,
7619                                                   unsigned Bytes,
7620                                                   int Dist) const {
7621   if (LD->isVolatile() || Base->isVolatile())
7622     return false;
7623   if (LD->isIndexed() || Base->isIndexed())
7624     return false;
7625   if (LD->getChain() != Base->getChain())
7626     return false;
7627   EVT VT = LD->getValueType(0);
7628   if (VT.getSizeInBits() / 8 != Bytes)
7629     return false;
7630
7631   SDValue Loc = LD->getOperand(1);
7632   SDValue BaseLoc = Base->getOperand(1);
7633   if (Loc.getOpcode() == ISD::FrameIndex) {
7634     if (BaseLoc.getOpcode() != ISD::FrameIndex)
7635       return false;
7636     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
7637     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
7638     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7639     int FS  = MFI.getObjectSize(FI);
7640     int BFS = MFI.getObjectSize(BFI);
7641     if (FS != BFS || FS != (int)Bytes) return false;
7642     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
7643   }
7644
7645   // Handle X + C.
7646   if (isBaseWithConstantOffset(Loc)) {
7647     int64_t LocOffset = cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
7648     if (Loc.getOperand(0) == BaseLoc) {
7649       // If the base location is a simple address with no offset itself, then
7650       // the second load's first add operand should be the base address.
7651       if (LocOffset == Dist * (int)Bytes)
7652         return true;
7653     } else if (isBaseWithConstantOffset(BaseLoc)) {
7654       // The base location itself has an offset, so subtract that value from the
7655       // second load's offset before comparing to distance * size.
7656       int64_t BOffset =
7657         cast<ConstantSDNode>(BaseLoc.getOperand(1))->getSExtValue();
7658       if (Loc.getOperand(0) == BaseLoc.getOperand(0)) {
7659         if ((LocOffset - BOffset) == Dist * (int)Bytes)
7660           return true;
7661       }
7662     }
7663   }
7664   const GlobalValue *GV1 = nullptr;
7665   const GlobalValue *GV2 = nullptr;
7666   int64_t Offset1 = 0;
7667   int64_t Offset2 = 0;
7668   bool isGA1 = TLI->isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7669   bool isGA2 = TLI->isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7670   if (isGA1 && isGA2 && GV1 == GV2)
7671     return Offset1 == (Offset2 + Dist*Bytes);
7672   return false;
7673 }
7674
7675 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
7676 /// it cannot be inferred.
7677 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
7678   // If this is a GlobalAddress + cst, return the alignment.
7679   const GlobalValue *GV;
7680   int64_t GVOffset = 0;
7681   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
7682     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
7683     KnownBits Known(PtrWidth);
7684     llvm::computeKnownBits(GV, Known, getDataLayout());
7685     unsigned AlignBits = Known.countMinTrailingZeros();
7686     unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
7687     if (Align)
7688       return MinAlign(Align, GVOffset);
7689   }
7690
7691   // If this is a direct reference to a stack slot, use information about the
7692   // stack slot's alignment.
7693   int FrameIdx = 1 << 31;
7694   int64_t FrameOffset = 0;
7695   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
7696     FrameIdx = FI->getIndex();
7697   } else if (isBaseWithConstantOffset(Ptr) &&
7698              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
7699     // Handle FI+Cst
7700     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7701     FrameOffset = Ptr.getConstantOperandVal(1);
7702   }
7703
7704   if (FrameIdx != (1 << 31)) {
7705     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
7706     unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
7707                                     FrameOffset);
7708     return FIInfoAlign;
7709   }
7710
7711   return 0;
7712 }
7713
7714 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
7715 /// which is split (or expanded) into two not necessarily identical pieces.
7716 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
7717   // Currently all types are split in half.
7718   EVT LoVT, HiVT;
7719   if (!VT.isVector())
7720     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
7721   else
7722     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
7723
7724   return std::make_pair(LoVT, HiVT);
7725 }
7726
7727 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
7728 /// low/high part.
7729 std::pair<SDValue, SDValue>
7730 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
7731                           const EVT &HiVT) {
7732   assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
7733          N.getValueType().getVectorNumElements() &&
7734          "More vector elements requested than available!");
7735   SDValue Lo, Hi;
7736   Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
7737                getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
7738   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
7739                getConstant(LoVT.getVectorNumElements(), DL,
7740                            TLI->getVectorIdxTy(getDataLayout())));
7741   return std::make_pair(Lo, Hi);
7742 }
7743
7744 void SelectionDAG::ExtractVectorElements(SDValue Op,
7745                                          SmallVectorImpl<SDValue> &Args,
7746                                          unsigned Start, unsigned Count) {
7747   EVT VT = Op.getValueType();
7748   if (Count == 0)
7749     Count = VT.getVectorNumElements();
7750
7751   EVT EltVT = VT.getVectorElementType();
7752   EVT IdxTy = TLI->getVectorIdxTy(getDataLayout());
7753   SDLoc SL(Op);
7754   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
7755     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7756                            Op, getConstant(i, SL, IdxTy)));
7757   }
7758 }
7759
7760 // getAddressSpace - Return the address space this GlobalAddress belongs to.
7761 unsigned GlobalAddressSDNode::getAddressSpace() const {
7762   return getGlobal()->getType()->getAddressSpace();
7763 }
7764
7765 Type *ConstantPoolSDNode::getType() const {
7766   if (isMachineConstantPoolEntry())
7767     return Val.MachineCPVal->getType();
7768   return Val.ConstVal->getType();
7769 }
7770
7771 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
7772                                         unsigned &SplatBitSize,
7773                                         bool &HasAnyUndefs,
7774                                         unsigned MinSplatBits,
7775                                         bool IsBigEndian) const {
7776   EVT VT = getValueType(0);
7777   assert(VT.isVector() && "Expected a vector type");
7778   unsigned VecWidth = VT.getSizeInBits();
7779   if (MinSplatBits > VecWidth)
7780     return false;
7781
7782   // FIXME: The widths are based on this node's type, but build vectors can
7783   // truncate their operands.
7784   SplatValue = APInt(VecWidth, 0);
7785   SplatUndef = APInt(VecWidth, 0);
7786
7787   // Get the bits. Bits with undefined values (when the corresponding element
7788   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
7789   // in SplatValue. If any of the values are not constant, give up and return
7790   // false.
7791   unsigned int NumOps = getNumOperands();
7792   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
7793   unsigned EltWidth = VT.getScalarSizeInBits();
7794
7795   for (unsigned j = 0; j < NumOps; ++j) {
7796     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
7797     SDValue OpVal = getOperand(i);
7798     unsigned BitPos = j * EltWidth;
7799
7800     if (OpVal.isUndef())
7801       SplatUndef.setBits(BitPos, BitPos + EltWidth);
7802     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
7803       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
7804     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
7805       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
7806     else
7807       return false;
7808   }
7809
7810   // The build_vector is all constants or undefs. Find the smallest element
7811   // size that splats the vector.
7812   HasAnyUndefs = (SplatUndef != 0);
7813
7814   // FIXME: This does not work for vectors with elements less than 8 bits.
7815   while (VecWidth > 8) {
7816     unsigned HalfSize = VecWidth / 2;
7817     APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
7818     APInt LowValue = SplatValue.trunc(HalfSize);
7819     APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
7820     APInt LowUndef = SplatUndef.trunc(HalfSize);
7821
7822     // If the two halves do not match (ignoring undef bits), stop here.
7823     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
7824         MinSplatBits > HalfSize)
7825       break;
7826
7827     SplatValue = HighValue | LowValue;
7828     SplatUndef = HighUndef & LowUndef;
7829
7830     VecWidth = HalfSize;
7831   }
7832
7833   SplatBitSize = VecWidth;
7834   return true;
7835 }
7836
7837 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
7838   if (UndefElements) {
7839     UndefElements->clear();
7840     UndefElements->resize(getNumOperands());
7841   }
7842   SDValue Splatted;
7843   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
7844     SDValue Op = getOperand(i);
7845     if (Op.isUndef()) {
7846       if (UndefElements)
7847         (*UndefElements)[i] = true;
7848     } else if (!Splatted) {
7849       Splatted = Op;
7850     } else if (Splatted != Op) {
7851       return SDValue();
7852     }
7853   }
7854
7855   if (!Splatted) {
7856     assert(getOperand(0).isUndef() &&
7857            "Can only have a splat without a constant for all undefs.");
7858     return getOperand(0);
7859   }
7860
7861   return Splatted;
7862 }
7863
7864 ConstantSDNode *
7865 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
7866   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
7867 }
7868
7869 ConstantFPSDNode *
7870 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
7871   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
7872 }
7873
7874 int32_t
7875 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
7876                                                    uint32_t BitWidth) const {
7877   if (ConstantFPSDNode *CN =
7878           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
7879     bool IsExact;
7880     APSInt IntVal(BitWidth);
7881     const APFloat &APF = CN->getValueAPF();
7882     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
7883             APFloat::opOK ||
7884         !IsExact)
7885       return -1;
7886
7887     return IntVal.exactLogBase2();
7888   }
7889   return -1;
7890 }
7891
7892 bool BuildVectorSDNode::isConstant() const {
7893   for (const SDValue &Op : op_values()) {
7894     unsigned Opc = Op.getOpcode();
7895     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
7896       return false;
7897   }
7898   return true;
7899 }
7900
7901 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
7902   // Find the first non-undef value in the shuffle mask.
7903   unsigned i, e;
7904   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
7905     /* search */;
7906
7907   assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
7908
7909   // Make sure all remaining elements are either undef or the same as the first
7910   // non-undef value.
7911   for (int Idx = Mask[i]; i != e; ++i)
7912     if (Mask[i] >= 0 && Mask[i] != Idx)
7913       return false;
7914   return true;
7915 }
7916
7917 // \brief Returns the SDNode if it is a constant integer BuildVector
7918 // or constant integer.
7919 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
7920   if (isa<ConstantSDNode>(N))
7921     return N.getNode();
7922   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
7923     return N.getNode();
7924   // Treat a GlobalAddress supporting constant offset folding as a
7925   // constant integer.
7926   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
7927     if (GA->getOpcode() == ISD::GlobalAddress &&
7928         TLI->isOffsetFoldingLegal(GA))
7929       return GA;
7930   return nullptr;
7931 }
7932
7933 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) {
7934   if (isa<ConstantFPSDNode>(N))
7935     return N.getNode();
7936
7937   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
7938     return N.getNode();
7939
7940   return nullptr;
7941 }
7942
7943 #ifndef NDEBUG
7944 static void checkForCyclesHelper(const SDNode *N,
7945                                  SmallPtrSetImpl<const SDNode*> &Visited,
7946                                  SmallPtrSetImpl<const SDNode*> &Checked,
7947                                  const llvm::SelectionDAG *DAG) {
7948   // If this node has already been checked, don't check it again.
7949   if (Checked.count(N))
7950     return;
7951
7952   // If a node has already been visited on this depth-first walk, reject it as
7953   // a cycle.
7954   if (!Visited.insert(N).second) {
7955     errs() << "Detected cycle in SelectionDAG\n";
7956     dbgs() << "Offending node:\n";
7957     N->dumprFull(DAG); dbgs() << "\n";
7958     abort();
7959   }
7960
7961   for (const SDValue &Op : N->op_values())
7962     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
7963
7964   Checked.insert(N);
7965   Visited.erase(N);
7966 }
7967 #endif
7968
7969 void llvm::checkForCycles(const llvm::SDNode *N,
7970                           const llvm::SelectionDAG *DAG,
7971                           bool force) {
7972 #ifndef NDEBUG
7973   bool check = force;
7974 #ifdef EXPENSIVE_CHECKS
7975   check = true;
7976 #endif  // EXPENSIVE_CHECKS
7977   if (check) {
7978     assert(N && "Checking nonexistent SDNode");
7979     SmallPtrSet<const SDNode*, 32> visited;
7980     SmallPtrSet<const SDNode*, 32> checked;
7981     checkForCyclesHelper(N, visited, checked, DAG);
7982   }
7983 #endif  // !NDEBUG
7984 }
7985
7986 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
7987   checkForCycles(DAG->getRoot().getNode(), DAG, force);
7988 }