LLVM  10.0.0svn
SelectionDAG.cpp
Go to the documentation of this file.
1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements the SelectionDAG class.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/APSInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
42 #include "llvm/IR/Constant.h"
43 #include "llvm/IR/Constants.h"
44 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/DebugLoc.h"
47 #include "llvm/IR/DerivedTypes.h"
48 #include "llvm/IR/Function.h"
49 #include "llvm/IR/GlobalValue.h"
50 #include "llvm/IR/Metadata.h"
51 #include "llvm/IR/Type.h"
52 #include "llvm/IR/Value.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/CodeGen.h"
55 #include "llvm/Support/Compiler.h"
56 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/KnownBits.h"
62 #include "llvm/Support/Mutex.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.
89 
90 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
91 
92 #define DEBUG_TYPE "selectiondag"
93 
94 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
95  cl::Hidden, cl::init(true),
96  cl::desc("Gang up loads and stores generated by inlining of memcpy"));
97 
98 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
99  cl::desc("Number limit for gluing ld/st of memcpy."),
100  cl::Hidden, cl::init(0));
101 
103  LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
104 }
105 
106 //===----------------------------------------------------------------------===//
107 // ConstantFPSDNode Class
108 //===----------------------------------------------------------------------===//
109 
110 /// isExactlyValue - We don't rely on operator== working on double values, as
111 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
112 /// As such, this method can be used to do an exact bit-for-bit comparison of
113 /// two floating point values.
115  return getValueAPF().bitwiseIsEqual(V);
116 }
117 
119  const APFloat& Val) {
120  assert(VT.isFloatingPoint() && "Can only convert between FP types");
121 
122  // convert modifies in place, so make a copy.
123  APFloat Val2 = APFloat(Val);
124  bool losesInfo;
125  (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
127  &losesInfo);
128  return !losesInfo;
129 }
130 
131 //===----------------------------------------------------------------------===//
132 // ISD Namespace
133 //===----------------------------------------------------------------------===//
134 
135 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
136  auto *BV = dyn_cast<BuildVectorSDNode>(N);
137  if (!BV)
138  return false;
139 
140  APInt SplatUndef;
141  unsigned SplatBitSize;
142  bool HasUndefs;
143  unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
144  return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
145  EltSize) &&
146  EltSize == SplatBitSize;
147 }
148 
149 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
150 // specializations of the more general isConstantSplatVector()?
151 
153  // Look through a bit convert.
154  while (N->getOpcode() == ISD::BITCAST)
155  N = N->getOperand(0).getNode();
156 
157  if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
158 
159  unsigned i = 0, e = N->getNumOperands();
160 
161  // Skip over all of the undef values.
162  while (i != e && N->getOperand(i).isUndef())
163  ++i;
164 
165  // Do not accept an all-undef vector.
166  if (i == e) return false;
167 
168  // Do not accept build_vectors that aren't all constants or which have non-~0
169  // elements. We have to be a bit careful here, as the type of the constant
170  // may not be the same as the type of the vector elements due to type
171  // legalization (the elements are promoted to a legal type for the target and
172  // a vector of a type may be legal when the base element type is not).
173  // We only want to check enough bits to cover the vector elements, because
174  // we care if the resultant vector is all ones, not whether the individual
175  // constants are.
176  SDValue NotZero = N->getOperand(i);
177  unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
178  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
179  if (CN->getAPIntValue().countTrailingOnes() < EltSize)
180  return false;
181  } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
182  if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
183  return false;
184  } else
185  return false;
186 
187  // Okay, we have at least one ~0 value, check to see if the rest match or are
188  // undefs. Even with the above element type twiddling, this should be OK, as
189  // the same type legalization should have applied to all the elements.
190  for (++i; i != e; ++i)
191  if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
192  return false;
193  return true;
194 }
195 
197  // Look through a bit convert.
198  while (N->getOpcode() == ISD::BITCAST)
199  N = N->getOperand(0).getNode();
200 
201  if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
202 
203  bool IsAllUndef = true;
204  for (const SDValue &Op : N->op_values()) {
205  if (Op.isUndef())
206  continue;
207  IsAllUndef = false;
208  // Do not accept build_vectors that aren't all constants or which have non-0
209  // elements. We have to be a bit careful here, as the type of the constant
210  // may not be the same as the type of the vector elements due to type
211  // legalization (the elements are promoted to a legal type for the target
212  // and a vector of a type may be legal when the base element type is not).
213  // We only want to check enough bits to cover the vector elements, because
214  // we care if the resultant vector is all zeros, not whether the individual
215  // constants are.
216  unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
217  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
218  if (CN->getAPIntValue().countTrailingZeros() < EltSize)
219  return false;
220  } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
221  if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
222  return false;
223  } else
224  return false;
225  }
226 
227  // Do not accept an all-undef vector.
228  if (IsAllUndef)
229  return false;
230  return true;
231 }
232 
234  if (N->getOpcode() != ISD::BUILD_VECTOR)
235  return false;
236 
237  for (const SDValue &Op : N->op_values()) {
238  if (Op.isUndef())
239  continue;
240  if (!isa<ConstantSDNode>(Op))
241  return false;
242  }
243  return true;
244 }
245 
247  if (N->getOpcode() != ISD::BUILD_VECTOR)
248  return false;
249 
250  for (const SDValue &Op : N->op_values()) {
251  if (Op.isUndef())
252  continue;
253  if (!isa<ConstantFPSDNode>(Op))
254  return false;
255  }
256  return true;
257 }
258 
260  // Return false if the node has no operands.
261  // This is "logically inconsistent" with the definition of "all" but
262  // is probably the desired behavior.
263  if (N->getNumOperands() == 0)
264  return false;
265  return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
266 }
267 
270  bool AllowUndefs) {
271  // FIXME: Add support for scalar UNDEF cases?
272  if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
273  return Match(Cst);
274 
275  // FIXME: Add support for vector UNDEF cases?
276  if (ISD::BUILD_VECTOR != Op.getOpcode())
277  return false;
278 
279  EVT SVT = Op.getValueType().getScalarType();
280  for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
281  if (AllowUndefs && Op.getOperand(i).isUndef()) {
282  if (!Match(nullptr))
283  return false;
284  continue;
285  }
286 
287  auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
288  if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
289  return false;
290  }
291  return true;
292 }
293 
295  SDValue LHS, SDValue RHS,
297  bool AllowUndefs, bool AllowTypeMismatch) {
298  if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
299  return false;
300 
301  // TODO: Add support for scalar UNDEF cases?
302  if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
303  if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
304  return Match(LHSCst, RHSCst);
305 
306  // TODO: Add support for vector UNDEF cases?
307  if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
308  ISD::BUILD_VECTOR != RHS.getOpcode())
309  return false;
310 
311  EVT SVT = LHS.getValueType().getScalarType();
312  for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
313  SDValue LHSOp = LHS.getOperand(i);
314  SDValue RHSOp = RHS.getOperand(i);
315  bool LHSUndef = AllowUndefs && LHSOp.isUndef();
316  bool RHSUndef = AllowUndefs && RHSOp.isUndef();
317  auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
318  auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
319  if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
320  return false;
321  if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
322  LHSOp.getValueType() != RHSOp.getValueType()))
323  return false;
324  if (!Match(LHSCst, RHSCst))
325  return false;
326  }
327  return true;
328 }
329 
331  switch (ExtType) {
332  case ISD::EXTLOAD:
333  return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
334  case ISD::SEXTLOAD:
335  return ISD::SIGN_EXTEND;
336  case ISD::ZEXTLOAD:
337  return ISD::ZERO_EXTEND;
338  default:
339  break;
340  }
341 
342  llvm_unreachable("Invalid LoadExtType");
343 }
344 
346  // To perform this operation, we just need to swap the L and G bits of the
347  // operation.
348  unsigned OldL = (Operation >> 2) & 1;
349  unsigned OldG = (Operation >> 1) & 1;
350  return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
351  (OldL << 1) | // New G bit
352  (OldG << 2)); // New L bit.
353 }
354 
356  unsigned Operation = Op;
357  if (isInteger)
358  Operation ^= 7; // Flip L, G, E bits, but not U.
359  else
360  Operation ^= 15; // Flip all of the condition bits.
361 
362  if (Operation > ISD::SETTRUE2)
363  Operation &= ~8; // Don't let N and U bits get set.
364 
365  return ISD::CondCode(Operation);
366 }
367 
368 /// For an integer comparison, return 1 if the comparison is a signed operation
369 /// and 2 if the result is an unsigned comparison. Return zero if the operation
370 /// does not depend on the sign of the input (setne and seteq).
371 static int isSignedOp(ISD::CondCode Opcode) {
372  switch (Opcode) {
373  default: llvm_unreachable("Illegal integer setcc operation!");
374  case ISD::SETEQ:
375  case ISD::SETNE: return 0;
376  case ISD::SETLT:
377  case ISD::SETLE:
378  case ISD::SETGT:
379  case ISD::SETGE: return 1;
380  case ISD::SETULT:
381  case ISD::SETULE:
382  case ISD::SETUGT:
383  case ISD::SETUGE: return 2;
384  }
385 }
386 
388  bool IsInteger) {
389  if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
390  // Cannot fold a signed integer setcc with an unsigned integer setcc.
391  return ISD::SETCC_INVALID;
392 
393  unsigned Op = Op1 | Op2; // Combine all of the condition bits.
394 
395  // If the N and U bits get set, then the resultant comparison DOES suddenly
396  // care about orderedness, and it is true when ordered.
397  if (Op > ISD::SETTRUE2)
398  Op &= ~16; // Clear the U bit if the N bit is set.
399 
400  // Canonicalize illegal integer setcc's.
401  if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
402  Op = ISD::SETNE;
403 
404  return ISD::CondCode(Op);
405 }
406 
408  bool IsInteger) {
409  if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
410  // Cannot fold a signed setcc with an unsigned setcc.
411  return ISD::SETCC_INVALID;
412 
413  // Combine all of the condition bits.
414  ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
415 
416  // Canonicalize illegal integer setcc's.
417  if (IsInteger) {
418  switch (Result) {
419  default: break;
420  case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
421  case ISD::SETOEQ: // SETEQ & SETU[LG]E
422  case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
423  case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
424  case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
425  }
426  }
427 
428  return Result;
429 }
430 
431 //===----------------------------------------------------------------------===//
432 // SDNode Profile Support
433 //===----------------------------------------------------------------------===//
434 
435 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
436 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
437  ID.AddInteger(OpC);
438 }
439 
440 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
441 /// solely with their pointer.
443  ID.AddPointer(VTList.VTs);
444 }
445 
446 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
448  ArrayRef<SDValue> Ops) {
449  for (auto& Op : Ops) {
450  ID.AddPointer(Op.getNode());
451  ID.AddInteger(Op.getResNo());
452  }
453 }
454 
455 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
457  ArrayRef<SDUse> Ops) {
458  for (auto& Op : Ops) {
459  ID.AddPointer(Op.getNode());
460  ID.AddInteger(Op.getResNo());
461  }
462 }
463 
464 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
465  SDVTList VTList, ArrayRef<SDValue> OpList) {
466  AddNodeIDOpcode(ID, OpC);
467  AddNodeIDValueTypes(ID, VTList);
468  AddNodeIDOperands(ID, OpList);
469 }
470 
471 /// If this is an SDNode with special info, add this info to the NodeID data.
472 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
473  switch (N->getOpcode()) {
475  case ISD::ExternalSymbol:
476  case ISD::MCSymbol:
477  llvm_unreachable("Should only be used on nodes with operands");
478  default: break; // Normal nodes don't need extra info.
479  case ISD::TargetConstant:
480  case ISD::Constant: {
481  const ConstantSDNode *C = cast<ConstantSDNode>(N);
483  ID.AddBoolean(C->isOpaque());
484  break;
485  }
487  case ISD::ConstantFP:
488  ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
489  break;
491  case ISD::GlobalAddress:
493  case ISD::GlobalTLSAddress: {
494  const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
495  ID.AddPointer(GA->getGlobal());
496  ID.AddInteger(GA->getOffset());
497  ID.AddInteger(GA->getTargetFlags());
498  break;
499  }
500  case ISD::BasicBlock:
501  ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
502  break;
503  case ISD::Register:
504  ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
505  break;
506  case ISD::RegisterMask:
507  ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
508  break;
509  case ISD::SRCVALUE:
510  ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
511  break;
512  case ISD::FrameIndex:
514  ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
515  break;
516  case ISD::LIFETIME_START:
517  case ISD::LIFETIME_END:
518  if (cast<LifetimeSDNode>(N)->hasOffset()) {
519  ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
520  ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
521  }
522  break;
523  case ISD::JumpTable:
525  ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
526  ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
527  break;
528  case ISD::ConstantPool:
530  const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
531  ID.AddInteger(CP->getAlignment());
532  ID.AddInteger(CP->getOffset());
533  if (CP->isMachineConstantPoolEntry())
535  else
536  ID.AddPointer(CP->getConstVal());
537  ID.AddInteger(CP->getTargetFlags());
538  break;
539  }
540  case ISD::TargetIndex: {
541  const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
542  ID.AddInteger(TI->getIndex());
543  ID.AddInteger(TI->getOffset());
544  ID.AddInteger(TI->getTargetFlags());
545  break;
546  }
547  case ISD::LOAD: {
548  const LoadSDNode *LD = cast<LoadSDNode>(N);
549  ID.AddInteger(LD->getMemoryVT().getRawBits());
550  ID.AddInteger(LD->getRawSubclassData());
552  break;
553  }
554  case ISD::STORE: {
555  const StoreSDNode *ST = cast<StoreSDNode>(N);
556  ID.AddInteger(ST->getMemoryVT().getRawBits());
557  ID.AddInteger(ST->getRawSubclassData());
559  break;
560  }
561  case ISD::MLOAD: {
562  const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
563  ID.AddInteger(MLD->getMemoryVT().getRawBits());
564  ID.AddInteger(MLD->getRawSubclassData());
566  break;
567  }
568  case ISD::MSTORE: {
569  const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
570  ID.AddInteger(MST->getMemoryVT().getRawBits());
571  ID.AddInteger(MST->getRawSubclassData());
573  break;
574  }
575  case ISD::MGATHER: {
576  const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
577  ID.AddInteger(MG->getMemoryVT().getRawBits());
578  ID.AddInteger(MG->getRawSubclassData());
580  break;
581  }
582  case ISD::MSCATTER: {
583  const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
584  ID.AddInteger(MS->getMemoryVT().getRawBits());
585  ID.AddInteger(MS->getRawSubclassData());
587  break;
588  }
591  case ISD::ATOMIC_SWAP:
596  case ISD::ATOMIC_LOAD_OR:
603  case ISD::ATOMIC_LOAD:
604  case ISD::ATOMIC_STORE: {
605  const AtomicSDNode *AT = cast<AtomicSDNode>(N);
606  ID.AddInteger(AT->getMemoryVT().getRawBits());
607  ID.AddInteger(AT->getRawSubclassData());
609  break;
610  }
611  case ISD::PREFETCH: {
612  const MemSDNode *PF = cast<MemSDNode>(N);
614  break;
615  }
616  case ISD::VECTOR_SHUFFLE: {
617  const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
618  for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
619  i != e; ++i)
620  ID.AddInteger(SVN->getMaskElt(i));
621  break;
622  }
624  case ISD::BlockAddress: {
625  const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
626  ID.AddPointer(BA->getBlockAddress());
627  ID.AddInteger(BA->getOffset());
628  ID.AddInteger(BA->getTargetFlags());
629  break;
630  }
631  } // end switch (N->getOpcode())
632 
633  // Target specific memory nodes could also have address spaces to check.
634  if (N->isTargetMemoryOpcode())
635  ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
636 }
637 
638 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
639 /// data.
640 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
641  AddNodeIDOpcode(ID, N->getOpcode());
642  // Add the return value info.
643  AddNodeIDValueTypes(ID, N->getVTList());
644  // Add the operand info.
645  AddNodeIDOperands(ID, N->ops());
646 
647  // Handle SDNode leafs with special info.
648  AddNodeIDCustom(ID, N);
649 }
650 
651 //===----------------------------------------------------------------------===//
652 // SelectionDAG Class
653 //===----------------------------------------------------------------------===//
654 
655 /// doNotCSE - Return true if CSE should not be performed for this node.
656 static bool doNotCSE(SDNode *N) {
657  if (N->getValueType(0) == MVT::Glue)
658  return true; // Never CSE anything that produces a flag.
659 
660  switch (N->getOpcode()) {
661  default: break;
662  case ISD::HANDLENODE:
663  case ISD::EH_LABEL:
664  return true; // Never CSE these nodes.
665  }
666 
667  // Check that remaining values produced are not flags.
668  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
669  if (N->getValueType(i) == MVT::Glue)
670  return true; // Never CSE anything that produces a flag.
671 
672  return false;
673 }
674 
675 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
676 /// SelectionDAG.
678  // Create a dummy node (which is not added to allnodes), that adds a reference
679  // to the root node, preventing it from being deleted.
681 
682  SmallVector<SDNode*, 128> DeadNodes;
683 
684  // Add all obviously-dead nodes to the DeadNodes worklist.
685  for (SDNode &Node : allnodes())
686  if (Node.use_empty())
687  DeadNodes.push_back(&Node);
688 
689  RemoveDeadNodes(DeadNodes);
690 
691  // If the root changed (e.g. it was a dead load, update the root).
692  setRoot(Dummy.getValue());
693 }
694 
695 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
696 /// given list, and any nodes that become unreachable as a result.
698 
699  // Process the worklist, deleting the nodes and adding their uses to the
700  // worklist.
701  while (!DeadNodes.empty()) {
702  SDNode *N = DeadNodes.pop_back_val();
703  // Skip to next node if we've already managed to delete the node. This could
704  // happen if replacing a node causes a node previously added to the node to
705  // be deleted.
706  if (N->getOpcode() == ISD::DELETED_NODE)
707  continue;
708 
709  for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
710  DUL->NodeDeleted(N, nullptr);
711 
712  // Take the node out of the appropriate CSE map.
713  RemoveNodeFromCSEMaps(N);
714 
715  // Next, brutally remove the operand list. This is safe to do, as there are
716  // no cycles in the graph.
717  for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
718  SDUse &Use = *I++;
719  SDNode *Operand = Use.getNode();
720  Use.set(SDValue());
721 
722  // Now that we removed this operand, see if there are no uses of it left.
723  if (Operand->use_empty())
724  DeadNodes.push_back(Operand);
725  }
726 
727  DeallocateNode(N);
728  }
729 }
730 
732  SmallVector<SDNode*, 16> DeadNodes(1, N);
733 
734  // Create a dummy node that adds a reference to the root node, preventing
735  // it from being deleted. (This matters if the root is an operand of the
736  // dead node.)
738 
739  RemoveDeadNodes(DeadNodes);
740 }
741 
743  // First take this out of the appropriate CSE map.
744  RemoveNodeFromCSEMaps(N);
745 
746  // Finally, remove uses due to operands of this node, remove from the
747  // AllNodes list, and delete the node.
748  DeleteNodeNotInCSEMaps(N);
749 }
750 
751 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
752  assert(N->getIterator() != AllNodes.begin() &&
753  "Cannot delete the entry node!");
754  assert(N->use_empty() && "Cannot delete a node that is not dead!");
755 
756  // Drop all of the operands and decrement used node's use counts.
757  N->DropOperands();
758 
759  DeallocateNode(N);
760 }
761 
762 void SDDbgInfo::erase(const SDNode *Node) {
763  DbgValMapType::iterator I = DbgValMap.find(Node);
764  if (I == DbgValMap.end())
765  return;
766  for (auto &Val: I->second)
767  Val->setIsInvalidated();
768  DbgValMap.erase(I);
769 }
770 
771 void SelectionDAG::DeallocateNode(SDNode *N) {
772  // If we have operands, deallocate them.
773  removeOperands(N);
774 
775  NodeAllocator.Deallocate(AllNodes.remove(N));
776 
777  // Set the opcode to DELETED_NODE to help catch bugs when node
778  // memory is reallocated.
779  // FIXME: There are places in SDag that have grown a dependency on the opcode
780  // value in the released node.
781  __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
782  N->NodeType = ISD::DELETED_NODE;
783 
784  // If any of the SDDbgValue nodes refer to this SDNode, invalidate
785  // them and forget about that node.
786  DbgInfo->erase(N);
787 }
788 
789 #ifndef NDEBUG
790 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
791 static void VerifySDNode(SDNode *N) {
792  switch (N->getOpcode()) {
793  default:
794  break;
795  case ISD::BUILD_PAIR: {
796  EVT VT = N->getValueType(0);
797  assert(N->getNumValues() == 1 && "Too many results!");
798  assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
799  "Wrong return type!");
800  assert(N->getNumOperands() == 2 && "Wrong number of operands!");
802  "Mismatched operand types!");
803  assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
804  "Wrong operand type!");
805  assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
806  "Wrong return type size");
807  break;
808  }
809  case ISD::BUILD_VECTOR: {
810  assert(N->getNumValues() == 1 && "Too many results!");
811  assert(N->getValueType(0).isVector() && "Wrong return type!");
813  "Wrong number of operands!");
814  EVT EltVT = N->getValueType(0).getVectorElementType();
815  for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
816  assert((I->getValueType() == EltVT ||
817  (EltVT.isInteger() && I->getValueType().isInteger() &&
818  EltVT.bitsLE(I->getValueType()))) &&
819  "Wrong operand type!");
820  assert(I->getValueType() == N->getOperand(0).getValueType() &&
821  "Operands must all have the same type");
822  }
823  break;
824  }
825  }
826 }
827 #endif // NDEBUG
828 
829 /// Insert a newly allocated node into the DAG.
830 ///
831 /// Handles insertion into the all nodes list and CSE map, as well as
832 /// verification and other common operations when a new node is allocated.
833 void SelectionDAG::InsertNode(SDNode *N) {
834  AllNodes.push_back(N);
835 #ifndef NDEBUG
836  N->PersistentId = NextPersistentId++;
837  VerifySDNode(N);
838 #endif
839  for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
840  DUL->NodeInserted(N);
841 }
842 
843 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
844 /// correspond to it. This is useful when we're about to delete or repurpose
845 /// the node. We don't want future request for structurally identical nodes
846 /// to return N anymore.
847 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
848  bool Erased = false;
849  switch (N->getOpcode()) {
850  case ISD::HANDLENODE: return false; // noop.
851  case ISD::CONDCODE:
852  assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
853  "Cond code doesn't exist!");
854  Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
855  CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
856  break;
857  case ISD::ExternalSymbol:
858  Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
859  break;
861  ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
862  Erased = TargetExternalSymbols.erase(
863  std::pair<std::string,unsigned char>(ESN->getSymbol(),
864  ESN->getTargetFlags()));
865  break;
866  }
867  case ISD::MCSymbol: {
868  auto *MCSN = cast<MCSymbolSDNode>(N);
869  Erased = MCSymbols.erase(MCSN->getMCSymbol());
870  break;
871  }
872  case ISD::VALUETYPE: {
873  EVT VT = cast<VTSDNode>(N)->getVT();
874  if (VT.isExtended()) {
875  Erased = ExtendedValueTypeNodes.erase(VT);
876  } else {
877  Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
878  ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
879  }
880  break;
881  }
882  default:
883  // Remove it from the CSE Map.
884  assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
885  assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
886  Erased = CSEMap.RemoveNode(N);
887  break;
888  }
889 #ifndef NDEBUG
890  // Verify that the node was actually in one of the CSE maps, unless it has a
891  // flag result (which cannot be CSE'd) or is one of the special cases that are
892  // not subject to CSE.
893  if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
894  !N->isMachineOpcode() && !doNotCSE(N)) {
895  N->dump(this);
896  dbgs() << "\n";
897  llvm_unreachable("Node is not in map!");
898  }
899 #endif
900  return Erased;
901 }
902 
903 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
904 /// maps and modified in place. Add it back to the CSE maps, unless an identical
905 /// node already exists, in which case transfer all its users to the existing
906 /// node. This transfer can potentially trigger recursive merging.
907 void
908 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
909  // For node types that aren't CSE'd, just act as if no identical node
910  // already exists.
911  if (!doNotCSE(N)) {
912  SDNode *Existing = CSEMap.GetOrInsertNode(N);
913  if (Existing != N) {
914  // If there was already an existing matching node, use ReplaceAllUsesWith
915  // to replace the dead one with the existing one. This can cause
916  // recursive merging of other unrelated nodes down the line.
917  ReplaceAllUsesWith(N, Existing);
918 
919  // N is now dead. Inform the listeners and delete it.
920  for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
921  DUL->NodeDeleted(N, Existing);
922  DeleteNodeNotInCSEMaps(N);
923  return;
924  }
925  }
926 
927  // If the node doesn't already exist, we updated it. Inform listeners.
928  for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
929  DUL->NodeUpdated(N);
930 }
931 
932 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
933 /// were replaced with those specified. If this node is never memoized,
934 /// return null, otherwise return a pointer to the slot it would take. If a
935 /// node already exists with these operands, the slot will be non-null.
936 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
937  void *&InsertPos) {
938  if (doNotCSE(N))
939  return nullptr;
940 
941  SDValue Ops[] = { Op };
943  AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
944  AddNodeIDCustom(ID, N);
945  SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
946  if (Node)
947  Node->intersectFlagsWith(N->getFlags());
948  return Node;
949 }
950 
951 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
952 /// were replaced with those specified. If this node is never memoized,
953 /// return null, otherwise return a pointer to the slot it would take. If a
954 /// node already exists with these operands, the slot will be non-null.
955 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
956  SDValue Op1, SDValue Op2,
957  void *&InsertPos) {
958  if (doNotCSE(N))
959  return nullptr;
960 
961  SDValue Ops[] = { Op1, Op2 };
963  AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
964  AddNodeIDCustom(ID, N);
965  SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
966  if (Node)
967  Node->intersectFlagsWith(N->getFlags());
968  return Node;
969 }
970 
971 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
972 /// were replaced with those specified. If this node is never memoized,
973 /// return null, otherwise return a pointer to the slot it would take. If a
974 /// node already exists with these operands, the slot will be non-null.
975 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
976  void *&InsertPos) {
977  if (doNotCSE(N))
978  return nullptr;
979 
981  AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
982  AddNodeIDCustom(ID, N);
983  SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
984  if (Node)
985  Node->intersectFlagsWith(N->getFlags());
986  return Node;
987 }
988 
989 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
990  Type *Ty = VT == MVT::iPTR ?
992  VT.getTypeForEVT(*getContext());
993 
994  return getDataLayout().getABITypeAlignment(Ty);
995 }
996 
997 // EntryNode could meaningfully have debug info if we can find it...
999  : TM(tm), OptLevel(OL),
1000  EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1001  Root(getEntryNode()) {
1002  InsertNode(&EntryNode);
1003  DbgInfo = new SDDbgInfo();
1004 }
1005 
1007  OptimizationRemarkEmitter &NewORE,
1008  Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1009  LegacyDivergenceAnalysis * Divergence) {
1010  MF = &NewMF;
1011  SDAGISelPass = PassPtr;
1012  ORE = &NewORE;
1013  TLI = getSubtarget().getTargetLowering();
1015  LibInfo = LibraryInfo;
1016  Context = &MF->getFunction().getContext();
1017  DA = Divergence;
1018 }
1019 
1021  assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1022  allnodes_clear();
1023  OperandRecycler.clear(OperandAllocator);
1024  delete DbgInfo;
1025 }
1026 
1027 void SelectionDAG::allnodes_clear() {
1028  assert(&*AllNodes.begin() == &EntryNode);
1029  AllNodes.remove(AllNodes.begin());
1030  while (!AllNodes.empty())
1031  DeallocateNode(&AllNodes.front());
1032 #ifndef NDEBUG
1033  NextPersistentId = 0;
1034 #endif
1035 }
1036 
1037 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1038  void *&InsertPos) {
1039  SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1040  if (N) {
1041  switch (N->getOpcode()) {
1042  default: break;
1043  case ISD::Constant:
1044  case ISD::ConstantFP:
1045  llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1046  "debug location. Use another overload.");
1047  }
1048  }
1049  return N;
1050 }
1051 
1052 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1053  const SDLoc &DL, void *&InsertPos) {
1054  SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1055  if (N) {
1056  switch (N->getOpcode()) {
1057  case ISD::Constant:
1058  case ISD::ConstantFP:
1059  // Erase debug location from the node if the node is used at several
1060  // different places. Do not propagate one location to all uses as it
1061  // will cause a worse single stepping debugging experience.
1062  if (N->getDebugLoc() != DL.getDebugLoc())
1063  N->setDebugLoc(DebugLoc());
1064  break;
1065  default:
1066  // When the node's point of use is located earlier in the instruction
1067  // sequence than its prior point of use, update its debug info to the
1068  // earlier location.
1069  if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1070  N->setDebugLoc(DL.getDebugLoc());
1071  break;
1072  }
1073  }
1074  return N;
1075 }
1076 
1078  allnodes_clear();
1079  OperandRecycler.clear(OperandAllocator);
1080  OperandAllocator.Reset();
1081  CSEMap.clear();
1082 
1083  ExtendedValueTypeNodes.clear();
1084  ExternalSymbols.clear();
1085  TargetExternalSymbols.clear();
1086  MCSymbols.clear();
1087  std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1088  static_cast<CondCodeSDNode*>(nullptr));
1089  std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1090  static_cast<SDNode*>(nullptr));
1091 
1092  EntryNode.UseList = nullptr;
1093  InsertNode(&EntryNode);
1094  Root = getEntryNode();
1095  DbgInfo->clear();
1096 }
1097 
1099  return VT.bitsGT(Op.getValueType())
1100  ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1101  : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1102 }
1103 
1105  return VT.bitsGT(Op.getValueType()) ?
1106  getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1107  getNode(ISD::TRUNCATE, DL, VT, Op);
1108 }
1109 
1111  return VT.bitsGT(Op.getValueType()) ?
1112  getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1113  getNode(ISD::TRUNCATE, DL, VT, Op);
1114 }
1115 
1117  return VT.bitsGT(Op.getValueType()) ?
1118  getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1119  getNode(ISD::TRUNCATE, DL, VT, Op);
1120 }
1121 
1123  EVT OpVT) {
1124  if (VT.bitsLE(Op.getValueType()))
1125  return getNode(ISD::TRUNCATE, SL, VT, Op);
1126 
1128  return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1129 }
1130 
1132  assert(!VT.isVector() &&
1133  "getZeroExtendInReg should use the vector element type instead of "
1134  "the vector type!");
1135  if (Op.getValueType().getScalarType() == VT) return Op;
1136  unsigned BitWidth = Op.getScalarValueSizeInBits();
1137  APInt Imm = APInt::getLowBitsSet(BitWidth,
1138  VT.getSizeInBits());
1139  return getNode(ISD::AND, DL, Op.getValueType(), Op,
1140  getConstant(Imm, DL, Op.getValueType()));
1141 }
1142 
1144  // Only unsigned pointer semantics are supported right now. In the future this
1145  // might delegate to TLI to check pointer signedness.
1146  return getZExtOrTrunc(Op, DL, VT);
1147 }
1148 
1150  // Only unsigned pointer semantics are supported right now. In the future this
1151  // might delegate to TLI to check pointer signedness.
1152  return getZeroExtendInReg(Op, DL, VT);
1153 }
1154 
1155 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1157  EVT EltVT = VT.getScalarType();
1158  SDValue NegOne =
1160  return getNode(ISD::XOR, DL, VT, Val, NegOne);
1161 }
1162 
1164  SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1165  return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1166 }
1167 
1169  EVT OpVT) {
1170  if (!V)
1171  return getConstant(0, DL, VT);
1172 
1173  switch (TLI->getBooleanContents(OpVT)) {
1176  return getConstant(1, DL, VT);
1178  return getAllOnesConstant(DL, VT);
1179  }
1180  llvm_unreachable("Unexpected boolean content enum!");
1181 }
1182 
1183 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1184  bool isT, bool isO) {
1185  EVT EltVT = VT.getScalarType();
1186  assert((EltVT.getSizeInBits() >= 64 ||
1187  (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1188  "getConstant with a uint64_t value that doesn't fit in the type!");
1189  return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1190 }
1191 
1193  bool isT, bool isO) {
1194  return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1195 }
1196 
1198  EVT VT, bool isT, bool isO) {
1199  assert(VT.isInteger() && "Cannot create FP integer constant!");
1200 
1201  EVT EltVT = VT.getScalarType();
1202  const ConstantInt *Elt = &Val;
1203 
1204  // In some cases the vector type is legal but the element type is illegal and
1205  // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1206  // inserted value (the type does not need to match the vector element type).
1207  // Any extra bits introduced will be truncated away.
1208  if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1210  EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1211  APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1212  Elt = ConstantInt::get(*getContext(), NewVal);
1213  }
1214  // In other cases the element type is illegal and needs to be expanded, for
1215  // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1216  // the value into n parts and use a vector type with n-times the elements.
1217  // Then bitcast to the type requested.
1218  // Legalizing constants too early makes the DAGCombiner's job harder so we
1219  // only legalize if the DAG tells us we must produce legal types.
1220  else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1221  TLI->getTypeAction(*getContext(), EltVT) ==
1223  const APInt &NewVal = Elt->getValue();
1224  EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1225  unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1226  unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1227  EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1228 
1229  // Check the temporary vector is the correct size. If this fails then
1230  // getTypeToTransformTo() probably returned a type whose size (in bits)
1231  // isn't a power-of-2 factor of the requested type size.
1232  assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1233 
1234  SmallVector<SDValue, 2> EltParts;
1235  for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1236  EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
1237  .zextOrTrunc(ViaEltSizeInBits), DL,
1238  ViaEltVT, isT, isO));
1239  }
1240 
1241  // EltParts is currently in little endian order. If we actually want
1242  // big-endian order then reverse it now.
1243  if (getDataLayout().isBigEndian())
1244  std::reverse(EltParts.begin(), EltParts.end());
1245 
1246  // The elements must be reversed when the element order is different
1247  // to the endianness of the elements (because the BITCAST is itself a
1248  // vector shuffle in this situation). However, we do not need any code to
1249  // perform this reversal because getConstant() is producing a vector
1250  // splat.
1251  // This situation occurs in MIPS MSA.
1252 
1254  for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1255  Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
1256 
1257  SDValue V = getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1258  return V;
1259  }
1260 
1261  assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1262  "APInt size does not match type size!");
1263  unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1265  AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1266  ID.AddPointer(Elt);
1267  ID.AddBoolean(isO);
1268  void *IP = nullptr;
1269  SDNode *N = nullptr;
1270  if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1271  if (!VT.isVector())
1272  return SDValue(N, 0);
1273 
1274  if (!N) {
1275  N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1276  CSEMap.InsertNode(N, IP);
1277  InsertNode(N);
1278  NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1279  }
1280 
1281  SDValue Result(N, 0);
1282  if (VT.isVector())
1283  Result = getSplatBuildVector(VT, DL, Result);
1284 
1285  return Result;
1286 }
1287 
1289  bool isTarget) {
1290  return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1291 }
1292 
1294  const SDLoc &DL, bool LegalTypes) {
1295  EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1296  return getConstant(Val, DL, ShiftVT);
1297 }
1298 
1300  bool isTarget) {
1301  return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1302 }
1303 
1305  EVT VT, bool isTarget) {
1306  assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1307 
1308  EVT EltVT = VT.getScalarType();
1309 
1310  // Do the map lookup using the actual bit pattern for the floating point
1311  // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1312  // we don't have issues with SNANs.
1313  unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1315  AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1316  ID.AddPointer(&V);
1317  void *IP = nullptr;
1318  SDNode *N = nullptr;
1319  if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1320  if (!VT.isVector())
1321  return SDValue(N, 0);
1322 
1323  if (!N) {
1324  N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1325  CSEMap.InsertNode(N, IP);
1326  InsertNode(N);
1327  }
1328 
1329  SDValue Result(N, 0);
1330  if (VT.isVector())
1331  Result = getSplatBuildVector(VT, DL, Result);
1332  NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1333  return Result;
1334 }
1335 
1336 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1337  bool isTarget) {
1338  EVT EltVT = VT.getScalarType();
1339  if (EltVT == MVT::f32)
1340  return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1341  else if (EltVT == MVT::f64)
1342  return getConstantFP(APFloat(Val), DL, VT, isTarget);
1343  else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1344  EltVT == MVT::f16) {
1345  bool Ignored;
1346  APFloat APF = APFloat(Val);
1348  &Ignored);
1349  return getConstantFP(APF, DL, VT, isTarget);
1350  } else
1351  llvm_unreachable("Unsupported type in getConstantFP");
1352 }
1353 
1355  EVT VT, int64_t Offset, bool isTargetGA,
1356  unsigned char TargetFlags) {
1357  assert((TargetFlags == 0 || isTargetGA) &&
1358  "Cannot set target flags on target-independent globals");
1359 
1360  // Truncate (with sign-extension) the offset value to the pointer size.
1361  unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1362  if (BitWidth < 64)
1363  Offset = SignExtend64(Offset, BitWidth);
1364 
1365  unsigned Opc;
1366  if (GV->isThreadLocal())
1368  else
1369  Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1370 
1372  AddNodeIDNode(ID, Opc, getVTList(VT), None);
1373  ID.AddPointer(GV);
1374  ID.AddInteger(Offset);
1375  ID.AddInteger(TargetFlags);
1376  void *IP = nullptr;
1377  if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1378  return SDValue(E, 0);
1379 
1380  auto *N = newSDNode<GlobalAddressSDNode>(
1381  Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1382  CSEMap.InsertNode(N, IP);
1383  InsertNode(N);
1384  return SDValue(N, 0);
1385 }
1386 
1387 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1388  unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1390  AddNodeIDNode(ID, Opc, getVTList(VT), None);
1391  ID.AddInteger(FI);
1392  void *IP = nullptr;
1393  if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1394  return SDValue(E, 0);
1395 
1396  auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1397  CSEMap.InsertNode(N, IP);
1398  InsertNode(N);
1399  return SDValue(N, 0);
1400 }
1401 
1402 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1403  unsigned char TargetFlags) {
1404  assert((TargetFlags == 0 || isTarget) &&
1405  "Cannot set target flags on target-independent jump tables");
1406  unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1408  AddNodeIDNode(ID, Opc, getVTList(VT), None);
1409  ID.AddInteger(JTI);
1410  ID.AddInteger(TargetFlags);
1411  void *IP = nullptr;
1412  if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1413  return SDValue(E, 0);
1414 
1415  auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1416  CSEMap.InsertNode(N, IP);
1417  InsertNode(N);
1418  return SDValue(N, 0);
1419 }
1420 
1422  unsigned Alignment, int Offset,
1423  bool isTarget,
1424  unsigned char TargetFlags) {
1425  assert((TargetFlags == 0 || isTarget) &&
1426  "Cannot set target flags on target-independent globals");
1427  if (Alignment == 0)
1428  Alignment = MF->getFunction().hasOptSize()
1431  unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1433  AddNodeIDNode(ID, Opc, getVTList(VT), None);
1434  ID.AddInteger(Alignment);
1435  ID.AddInteger(Offset);
1436  ID.AddPointer(C);
1437  ID.AddInteger(TargetFlags);
1438  void *IP = nullptr;
1439  if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1440  return SDValue(E, 0);
1441 
1442  auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1443  TargetFlags);
1444  CSEMap.InsertNode(N, IP);
1445  InsertNode(N);
1446  return SDValue(N, 0);
1447 }
1448 
1450  unsigned Alignment, int Offset,
1451  bool isTarget,
1452  unsigned char TargetFlags) {
1453  assert((TargetFlags == 0 || isTarget) &&
1454  "Cannot set target flags on target-independent globals");
1455  if (Alignment == 0)
1456  Alignment = getDataLayout().getPrefTypeAlignment(C->getType());
1457  unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1459  AddNodeIDNode(ID, Opc, getVTList(VT), None);
1460  ID.AddInteger(Alignment);
1461  ID.AddInteger(Offset);
1462  C->addSelectionDAGCSEId(ID);
1463  ID.AddInteger(TargetFlags);
1464  void *IP = nullptr;
1465  if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1466  return SDValue(E, 0);
1467 
1468  auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1469  TargetFlags);
1470  CSEMap.InsertNode(N, IP);
1471  InsertNode(N);
1472  return SDValue(N, 0);
1473 }
1474 
1476  unsigned char TargetFlags) {
1479  ID.AddInteger(Index);
1480  ID.AddInteger(Offset);
1481  ID.AddInteger(TargetFlags);
1482  void *IP = nullptr;
1483  if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1484  return SDValue(E, 0);
1485 
1486  auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1487  CSEMap.InsertNode(N, IP);
1488  InsertNode(N);
1489  return SDValue(N, 0);
1490 }
1491 
1495  ID.AddPointer(MBB);
1496  void *IP = nullptr;
1497  if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1498  return SDValue(E, 0);
1499 
1500  auto *N = newSDNode<BasicBlockSDNode>(MBB);
1501  CSEMap.InsertNode(N, IP);
1502  InsertNode(N);
1503  return SDValue(N, 0);
1504 }
1505 
1507  if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1508  ValueTypeNodes.size())
1509  ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1510 
1511  SDNode *&N = VT.isExtended() ?
1512  ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1513 
1514  if (N) return SDValue(N, 0);
1515  N = newSDNode<VTSDNode>(VT);
1516  InsertNode(N);
1517  return SDValue(N, 0);
1518 }
1519 
1521  SDNode *&N = ExternalSymbols[Sym];
1522  if (N) return SDValue(N, 0);
1523  N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1524  InsertNode(N);
1525  return SDValue(N, 0);
1526 }
1527 
1529  SDNode *&N = MCSymbols[Sym];
1530  if (N)
1531  return SDValue(N, 0);
1532  N = newSDNode<MCSymbolSDNode>(Sym, VT);
1533  InsertNode(N);
1534  return SDValue(N, 0);
1535 }
1536 
1538  unsigned char TargetFlags) {
1539  SDNode *&N =
1540  TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1541  TargetFlags)];
1542  if (N) return SDValue(N, 0);
1543  N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1544  InsertNode(N);
1545  return SDValue(N, 0);
1546 }
1547 
1549  if ((unsigned)Cond >= CondCodeNodes.size())
1550  CondCodeNodes.resize(Cond+1);
1551 
1552  if (!CondCodeNodes[Cond]) {
1553  auto *N = newSDNode<CondCodeSDNode>(Cond);
1554  CondCodeNodes[Cond] = N;
1555  InsertNode(N);
1556  }
1557 
1558  return SDValue(CondCodeNodes[Cond], 0);
1559 }
1560 
1561 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1562 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1564  std::swap(N1, N2);
1566 }
1567 
1569  SDValue N2, ArrayRef<int> Mask) {
1570  assert(VT.getVectorNumElements() == Mask.size() &&
1571  "Must have the same number of vector elements as mask elements!");
1572  assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1573  "Invalid VECTOR_SHUFFLE");
1574 
1575  // Canonicalize shuffle undef, undef -> undef
1576  if (N1.isUndef() && N2.isUndef())
1577  return getUNDEF(VT);
1578 
1579  // Validate that all indices in Mask are within the range of the elements
1580  // input to the shuffle.
1581  int NElts = Mask.size();
1582  assert(llvm::all_of(Mask,
1583  [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1584  "Index out of range");
1585 
1586  // Copy the mask so we can do any needed cleanup.
1587  SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1588 
1589  // Canonicalize shuffle v, v -> v, undef
1590  if (N1 == N2) {
1591  N2 = getUNDEF(VT);
1592  for (int i = 0; i != NElts; ++i)
1593  if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1594  }
1595 
1596  // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1597  if (N1.isUndef())
1598  commuteShuffle(N1, N2, MaskVec);
1599 
1600  if (TLI->hasVectorBlend()) {
1601  // If shuffling a splat, try to blend the splat instead. We do this here so
1602  // that even when this arises during lowering we don't have to re-handle it.
1603  auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1604  BitVector UndefElements;
1605  SDValue Splat = BV->getSplatValue(&UndefElements);
1606  if (!Splat)
1607  return;
1608 
1609  for (int i = 0; i < NElts; ++i) {
1610  if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1611  continue;
1612 
1613  // If this input comes from undef, mark it as such.
1614  if (UndefElements[MaskVec[i] - Offset]) {
1615  MaskVec[i] = -1;
1616  continue;
1617  }
1618 
1619  // If we can blend a non-undef lane, use that instead.
1620  if (!UndefElements[i])
1621  MaskVec[i] = i + Offset;
1622  }
1623  };
1624  if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1625  BlendSplat(N1BV, 0);
1626  if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1627  BlendSplat(N2BV, NElts);
1628  }
1629 
1630  // Canonicalize all index into lhs, -> shuffle lhs, undef
1631  // Canonicalize all index into rhs, -> shuffle rhs, undef
1632  bool AllLHS = true, AllRHS = true;
1633  bool N2Undef = N2.isUndef();
1634  for (int i = 0; i != NElts; ++i) {
1635  if (MaskVec[i] >= NElts) {
1636  if (N2Undef)
1637  MaskVec[i] = -1;
1638  else
1639  AllLHS = false;
1640  } else if (MaskVec[i] >= 0) {
1641  AllRHS = false;
1642  }
1643  }
1644  if (AllLHS && AllRHS)
1645  return getUNDEF(VT);
1646  if (AllLHS && !N2Undef)
1647  N2 = getUNDEF(VT);
1648  if (AllRHS) {
1649  N1 = getUNDEF(VT);
1650  commuteShuffle(N1, N2, MaskVec);
1651  }
1652  // Reset our undef status after accounting for the mask.
1653  N2Undef = N2.isUndef();
1654  // Re-check whether both sides ended up undef.
1655  if (N1.isUndef() && N2Undef)
1656  return getUNDEF(VT);
1657 
1658  // If Identity shuffle return that node.
1659  bool Identity = true, AllSame = true;
1660  for (int i = 0; i != NElts; ++i) {
1661  if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1662  if (MaskVec[i] != MaskVec[0]) AllSame = false;
1663  }
1664  if (Identity && NElts)
1665  return N1;
1666 
1667  // Shuffling a constant splat doesn't change the result.
1668  if (N2Undef) {
1669  SDValue V = N1;
1670 
1671  // Look through any bitcasts. We check that these don't change the number
1672  // (and size) of elements and just changes their types.
1673  while (V.getOpcode() == ISD::BITCAST)
1674  V = V->getOperand(0);
1675 
1676  // A splat should always show up as a build vector node.
1677  if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1678  BitVector UndefElements;
1679  SDValue Splat = BV->getSplatValue(&UndefElements);
1680  // If this is a splat of an undef, shuffling it is also undef.
1681  if (Splat && Splat.isUndef())
1682  return getUNDEF(VT);
1683 
1684  bool SameNumElts =
1686 
1687  // We only have a splat which can skip shuffles if there is a splatted
1688  // value and no undef lanes rearranged by the shuffle.
1689  if (Splat && UndefElements.none()) {
1690  // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1691  // number of elements match or the value splatted is a zero constant.
1692  if (SameNumElts)
1693  return N1;
1694  if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1695  if (C->isNullValue())
1696  return N1;
1697  }
1698 
1699  // If the shuffle itself creates a splat, build the vector directly.
1700  if (AllSame && SameNumElts) {
1701  EVT BuildVT = BV->getValueType(0);
1702  const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1703  SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1704 
1705  // We may have jumped through bitcasts, so the type of the
1706  // BUILD_VECTOR may not match the type of the shuffle.
1707  if (BuildVT != VT)
1708  NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1709  return NewBV;
1710  }
1711  }
1712  }
1713 
1715  SDValue Ops[2] = { N1, N2 };
1717  for (int i = 0; i != NElts; ++i)
1718  ID.AddInteger(MaskVec[i]);
1719 
1720  void* IP = nullptr;
1721  if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1722  return SDValue(E, 0);
1723 
1724  // Allocate the mask array for the node out of the BumpPtrAllocator, since
1725  // SDNode doesn't have access to it. This memory will be "leaked" when
1726  // the node is deallocated, but recovered when the NodeAllocator is released.
1727  int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1728  llvm::copy(MaskVec, MaskAlloc);
1729 
1730  auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1731  dl.getDebugLoc(), MaskAlloc);
1732  createOperands(N, Ops);
1733 
1734  CSEMap.InsertNode(N, IP);
1735  InsertNode(N);
1736  SDValue V = SDValue(N, 0);
1737  NewSDValueDbgMsg(V, "Creating new node: ", this);
1738  return V;
1739 }
1740 
1742  EVT VT = SV.getValueType(0);
1743  SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1745 
1746  SDValue Op0 = SV.getOperand(0);
1747  SDValue Op1 = SV.getOperand(1);
1748  return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1749 }
1750 
1754  ID.AddInteger(RegNo);
1755  void *IP = nullptr;
1756  if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1757  return SDValue(E, 0);
1758 
1759  auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1760  N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
1761  CSEMap.InsertNode(N, IP);
1762  InsertNode(N);
1763  return SDValue(N, 0);
1764 }
1765 
1769  ID.AddPointer(RegMask);
1770  void *IP = nullptr;
1771  if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1772  return SDValue(E, 0);
1773 
1774  auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1775  CSEMap.InsertNode(N, IP);
1776  InsertNode(N);
1777  return SDValue(N, 0);
1778 }
1779 
1781  MCSymbol *Label) {
1782  return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
1783 }
1784 
1785 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
1786  SDValue Root, MCSymbol *Label) {
1788  SDValue Ops[] = { Root };
1789  AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
1790  ID.AddPointer(Label);
1791  void *IP = nullptr;
1792  if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1793  return SDValue(E, 0);
1794 
1795  auto *N =
1796  newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
1797  createOperands(N, Ops);
1798 
1799  CSEMap.InsertNode(N, IP);
1800  InsertNode(N);
1801  return SDValue(N, 0);
1802 }
1803 
1805  int64_t Offset,
1806  bool isTarget,
1807  unsigned char TargetFlags) {
1808  unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1809 
1811  AddNodeIDNode(ID, Opc, getVTList(VT), None);
1812  ID.AddPointer(BA);
1813  ID.AddInteger(Offset);
1814  ID.AddInteger(TargetFlags);
1815  void *IP = nullptr;
1816  if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1817  return SDValue(E, 0);
1818 
1819  auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
1820  CSEMap.InsertNode(N, IP);
1821  InsertNode(N);
1822  return SDValue(N, 0);
1823 }
1824 
1826  assert((!V || V->getType()->isPointerTy()) &&
1827  "SrcValue is not a pointer?");
1828 
1831  ID.AddPointer(V);
1832 
1833  void *IP = nullptr;
1834  if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1835  return SDValue(E, 0);
1836 
1837  auto *N = newSDNode<SrcValueSDNode>(V);
1838  CSEMap.InsertNode(N, IP);
1839  InsertNode(N);
1840  return SDValue(N, 0);
1841 }
1842 
1846  ID.AddPointer(MD);
1847 
1848  void *IP = nullptr;
1849  if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1850  return SDValue(E, 0);
1851 
1852  auto *N = newSDNode<MDNodeSDNode>(MD);
1853  CSEMap.InsertNode(N, IP);
1854  InsertNode(N);
1855  return SDValue(N, 0);
1856 }
1857 
1859  if (VT == V.getValueType())
1860  return V;
1861 
1862  return getNode(ISD::BITCAST, SDLoc(V), VT, V);
1863 }
1864 
1866  unsigned SrcAS, unsigned DestAS) {
1867  SDValue Ops[] = {Ptr};
1870  ID.AddInteger(SrcAS);
1871  ID.AddInteger(DestAS);
1872 
1873  void *IP = nullptr;
1874  if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1875  return SDValue(E, 0);
1876 
1877  auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
1878  VT, SrcAS, DestAS);
1879  createOperands(N, Ops);
1880 
1881  CSEMap.InsertNode(N, IP);
1882  InsertNode(N);
1883  return SDValue(N, 0);
1884 }
1885 
1886 /// getShiftAmountOperand - Return the specified value casted to
1887 /// the target's desired shift amount type.
1889  EVT OpTy = Op.getValueType();
1890  EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
1891  if (OpTy == ShTy || OpTy.isVector()) return Op;
1892 
1893  return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
1894 }
1895 
1897  SDLoc dl(Node);
1898  const TargetLowering &TLI = getTargetLoweringInfo();
1899  const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1900  EVT VT = Node->getValueType(0);
1901  SDValue Tmp1 = Node->getOperand(0);
1902  SDValue Tmp2 = Node->getOperand(1);
1903  unsigned Align = Node->getConstantOperandVal(3);
1904 
1905  SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
1906  Tmp2, MachinePointerInfo(V));
1907  SDValue VAList = VAListLoad;
1908 
1909  if (Align > TLI.getMinStackArgumentAlignment()) {
1910  assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1911 
1912  VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1913  getConstant(Align - 1, dl, VAList.getValueType()));
1914 
1915  VAList = getNode(ISD::AND, dl, VAList.getValueType(), VAList,
1916  getConstant(-(int64_t)Align, dl, VAList.getValueType()));
1917  }
1918 
1919  // Increment the pointer, VAList, to the next vaarg
1920  Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1921  getConstant(getDataLayout().getTypeAllocSize(
1922  VT.getTypeForEVT(*getContext())),
1923  dl, VAList.getValueType()));
1924  // Store the incremented VAList to the legalized pointer
1925  Tmp1 =
1926  getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
1927  // Load the actual argument out of the pointer VAList
1928  return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
1929 }
1930 
1932  SDLoc dl(Node);
1933  const TargetLowering &TLI = getTargetLoweringInfo();
1934  // This defaults to loading a pointer from the input and storing it to the
1935  // output, returning the chain.
1936  const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
1937  const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
1938  SDValue Tmp1 =
1939  getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
1940  Node->getOperand(2), MachinePointerInfo(VS));
1941  return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
1942  MachinePointerInfo(VD));
1943 }
1944 
1947  unsigned ByteSize = VT.getStoreSize();
1948  Type *Ty = VT.getTypeForEVT(*getContext());
1949  unsigned StackAlign =
1950  std::max((unsigned)getDataLayout().getPrefTypeAlignment(Ty), minAlign);
1951 
1952  int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
1953  return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1954 }
1955 
1957  unsigned Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize());
1958  Type *Ty1 = VT1.getTypeForEVT(*getContext());
1959  Type *Ty2 = VT2.getTypeForEVT(*getContext());
1960  const DataLayout &DL = getDataLayout();
1961  unsigned Align =
1963 
1965  int FrameIdx = MFI.CreateStackObject(Bytes, Align, false);
1966  return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1967 }
1968 
1970  ISD::CondCode Cond, const SDLoc &dl) {
1971  EVT OpVT = N1.getValueType();
1972 
1973  // These setcc operations always fold.
1974  switch (Cond) {
1975  default: break;
1976  case ISD::SETFALSE:
1977  case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
1978  case ISD::SETTRUE:
1979  case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
1980 
1981  case ISD::SETOEQ:
1982  case ISD::SETOGT:
1983  case ISD::SETOGE:
1984  case ISD::SETOLT:
1985  case ISD::SETOLE:
1986  case ISD::SETONE:
1987  case ISD::SETO:
1988  case ISD::SETUO:
1989  case ISD::SETUEQ:
1990  case ISD::SETUNE:
1991  assert(!OpVT.isInteger() && "Illegal setcc for integer!");
1992  break;
1993  }
1994 
1995  if (OpVT.isInteger()) {
1996  // For EQ and NE, we can always pick a value for the undef to make the
1997  // predicate pass or fail, so we can return undef.
1998  // Matches behavior in llvm::ConstantFoldCompareInstruction.
1999  // icmp eq/ne X, undef -> undef.
2000  if ((N1.isUndef() || N2.isUndef()) &&
2001  (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2002  return getUNDEF(VT);
2003 
2004  // If both operands are undef, we can return undef for int comparison.
2005  // icmp undef, undef -> undef.
2006  if (N1.isUndef() && N2.isUndef())
2007  return getUNDEF(VT);
2008 
2009  // icmp X, X -> true/false
2010  // icmp X, undef -> true/false because undef could be X.
2011  if (N1 == N2)
2012  return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2013  }
2014 
2015  if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2016  const APInt &C2 = N2C->getAPIntValue();
2017  if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2018  const APInt &C1 = N1C->getAPIntValue();
2019 
2020  switch (Cond) {
2021  default: llvm_unreachable("Unknown integer setcc!");
2022  case ISD::SETEQ: return getBoolConstant(C1 == C2, dl, VT, OpVT);
2023  case ISD::SETNE: return getBoolConstant(C1 != C2, dl, VT, OpVT);
2024  case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
2025  case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
2026  case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
2027  case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
2028  case ISD::SETLT: return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
2029  case ISD::SETGT: return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
2030  case ISD::SETLE: return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
2031  case ISD::SETGE: return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
2032  }
2033  }
2034  }
2035 
2036  auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2037  auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2038 
2039  if (N1CFP && N2CFP) {
2040  APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2041  switch (Cond) {
2042  default: break;
2043  case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2044  return getUNDEF(VT);
2046  case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2047  OpVT);
2048  case ISD::SETNE: if (R==APFloat::cmpUnordered)
2049  return getUNDEF(VT);
2052  R==APFloat::cmpLessThan, dl, VT,
2053  OpVT);
2054  case ISD::SETLT: if (R==APFloat::cmpUnordered)
2055  return getUNDEF(VT);
2057  case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2058  OpVT);
2059  case ISD::SETGT: if (R==APFloat::cmpUnordered)
2060  return getUNDEF(VT);
2063  VT, OpVT);
2064  case ISD::SETLE: if (R==APFloat::cmpUnordered)
2065  return getUNDEF(VT);
2068  R==APFloat::cmpEqual, dl, VT,
2069  OpVT);
2070  case ISD::SETGE: if (R==APFloat::cmpUnordered)
2071  return getUNDEF(VT);
2074  R==APFloat::cmpEqual, dl, VT, OpVT);
2075  case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2076  OpVT);
2077  case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2078  OpVT);
2080  R==APFloat::cmpEqual, dl, VT,
2081  OpVT);
2082  case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2083  OpVT);
2085  R==APFloat::cmpLessThan, dl, VT,
2086  OpVT);
2088  R==APFloat::cmpUnordered, dl, VT,
2089  OpVT);
2091  VT, OpVT);
2092  case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2093  OpVT);
2094  }
2095  } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2096  // Ensure that the constant occurs on the RHS.
2097  ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2098  if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2099  return SDValue();
2100  return getSetCC(dl, VT, N2, N1, SwappedCond);
2101  } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2102  (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2103  // If an operand is known to be a nan (or undef that could be a nan), we can
2104  // fold it.
2105  // Choosing NaN for the undef will always make unordered comparison succeed
2106  // and ordered comparison fails.
2107  // Matches behavior in llvm::ConstantFoldCompareInstruction.
2108  switch (ISD::getUnorderedFlavor(Cond)) {
2109  default:
2110  llvm_unreachable("Unknown flavor!");
2111  case 0: // Known false.
2112  return getBoolConstant(false, dl, VT, OpVT);
2113  case 1: // Known true.
2114  return getBoolConstant(true, dl, VT, OpVT);
2115  case 2: // Undefined.
2116  return getUNDEF(VT);
2117  }
2118  }
2119 
2120  // Could not fold it.
2121  return SDValue();
2122 }
2123 
2124 /// See if the specified operand can be simplified with the knowledge that only
2125 /// the bits specified by DemandedBits are used.
2126 /// TODO: really we should be making this into the DAG equivalent of
2127 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2129  EVT VT = V.getValueType();
2130  APInt DemandedElts = VT.isVector()
2132  : APInt(1, 1);
2133  return GetDemandedBits(V, DemandedBits, DemandedElts);
2134 }
2135 
2136 /// See if the specified operand can be simplified with the knowledge that only
2137 /// the bits specified by DemandedBits are used in the elements specified by
2138 /// DemandedElts.
2139 /// TODO: really we should be making this into the DAG equivalent of
2140 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2142  const APInt &DemandedElts) {
2143  switch (V.getOpcode()) {
2144  default:
2145  break;
2146  case ISD::Constant: {
2147  auto *CV = cast<ConstantSDNode>(V.getNode());
2148  assert(CV && "Const value should be ConstSDNode.");
2149  const APInt &CVal = CV->getAPIntValue();
2150  APInt NewVal = CVal & DemandedBits;
2151  if (NewVal != CVal)
2152  return getConstant(NewVal, SDLoc(V), V.getValueType());
2153  break;
2154  }
2155  case ISD::OR:
2156  case ISD::XOR:
2157  // If the LHS or RHS don't contribute bits to the or, drop them.
2158  if (MaskedValueIsZero(V.getOperand(0), DemandedBits))
2159  return V.getOperand(1);
2160  if (MaskedValueIsZero(V.getOperand(1), DemandedBits))
2161  return V.getOperand(0);
2162  break;
2163  case ISD::SRL:
2164  // Only look at single-use SRLs.
2165  if (!V.getNode()->hasOneUse())
2166  break;
2167  if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2168  // See if we can recursively simplify the LHS.
2169  unsigned Amt = RHSC->getZExtValue();
2170 
2171  // Watch out for shift count overflow though.
2172  if (Amt >= DemandedBits.getBitWidth())
2173  break;
2174  APInt SrcDemandedBits = DemandedBits << Amt;
2175  if (SDValue SimplifyLHS =
2176  GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2177  return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2178  V.getOperand(1));
2179  }
2180  break;
2181  case ISD::AND: {
2182  // X & -1 -> X (ignoring bits which aren't demanded).
2183  // Also handle the case where masked out bits in X are known to be zero.
2184  if (ConstantSDNode *RHSC = isConstOrConstSplat(V.getOperand(1))) {
2185  const APInt &AndVal = RHSC->getAPIntValue();
2186  if (DemandedBits.isSubsetOf(AndVal) ||
2187  DemandedBits.isSubsetOf(computeKnownBits(V.getOperand(0)).Zero |
2188  AndVal))
2189  return V.getOperand(0);
2190  }
2191  break;
2192  }
2193  case ISD::ANY_EXTEND: {
2194  SDValue Src = V.getOperand(0);
2195  unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
2196  // Being conservative here - only peek through if we only demand bits in the
2197  // non-extended source (even though the extended bits are technically
2198  // undef).
2199  if (DemandedBits.getActiveBits() > SrcBitWidth)
2200  break;
2201  APInt SrcDemandedBits = DemandedBits.trunc(SrcBitWidth);
2202  if (SDValue DemandedSrc = GetDemandedBits(Src, SrcDemandedBits))
2203  return getNode(ISD::ANY_EXTEND, SDLoc(V), V.getValueType(), DemandedSrc);
2204  break;
2205  }
2207  EVT ExVT = cast<VTSDNode>(V.getOperand(1))->getVT();
2208  unsigned ExVTBits = ExVT.getScalarSizeInBits();
2209 
2210  // If none of the extended bits are demanded, eliminate the sextinreg.
2211  if (DemandedBits.getActiveBits() <= ExVTBits)
2212  return V.getOperand(0);
2213 
2214  break;
2215  }
2216  return SDValue();
2217 }
2218 
2219 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2220 /// use this predicate to simplify operations downstream.
2221 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2222  unsigned BitWidth = Op.getScalarValueSizeInBits();
2223  return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2224 }
2225 
2226 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2227 /// this predicate to simplify operations downstream. Mask is known to be zero
2228 /// for bits that V cannot have.
2230  unsigned Depth) const {
2231  EVT VT = V.getValueType();
2232  APInt DemandedElts = VT.isVector()
2234  : APInt(1, 1);
2235  return MaskedValueIsZero(V, Mask, DemandedElts, Depth);
2236 }
2237 
2238 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2239 /// DemandedElts. We use this predicate to simplify operations downstream.
2240 /// Mask is known to be zero for bits that V cannot have.
2242  const APInt &DemandedElts,
2243  unsigned Depth) const {
2244  return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2245 }
2246 
2247 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2249  unsigned Depth) const {
2250  return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2251 }
2252 
2253 /// isSplatValue - Return true if the vector V has the same value
2254 /// across all DemandedElts.
2255 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2256  APInt &UndefElts) {
2257  if (!DemandedElts)
2258  return false; // No demanded elts, better to assume we don't know anything.
2259 
2260  EVT VT = V.getValueType();
2261  assert(VT.isVector() && "Vector type expected");
2262 
2263  unsigned NumElts = VT.getVectorNumElements();
2264  assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2265  UndefElts = APInt::getNullValue(NumElts);
2266 
2267  switch (V.getOpcode()) {
2268  case ISD::BUILD_VECTOR: {
2269  SDValue Scl;
2270  for (unsigned i = 0; i != NumElts; ++i) {
2271  SDValue Op = V.getOperand(i);
2272  if (Op.isUndef()) {
2273  UndefElts.setBit(i);
2274  continue;
2275  }
2276  if (!DemandedElts[i])
2277  continue;
2278  if (Scl && Scl != Op)
2279  return false;
2280  Scl = Op;
2281  }
2282  return true;
2283  }
2284  case ISD::VECTOR_SHUFFLE: {
2285  // Check if this is a shuffle node doing a splat.
2286  // TODO: Do we need to handle shuffle(splat, undef, mask)?
2287  int SplatIndex = -1;
2288  ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2289  for (int i = 0; i != (int)NumElts; ++i) {
2290  int M = Mask[i];
2291  if (M < 0) {
2292  UndefElts.setBit(i);
2293  continue;
2294  }
2295  if (!DemandedElts[i])
2296  continue;
2297  if (0 <= SplatIndex && SplatIndex != M)
2298  return false;
2299  SplatIndex = M;
2300  }
2301  return true;
2302  }
2303  case ISD::EXTRACT_SUBVECTOR: {
2304  SDValue Src = V.getOperand(0);
2306  unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2307  if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2308  // Offset the demanded elts by the subvector index.
2309  uint64_t Idx = SubIdx->getZExtValue();
2310  APInt UndefSrcElts;
2311  APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2312  if (isSplatValue(Src, DemandedSrc, UndefSrcElts)) {
2313  UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2314  return true;
2315  }
2316  }
2317  break;
2318  }
2319  case ISD::ADD:
2320  case ISD::SUB:
2321  case ISD::AND: {
2322  APInt UndefLHS, UndefRHS;
2323  SDValue LHS = V.getOperand(0);
2324  SDValue RHS = V.getOperand(1);
2325  if (isSplatValue(LHS, DemandedElts, UndefLHS) &&
2326  isSplatValue(RHS, DemandedElts, UndefRHS)) {
2327  UndefElts = UndefLHS | UndefRHS;
2328  return true;
2329  }
2330  break;
2331  }
2332  }
2333 
2334  return false;
2335 }
2336 
2337 /// Helper wrapper to main isSplatValue function.
2338 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2339  EVT VT = V.getValueType();
2340  assert(VT.isVector() && "Vector type expected");
2341  unsigned NumElts = VT.getVectorNumElements();
2342 
2343  APInt UndefElts;
2344  APInt DemandedElts = APInt::getAllOnesValue(NumElts);
2345  return isSplatValue(V, DemandedElts, UndefElts) &&
2346  (AllowUndefs || !UndefElts);
2347 }
2348 
2351 
2352  EVT VT = V.getValueType();
2353  unsigned Opcode = V.getOpcode();
2354  switch (Opcode) {
2355  default: {
2356  APInt UndefElts;
2357  APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2358  if (isSplatValue(V, DemandedElts, UndefElts)) {
2359  // Handle case where all demanded elements are UNDEF.
2360  if (DemandedElts.isSubsetOf(UndefElts)) {
2361  SplatIdx = 0;
2362  return getUNDEF(VT);
2363  }
2364  SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2365  return V;
2366  }
2367  break;
2368  }
2369  case ISD::VECTOR_SHUFFLE: {
2370  // Check if this is a shuffle node doing a splat.
2371  // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2372  // getTargetVShiftNode currently struggles without the splat source.
2373  auto *SVN = cast<ShuffleVectorSDNode>(V);
2374  if (!SVN->isSplat())
2375  break;
2376  int Idx = SVN->getSplatIndex();
2377  int NumElts = V.getValueType().getVectorNumElements();
2378  SplatIdx = Idx % NumElts;
2379  return V.getOperand(Idx / NumElts);
2380  }
2381  }
2382 
2383  return SDValue();
2384 }
2385 
2387  int SplatIdx;
2388  if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx))
2390  SrcVector.getValueType().getScalarType(), SrcVector,
2391  getIntPtrConstant(SplatIdx, SDLoc(V)));
2392  return SDValue();
2393 }
2394 
2395 /// If a SHL/SRA/SRL node has a constant or splat constant shift amount that
2396 /// is less than the element bit-width of the shift node, return it.
2398  if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1))) {
2399  // Shifting more than the bitwidth is not valid.
2400  const APInt &ShAmt = SA->getAPIntValue();
2401  if (ShAmt.ult(V.getScalarValueSizeInBits()))
2402  return &ShAmt;
2403  }
2404  return nullptr;
2405 }
2406 
2407 /// Determine which bits of Op are known to be either zero or one and return
2408 /// them in Known. For vectors, the known bits are those that are shared by
2409 /// every vector element.
2411  EVT VT = Op.getValueType();
2412  APInt DemandedElts = VT.isVector()
2414  : APInt(1, 1);
2415  return computeKnownBits(Op, DemandedElts, Depth);
2416 }
2417 
2418 /// Determine which bits of Op are known to be either zero or one and return
2419 /// them in Known. The DemandedElts argument allows us to only collect the known
2420 /// bits that are shared by the requested vector elements.
2422  unsigned Depth) const {
2423  unsigned BitWidth = Op.getScalarValueSizeInBits();
2424 
2425  KnownBits Known(BitWidth); // Don't know anything.
2426 
2427  if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2428  // We know all of the bits for a constant!
2429  Known.One = C->getAPIntValue();
2430  Known.Zero = ~Known.One;
2431  return Known;
2432  }
2433  if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2434  // We know all of the bits for a constant fp!
2435  Known.One = C->getValueAPF().bitcastToAPInt();
2436  Known.Zero = ~Known.One;
2437  return Known;
2438  }
2439 
2440  if (Depth == 6)
2441  return Known; // Limit search depth.
2442 
2443  KnownBits Known2;
2444  unsigned NumElts = DemandedElts.getBitWidth();
2445  assert((!Op.getValueType().isVector() ||
2446  NumElts == Op.getValueType().getVectorNumElements()) &&
2447  "Unexpected vector size");
2448 
2449  if (!DemandedElts)
2450  return Known; // No demanded elts, better to assume we don't know anything.
2451 
2452  unsigned Opcode = Op.getOpcode();
2453  switch (Opcode) {
2454  case ISD::BUILD_VECTOR:
2455  // Collect the known bits that are shared by every demanded vector element.
2456  Known.Zero.setAllBits(); Known.One.setAllBits();
2457  for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2458  if (!DemandedElts[i])
2459  continue;
2460 
2461  SDValue SrcOp = Op.getOperand(i);
2462  Known2 = computeKnownBits(SrcOp, Depth + 1);
2463 
2464  // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2465  if (SrcOp.getValueSizeInBits() != BitWidth) {
2466  assert(SrcOp.getValueSizeInBits() > BitWidth &&
2467  "Expected BUILD_VECTOR implicit truncation");
2468  Known2 = Known2.trunc(BitWidth);
2469  }
2470 
2471  // Known bits are the values that are shared by every demanded element.
2472  Known.One &= Known2.One;
2473  Known.Zero &= Known2.Zero;
2474 
2475  // If we don't know any bits, early out.
2476  if (Known.isUnknown())
2477  break;
2478  }
2479  break;
2480  case ISD::VECTOR_SHUFFLE: {
2481  // Collect the known bits that are shared by every vector element referenced
2482  // by the shuffle.
2483  APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2484  Known.Zero.setAllBits(); Known.One.setAllBits();
2485  const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2486  assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2487  for (unsigned i = 0; i != NumElts; ++i) {
2488  if (!DemandedElts[i])
2489  continue;
2490 
2491  int M = SVN->getMaskElt(i);
2492  if (M < 0) {
2493  // For UNDEF elements, we don't know anything about the common state of
2494  // the shuffle result.
2495  Known.resetAll();
2496  DemandedLHS.clearAllBits();
2497  DemandedRHS.clearAllBits();
2498  break;
2499  }
2500 
2501  if ((unsigned)M < NumElts)
2502  DemandedLHS.setBit((unsigned)M % NumElts);
2503  else
2504  DemandedRHS.setBit((unsigned)M % NumElts);
2505  }
2506  // Known bits are the values that are shared by every demanded element.
2507  if (!!DemandedLHS) {
2508  SDValue LHS = Op.getOperand(0);
2509  Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2510  Known.One &= Known2.One;
2511  Known.Zero &= Known2.Zero;
2512  }
2513  // If we don't know any bits, early out.
2514  if (Known.isUnknown())
2515  break;
2516  if (!!DemandedRHS) {
2517  SDValue RHS = Op.getOperand(1);
2518  Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2519  Known.One &= Known2.One;
2520  Known.Zero &= Known2.Zero;
2521  }
2522  break;
2523  }
2524  case ISD::CONCAT_VECTORS: {
2525  // Split DemandedElts and test each of the demanded subvectors.
2526  Known.Zero.setAllBits(); Known.One.setAllBits();
2527  EVT SubVectorVT = Op.getOperand(0).getValueType();
2528  unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2529  unsigned NumSubVectors = Op.getNumOperands();
2530  for (unsigned i = 0; i != NumSubVectors; ++i) {
2531  APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2532  DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2533  if (!!DemandedSub) {
2534  SDValue Sub = Op.getOperand(i);
2535  Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2536  Known.One &= Known2.One;
2537  Known.Zero &= Known2.Zero;
2538  }
2539  // If we don't know any bits, early out.
2540  if (Known.isUnknown())
2541  break;
2542  }
2543  break;
2544  }
2545  case ISD::INSERT_SUBVECTOR: {
2546  // If we know the element index, demand any elements from the subvector and
2547  // the remainder from the src its inserted into, otherwise demand them all.
2548  SDValue Src = Op.getOperand(0);
2549  SDValue Sub = Op.getOperand(1);
2551  unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2552  if (SubIdx && SubIdx->getAPIntValue().ule(NumElts - NumSubElts)) {
2553  Known.One.setAllBits();
2554  Known.Zero.setAllBits();
2555  uint64_t Idx = SubIdx->getZExtValue();
2556  APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2557  if (!!DemandedSubElts) {
2558  Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2559  if (Known.isUnknown())
2560  break; // early-out.
2561  }
2562  APInt SubMask = APInt::getBitsSet(NumElts, Idx, Idx + NumSubElts);
2563  APInt DemandedSrcElts = DemandedElts & ~SubMask;
2564  if (!!DemandedSrcElts) {
2565  Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2566  Known.One &= Known2.One;
2567  Known.Zero &= Known2.Zero;
2568  }
2569  } else {
2570  Known = computeKnownBits(Sub, Depth + 1);
2571  if (Known.isUnknown())
2572  break; // early-out.
2573  Known2 = computeKnownBits(Src, Depth + 1);
2574  Known.One &= Known2.One;
2575  Known.Zero &= Known2.Zero;
2576  }
2577  break;
2578  }
2579  case ISD::EXTRACT_SUBVECTOR: {
2580  // If we know the element index, just demand that subvector elements,
2581  // otherwise demand them all.
2582  SDValue Src = Op.getOperand(0);
2584  unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2585  if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2586  // Offset the demanded elts by the subvector index.
2587  uint64_t Idx = SubIdx->getZExtValue();
2588  APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2589  Known = computeKnownBits(Src, DemandedSrc, Depth + 1);
2590  } else {
2591  Known = computeKnownBits(Src, Depth + 1);
2592  }
2593  break;
2594  }
2595  case ISD::SCALAR_TO_VECTOR: {
2596  // We know about scalar_to_vector as much as we know about it source,
2597  // which becomes the first element of otherwise unknown vector.
2598  if (DemandedElts != 1)
2599  break;
2600 
2601  SDValue N0 = Op.getOperand(0);
2602  Known = computeKnownBits(N0, Depth + 1);
2603  if (N0.getValueSizeInBits() != BitWidth)
2604  Known = Known.trunc(BitWidth);
2605 
2606  break;
2607  }
2608  case ISD::BITCAST: {
2609  SDValue N0 = Op.getOperand(0);
2610  EVT SubVT = N0.getValueType();
2611  unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2612 
2613  // Ignore bitcasts from unsupported types.
2614  if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2615  break;
2616 
2617  // Fast handling of 'identity' bitcasts.
2618  if (BitWidth == SubBitWidth) {
2619  Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2620  break;
2621  }
2622 
2623  bool IsLE = getDataLayout().isLittleEndian();
2624 
2625  // Bitcast 'small element' vector to 'large element' scalar/vector.
2626  if ((BitWidth % SubBitWidth) == 0) {
2627  assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2628 
2629  // Collect known bits for the (larger) output by collecting the known
2630  // bits from each set of sub elements and shift these into place.
2631  // We need to separately call computeKnownBits for each set of
2632  // sub elements as the knownbits for each is likely to be different.
2633  unsigned SubScale = BitWidth / SubBitWidth;
2634  APInt SubDemandedElts(NumElts * SubScale, 0);
2635  for (unsigned i = 0; i != NumElts; ++i)
2636  if (DemandedElts[i])
2637  SubDemandedElts.setBit(i * SubScale);
2638 
2639  for (unsigned i = 0; i != SubScale; ++i) {
2640  Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2641  Depth + 1);
2642  unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2643  Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts);
2644  Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts);
2645  }
2646  }
2647 
2648  // Bitcast 'large element' scalar/vector to 'small element' vector.
2649  if ((SubBitWidth % BitWidth) == 0) {
2650  assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2651 
2652  // Collect known bits for the (smaller) output by collecting the known
2653  // bits from the overlapping larger input elements and extracting the
2654  // sub sections we actually care about.
2655  unsigned SubScale = SubBitWidth / BitWidth;
2656  APInt SubDemandedElts(NumElts / SubScale, 0);
2657  for (unsigned i = 0; i != NumElts; ++i)
2658  if (DemandedElts[i])
2659  SubDemandedElts.setBit(i / SubScale);
2660 
2661  Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
2662 
2663  Known.Zero.setAllBits(); Known.One.setAllBits();
2664  for (unsigned i = 0; i != NumElts; ++i)
2665  if (DemandedElts[i]) {
2666  unsigned Shifts = IsLE ? i : NumElts - 1 - i;
2667  unsigned Offset = (Shifts % SubScale) * BitWidth;
2668  Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
2669  Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
2670  // If we don't know any bits, early out.
2671  if (Known.isUnknown())
2672  break;
2673  }
2674  }
2675  break;
2676  }
2677  case ISD::AND:
2678  // If either the LHS or the RHS are Zero, the result is zero.
2679  Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2680  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2681 
2682  // Output known-1 bits are only known if set in both the LHS & RHS.
2683  Known.One &= Known2.One;
2684  // Output known-0 are known to be clear if zero in either the LHS | RHS.
2685  Known.Zero |= Known2.Zero;
2686  break;
2687  case ISD::OR:
2688  Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2689  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2690 
2691  // Output known-0 bits are only known if clear in both the LHS & RHS.
2692  Known.Zero &= Known2.Zero;
2693  // Output known-1 are known to be set if set in either the LHS | RHS.
2694  Known.One |= Known2.One;
2695  break;
2696  case ISD::XOR: {
2697  Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2698  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2699 
2700  // Output known-0 bits are known if clear or set in both the LHS & RHS.
2701  APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
2702  // Output known-1 are known to be set if set in only one of the LHS, RHS.
2703  Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
2704  Known.Zero = KnownZeroOut;
2705  break;
2706  }
2707  case ISD::MUL: {
2708  Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2709  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2710 
2711  // If low bits are zero in either operand, output low known-0 bits.
2712  // Also compute a conservative estimate for high known-0 bits.
2713  // More trickiness is possible, but this is sufficient for the
2714  // interesting case of alignment computation.
2715  unsigned TrailZ = Known.countMinTrailingZeros() +
2716  Known2.countMinTrailingZeros();
2717  unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
2718  Known2.countMinLeadingZeros(),
2719  BitWidth) - BitWidth;
2720 
2721  Known.resetAll();
2722  Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
2723  Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
2724  break;
2725  }
2726  case ISD::UDIV: {
2727  // For the purposes of computing leading zeros we can conservatively
2728  // treat a udiv as a logical right shift by the power of 2 known to
2729  // be less than the denominator.
2730  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2731  unsigned LeadZ = Known2.countMinLeadingZeros();
2732 
2733  Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2734  unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
2735  if (RHSMaxLeadingZeros != BitWidth)
2736  LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
2737 
2738  Known.Zero.setHighBits(LeadZ);
2739  break;
2740  }
2741  case ISD::SELECT:
2742  case ISD::VSELECT:
2743  Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
2744  // If we don't know any bits, early out.
2745  if (Known.isUnknown())
2746  break;
2747  Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
2748 
2749  // Only known if known in both the LHS and RHS.
2750  Known.One &= Known2.One;
2751  Known.Zero &= Known2.Zero;
2752  break;
2753  case ISD::SELECT_CC:
2754  Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
2755  // If we don't know any bits, early out.
2756  if (Known.isUnknown())
2757  break;
2758  Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
2759 
2760  // Only known if known in both the LHS and RHS.
2761  Known.One &= Known2.One;
2762  Known.Zero &= Known2.Zero;
2763  break;
2764  case ISD::SMULO:
2765  case ISD::UMULO:
2767  if (Op.getResNo() != 1)
2768  break;
2769  // The boolean result conforms to getBooleanContents.
2770  // If we know the result of a setcc has the top bits zero, use this info.
2771  // We know that we have an integer-based boolean since these operations
2772  // are only available for integer.
2773  if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2775  BitWidth > 1)
2776  Known.Zero.setBitsFrom(1);
2777  break;
2778  case ISD::SETCC:
2779  // If we know the result of a setcc has the top bits zero, use this info.
2780  if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2782  BitWidth > 1)
2783  Known.Zero.setBitsFrom(1);
2784  break;
2785  case ISD::SHL:
2786  if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2787  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2788  unsigned Shift = ShAmt->getZExtValue();
2789  Known.Zero <<= Shift;
2790  Known.One <<= Shift;
2791  // Low bits are known zero.
2792  Known.Zero.setLowBits(Shift);
2793  }
2794  break;
2795  case ISD::SRL:
2796  if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2797  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2798  unsigned Shift = ShAmt->getZExtValue();
2799  Known.Zero.lshrInPlace(Shift);
2800  Known.One.lshrInPlace(Shift);
2801  // High bits are known zero.
2802  Known.Zero.setHighBits(Shift);
2803  } else if (auto *BV = dyn_cast<BuildVectorSDNode>(Op.getOperand(1))) {
2804  // If the shift amount is a vector of constants see if we can bound
2805  // the number of upper zero bits.
2806  unsigned ShiftAmountMin = BitWidth;
2807  for (unsigned i = 0; i != BV->getNumOperands(); ++i) {
2808  if (auto *C = dyn_cast<ConstantSDNode>(BV->getOperand(i))) {
2809  const APInt &ShAmt = C->getAPIntValue();
2810  if (ShAmt.ult(BitWidth)) {
2811  ShiftAmountMin = std::min<unsigned>(ShiftAmountMin,
2812  ShAmt.getZExtValue());
2813  continue;
2814  }
2815  }
2816  // Don't know anything.
2817  ShiftAmountMin = 0;
2818  break;
2819  }
2820 
2821  Known.Zero.setHighBits(ShiftAmountMin);
2822  }
2823  break;
2824  case ISD::SRA:
2825  if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2826  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2827  unsigned Shift = ShAmt->getZExtValue();
2828  // Sign extend known zero/one bit (else is unknown).
2829  Known.Zero.ashrInPlace(Shift);
2830  Known.One.ashrInPlace(Shift);
2831  }
2832  break;
2833  case ISD::FSHL:
2834  case ISD::FSHR:
2835  if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
2836  unsigned Amt = C->getAPIntValue().urem(BitWidth);
2837 
2838  // For fshl, 0-shift returns the 1st arg.
2839  // For fshr, 0-shift returns the 2nd arg.
2840  if (Amt == 0) {
2841  Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
2842  DemandedElts, Depth + 1);
2843  break;
2844  }
2845 
2846  // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
2847  // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
2848  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2849  Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2850  if (Opcode == ISD::FSHL) {
2851  Known.One <<= Amt;
2852  Known.Zero <<= Amt;
2853  Known2.One.lshrInPlace(BitWidth - Amt);
2854  Known2.Zero.lshrInPlace(BitWidth - Amt);
2855  } else {
2856  Known.One <<= BitWidth - Amt;
2857  Known.Zero <<= BitWidth - Amt;
2858  Known2.One.lshrInPlace(Amt);
2859  Known2.Zero.lshrInPlace(Amt);
2860  }
2861  Known.One |= Known2.One;
2862  Known.Zero |= Known2.Zero;
2863  }
2864  break;
2865  case ISD::SIGN_EXTEND_INREG: {
2866  EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2867  unsigned EBits = EVT.getScalarSizeInBits();
2868 
2869  // Sign extension. Compute the demanded bits in the result that are not
2870  // present in the input.
2871  APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
2872 
2873  APInt InSignMask = APInt::getSignMask(EBits);
2874  APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
2875 
2876  // If the sign extended bits are demanded, we know that the sign
2877  // bit is demanded.
2878  InSignMask = InSignMask.zext(BitWidth);
2879  if (NewBits.getBoolValue())
2880  InputDemandedBits |= InSignMask;
2881 
2882  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2883  Known.One &= InputDemandedBits;
2884  Known.Zero &= InputDemandedBits;
2885 
2886  // If the sign bit of the input is known set or clear, then we know the
2887  // top bits of the result.
2888  if (Known.Zero.intersects(InSignMask)) { // Input sign bit known clear
2889  Known.Zero |= NewBits;
2890  Known.One &= ~NewBits;
2891  } else if (Known.One.intersects(InSignMask)) { // Input sign bit known set
2892  Known.One |= NewBits;
2893  Known.Zero &= ~NewBits;
2894  } else { // Input sign bit unknown
2895  Known.Zero &= ~NewBits;
2896  Known.One &= ~NewBits;
2897  }
2898  break;
2899  }
2900  case ISD::CTTZ:
2901  case ISD::CTTZ_ZERO_UNDEF: {
2902  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2903  // If we have a known 1, its position is our upper bound.
2904  unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2905  unsigned LowBits = Log2_32(PossibleTZ) + 1;
2906  Known.Zero.setBitsFrom(LowBits);
2907  break;
2908  }
2909  case ISD::CTLZ:
2910  case ISD::CTLZ_ZERO_UNDEF: {
2911  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2912  // If we have a known 1, its position is our upper bound.
2913  unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2914  unsigned LowBits = Log2_32(PossibleLZ) + 1;
2915  Known.Zero.setBitsFrom(LowBits);
2916  break;
2917  }
2918  case ISD::CTPOP: {
2919  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2920  // If we know some of the bits are zero, they can't be one.
2921  unsigned PossibleOnes = Known2.countMaxPopulation();
2922  Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
2923  break;
2924  }
2925  case ISD::LOAD: {
2926  LoadSDNode *LD = cast<LoadSDNode>(Op);
2927  const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
2928  if (ISD::isNON_EXTLoad(LD) && Cst) {
2929  // Determine any common known bits from the loaded constant pool value.
2930  Type *CstTy = Cst->getType();
2931  if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
2932  // If its a vector splat, then we can (quickly) reuse the scalar path.
2933  // NOTE: We assume all elements match and none are UNDEF.
2934  if (CstTy->isVectorTy()) {
2935  if (const Constant *Splat = Cst->getSplatValue()) {
2936  Cst = Splat;
2937  CstTy = Cst->getType();
2938  }
2939  }
2940  // TODO - do we need to handle different bitwidths?
2941  if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
2942  // Iterate across all vector elements finding common known bits.
2943  Known.One.setAllBits();
2944  Known.Zero.setAllBits();
2945  for (unsigned i = 0; i != NumElts; ++i) {
2946  if (!DemandedElts[i])
2947  continue;
2948  if (Constant *Elt = Cst->getAggregateElement(i)) {
2949  if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
2950  const APInt &Value = CInt->getValue();
2951  Known.One &= Value;
2952  Known.Zero &= ~Value;
2953  continue;
2954  }
2955  if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
2956  APInt Value = CFP->getValueAPF().bitcastToAPInt();
2957  Known.One &= Value;
2958  Known.Zero &= ~Value;
2959  continue;
2960  }
2961  }
2962  Known.One.clearAllBits();
2963  Known.Zero.clearAllBits();
2964  break;
2965  }
2966  } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
2967  if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
2968  const APInt &Value = CInt->getValue();
2969  Known.One = Value;
2970  Known.Zero = ~Value;
2971  } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
2972  APInt Value = CFP->getValueAPF().bitcastToAPInt();
2973  Known.One = Value;
2974  Known.Zero = ~Value;
2975  }
2976  }
2977  }
2978  } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
2979  // If this is a ZEXTLoad and we are looking at the loaded value.
2980  EVT VT = LD->getMemoryVT();
2981  unsigned MemBits = VT.getScalarSizeInBits();
2982  Known.Zero.setBitsFrom(MemBits);
2983  } else if (const MDNode *Ranges = LD->getRanges()) {
2984  if (LD->getExtensionType() == ISD::NON_EXTLOAD)
2985  computeKnownBitsFromRangeMetadata(*Ranges, Known);
2986  }
2987  break;
2988  }
2990  EVT InVT = Op.getOperand(0).getValueType();
2991  APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
2992  Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
2993  Known = Known.zext(BitWidth, true /* ExtendedBitsAreKnownZero */);
2994  break;
2995  }
2996  case ISD::ZERO_EXTEND: {
2997  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2998  Known = Known.zext(BitWidth, true /* ExtendedBitsAreKnownZero */);
2999  break;
3000  }
3002  EVT InVT = Op.getOperand(0).getValueType();
3003  APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3004  Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3005  // If the sign bit is known to be zero or one, then sext will extend
3006  // it to the top bits, else it will just zext.
3007  Known = Known.sext(BitWidth);
3008  break;
3009  }
3010  case ISD::SIGN_EXTEND: {
3011  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3012  // If the sign bit is known to be zero or one, then sext will extend
3013  // it to the top bits, else it will just zext.
3014  Known = Known.sext(BitWidth);
3015  break;
3016  }
3017  case ISD::ANY_EXTEND: {
3018  Known = computeKnownBits(Op.getOperand(0), Depth+1);
3019  Known = Known.zext(BitWidth, false /* ExtendedBitsAreKnownZero */);
3020  break;
3021  }
3022  case ISD::TRUNCATE: {
3023  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3024  Known = Known.trunc(BitWidth);
3025  break;
3026  }
3027  case ISD::AssertZext: {
3028  EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3029  APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3030  Known = computeKnownBits(Op.getOperand(0), Depth+1);
3031  Known.Zero |= (~InMask);
3032  Known.One &= (~Known.Zero);
3033  break;
3034  }
3035  case ISD::FGETSIGN:
3036  // All bits are zero except the low bit.
3037  Known.Zero.setBitsFrom(1);
3038  break;
3039  case ISD::USUBO:
3040  case ISD::SSUBO:
3041  if (Op.getResNo() == 1) {
3042  // If we know the result of a setcc has the top bits zero, use this info.
3043  if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3045  BitWidth > 1)
3046  Known.Zero.setBitsFrom(1);
3047  break;
3048  }
3050  case ISD::SUB:
3051  case ISD::SUBC: {
3052  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3053  Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3054  Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3055  Known, Known2);
3056  break;
3057  }
3058  case ISD::UADDO:
3059  case ISD::SADDO:
3060  case ISD::ADDCARRY:
3061  if (Op.getResNo() == 1) {
3062  // If we know the result of a setcc has the top bits zero, use this info.
3063  if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3065  BitWidth > 1)
3066  Known.Zero.setBitsFrom(1);
3067  break;
3068  }
3070  case ISD::ADD:
3071  case ISD::ADDC:
3072  case ISD::ADDE: {
3073  assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3074 
3075  // With ADDE and ADDCARRY, a carry bit may be added in.
3076  KnownBits Carry(1);
3077  if (Opcode == ISD::ADDE)
3078  // Can't track carry from glue, set carry to unknown.
3079  Carry.resetAll();
3080  else if (Opcode == ISD::ADDCARRY)
3081  // TODO: Compute known bits for the carry operand. Not sure if it is worth
3082  // the trouble (how often will we find a known carry bit). And I haven't
3083  // tested this very much yet, but something like this might work:
3084  // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3085  // Carry = Carry.zextOrTrunc(1, false);
3086  Carry.resetAll();
3087  else
3088  Carry.setAllZero();
3089 
3090  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3091  Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3092  Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3093  break;
3094  }
3095  case ISD::SREM:
3096  if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
3097  const APInt &RA = Rem->getAPIntValue().abs();
3098  if (RA.isPowerOf2()) {
3099  APInt LowBits = RA - 1;
3100  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3101 
3102  // The low bits of the first operand are unchanged by the srem.
3103  Known.Zero = Known2.Zero & LowBits;
3104  Known.One = Known2.One & LowBits;
3105 
3106  // If the first operand is non-negative or has all low bits zero, then
3107  // the upper bits are all zero.
3108  if (Known2.Zero[BitWidth-1] || ((Known2.Zero & LowBits) == LowBits))
3109  Known.Zero |= ~LowBits;
3110 
3111  // If the first operand is negative and not all low bits are zero, then
3112  // the upper bits are all one.
3113  if (Known2.One[BitWidth-1] && ((Known2.One & LowBits) != 0))
3114  Known.One |= ~LowBits;
3115  assert((Known.Zero & Known.One) == 0&&"Bits known to be one AND zero?");
3116  }
3117  }
3118  break;
3119  case ISD::UREM: {
3120  if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
3121  const APInt &RA = Rem->getAPIntValue();
3122  if (RA.isPowerOf2()) {
3123  APInt LowBits = (RA - 1);
3124  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3125 
3126  // The upper bits are all zero, the lower ones are unchanged.
3127  Known.Zero = Known2.Zero | ~LowBits;
3128  Known.One = Known2.One & LowBits;
3129  break;
3130  }
3131  }
3132 
3133  // Since the result is less than or equal to either operand, any leading
3134  // zero bits in either operand must also exist in the result.
3135  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3136  Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3137 
3138  uint32_t Leaders =
3139  std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
3140  Known.resetAll();
3141  Known.Zero.setHighBits(Leaders);
3142  break;
3143  }
3144  case ISD::EXTRACT_ELEMENT: {
3145  Known = computeKnownBits(Op.getOperand(0), Depth+1);
3146  const unsigned Index = Op.getConstantOperandVal(1);
3147  const unsigned EltBitWidth = Op.getValueSizeInBits();
3148 
3149  // Remove low part of known bits mask
3150  Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3151  Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3152 
3153  // Remove high part of known bit mask
3154  Known = Known.trunc(EltBitWidth);
3155  break;
3156  }
3157  case ISD::EXTRACT_VECTOR_ELT: {
3158  SDValue InVec = Op.getOperand(0);
3159  SDValue EltNo = Op.getOperand(1);
3160  EVT VecVT = InVec.getValueType();
3161  const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3162  const unsigned NumSrcElts = VecVT.getVectorNumElements();
3163  // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3164  // anything about the extended bits.
3165  if (BitWidth > EltBitWidth)
3166  Known = Known.trunc(EltBitWidth);
3167  ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3168  if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) {
3169  // If we know the element index, just demand that vector element.
3170  unsigned Idx = ConstEltNo->getZExtValue();
3171  APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
3172  Known = computeKnownBits(InVec, DemandedElt, Depth + 1);
3173  } else {
3174  // Unknown element index, so ignore DemandedElts and demand them all.
3175  Known = computeKnownBits(InVec, Depth + 1);
3176  }
3177  if (BitWidth > EltBitWidth)
3178  Known = Known.zext(BitWidth, false /* => any extend */);
3179  break;
3180  }
3181  case ISD::INSERT_VECTOR_ELT: {
3182  SDValue InVec = Op.getOperand(0);
3183  SDValue InVal = Op.getOperand(1);
3184  SDValue EltNo = Op.getOperand(2);
3185 
3186  ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3187  if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3188  // If we know the element index, split the demand between the
3189  // source vector and the inserted element.
3190  Known.Zero = Known.One = APInt::getAllOnesValue(BitWidth);
3191  unsigned EltIdx = CEltNo->getZExtValue();
3192 
3193  // If we demand the inserted element then add its common known bits.
3194  if (DemandedElts[EltIdx]) {
3195  Known2 = computeKnownBits(InVal, Depth + 1);
3196  Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
3197  Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
3198  }
3199 
3200  // If we demand the source vector then add its common known bits, ensuring
3201  // that we don't demand the inserted element.
3202  APInt VectorElts = DemandedElts & ~(APInt::getOneBitSet(NumElts, EltIdx));
3203  if (!!VectorElts) {
3204  Known2 = computeKnownBits(InVec, VectorElts, Depth + 1);
3205  Known.One &= Known2.One;
3206  Known.Zero &= Known2.Zero;
3207  }
3208  } else {
3209  // Unknown element index, so ignore DemandedElts and demand them all.
3210  Known = computeKnownBits(InVec, Depth + 1);
3211  Known2 = computeKnownBits(InVal, Depth + 1);
3212  Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
3213  Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
3214  }
3215  break;
3216  }
3217  case ISD::BITREVERSE: {
3218  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3219  Known.Zero = Known2.Zero.reverseBits();
3220  Known.One = Known2.One.reverseBits();
3221  break;
3222  }
3223  case ISD::BSWAP: {
3224  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3225  Known.Zero = Known2.Zero.byteSwap();
3226  Known.One = Known2.One.byteSwap();
3227  break;
3228  }
3229  case ISD::ABS: {
3230  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3231 
3232  // If the source's MSB is zero then we know the rest of the bits already.
3233  if (Known2.isNonNegative()) {
3234  Known.Zero = Known2.Zero;
3235  Known.One = Known2.One;
3236  break;
3237  }
3238 
3239  // We only know that the absolute values's MSB will be zero iff there is
3240  // a set bit that isn't the sign bit (otherwise it could be INT_MIN).
3241  Known2.One.clearSignBit();
3242  if (Known2.One.getBoolValue()) {
3243  Known.Zero = APInt::getSignMask(BitWidth);
3244  break;
3245  }
3246  break;
3247  }
3248  case ISD::UMIN: {
3249  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3250  Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3251 
3252  // UMIN - we know that the result will have the maximum of the
3253  // known zero leading bits of the inputs.
3254  unsigned LeadZero = Known.countMinLeadingZeros();
3255  LeadZero = std::max(LeadZero, Known2.countMinLeadingZeros());
3256 
3257  Known.Zero &= Known2.Zero;
3258  Known.One &= Known2.One;
3259  Known.Zero.setHighBits(LeadZero);
3260  break;
3261  }
3262  case ISD::UMAX: {
3263  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3264  Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3265 
3266  // UMAX - we know that the result will have the maximum of the
3267  // known one leading bits of the inputs.
3268  unsigned LeadOne = Known.countMinLeadingOnes();
3269  LeadOne = std::max(LeadOne, Known2.countMinLeadingOnes());
3270 
3271  Known.Zero &= Known2.Zero;
3272  Known.One &= Known2.One;
3273  Known.One.setHighBits(LeadOne);
3274  break;
3275  }
3276  case ISD::SMIN:
3277  case ISD::SMAX: {
3278  // If we have a clamp pattern, we know that the number of sign bits will be
3279  // the minimum of the clamp min/max range.
3280  bool IsMax = (Opcode == ISD::SMAX);
3281  ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3282  if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3283  if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3284  CstHigh =
3285  isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3286  if (CstLow && CstHigh) {
3287  if (!IsMax)
3288  std::swap(CstLow, CstHigh);
3289 
3290  const APInt &ValueLow = CstLow->getAPIntValue();
3291  const APInt &ValueHigh = CstHigh->getAPIntValue();
3292  if (ValueLow.sle(ValueHigh)) {
3293  unsigned LowSignBits = ValueLow.getNumSignBits();
3294  unsigned HighSignBits = ValueHigh.getNumSignBits();
3295  unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3296  if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3297  Known.One.setHighBits(MinSignBits);
3298  break;
3299  }
3300  if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3301  Known.Zero.setHighBits(MinSignBits);
3302  break;
3303  }
3304  }
3305  }
3306 
3307  // Fallback - just get the shared known bits of the operands.
3308  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3309  if (Known.isUnknown()) break; // Early-out
3310  Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3311  Known.Zero &= Known2.Zero;
3312  Known.One &= Known2.One;
3313  break;
3314  }
3315  case ISD::FrameIndex:
3316  case ISD::TargetFrameIndex:
3317  TLI->computeKnownBitsForFrameIndex(Op, Known, DemandedElts, *this, Depth);
3318  break;
3319 
3320  default:
3321  if (Opcode < ISD::BUILTIN_OP_END)
3322  break;
3326  case ISD::INTRINSIC_VOID:
3327  // Allow the target to implement this method for its nodes.
3328  TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3329  break;
3330  }
3331 
3332  assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3333  return Known;
3334 }
3335 
3337  SDValue N1) const {
3338  // X + 0 never overflow
3339  if (isNullConstant(N1))
3340  return OFK_Never;
3341 
3342  KnownBits N1Known = computeKnownBits(N1);
3343  if (N1Known.Zero.getBoolValue()) {
3344  KnownBits N0Known = computeKnownBits(N0);
3345 
3346  bool overflow;
3347  (void)(~N0Known.Zero).uadd_ov(~N1Known.Zero, overflow);
3348  if (!overflow)
3349  return OFK_Never;
3350  }
3351 
3352  // mulhi + 1 never overflow
3353  if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3354  (~N1Known.Zero & 0x01) == ~N1Known.Zero)
3355  return OFK_Never;
3356 
3357  if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3358  KnownBits N0Known = computeKnownBits(N0);
3359 
3360  if ((~N0Known.Zero & 0x01) == ~N0Known.Zero)
3361  return OFK_Never;
3362  }
3363 
3364  return OFK_Sometime;
3365 }
3366 
3368  EVT OpVT = Val.getValueType();
3369  unsigned BitWidth = OpVT.getScalarSizeInBits();
3370 
3371  // Is the constant a known power of 2?
3372  if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3373  return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3374 
3375  // A left-shift of a constant one will have exactly one bit set because
3376  // shifting the bit off the end is undefined.
3377  if (Val.getOpcode() == ISD::SHL) {
3378  auto *C = isConstOrConstSplat(Val.getOperand(0));
3379  if (C && C->getAPIntValue() == 1)
3380  return true;
3381  }
3382 
3383  // Similarly, a logical right-shift of a constant sign-bit will have exactly
3384  // one bit set.
3385  if (Val.getOpcode() == ISD::SRL) {
3386  auto *C = isConstOrConstSplat(Val.getOperand(0));
3387  if (C && C->getAPIntValue().isSignMask())
3388  return true;
3389  }
3390 
3391  // Are all operands of a build vector constant powers of two?
3392  if (Val.getOpcode() == ISD::BUILD_VECTOR)
3393  if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3394  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3395  return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3396  return false;
3397  }))
3398  return true;
3399 
3400  // More could be done here, though the above checks are enough
3401  // to handle some common cases.
3402 
3403  // Fall back to computeKnownBits to catch other known cases.
3404  KnownBits Known = computeKnownBits(Val);
3405  return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3406 }
3407 
3408 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3409  EVT VT = Op.getValueType();
3410  APInt DemandedElts = VT.isVector()
3412  : APInt(1, 1);
3413  return ComputeNumSignBits(Op, DemandedElts, Depth);
3414 }
3415 
3416 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3417  unsigned Depth) const {
3418  EVT VT = Op.getValueType();
3419  assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3420  unsigned VTBits = VT.getScalarSizeInBits();
3421  unsigned NumElts = DemandedElts.getBitWidth();
3422  unsigned Tmp, Tmp2;
3423  unsigned FirstAnswer = 1;
3424 
3425  if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3426  const APInt &Val = C->getAPIntValue();
3427  return Val.getNumSignBits();
3428  }
3429 
3430  if (Depth == 6)
3431  return 1; // Limit search depth.
3432 
3433  if (!DemandedElts)
3434  return 1; // No demanded elts, better to assume we don't know anything.
3435 
3436  unsigned Opcode = Op.getOpcode();
3437  switch (Opcode) {
3438  default: break;
3439  case ISD::AssertSext:
3440  Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3441  return VTBits-Tmp+1;
3442  case ISD::AssertZext:
3443  Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3444  return VTBits-Tmp;
3445 
3446  case ISD::BUILD_VECTOR:
3447  Tmp = VTBits;
3448  for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3449  if (!DemandedElts[i])
3450  continue;
3451 
3452  SDValue SrcOp = Op.getOperand(i);
3453  Tmp2 = ComputeNumSignBits(Op.getOperand(i), Depth + 1);
3454 
3455  // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3456  if (SrcOp.getValueSizeInBits() != VTBits) {
3457  assert(SrcOp.getValueSizeInBits() > VTBits &&
3458  "Expected BUILD_VECTOR implicit truncation");
3459  unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3460  Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3461  }
3462  Tmp = std::min(Tmp, Tmp2);
3463  }
3464  return Tmp;
3465 
3466  case ISD::VECTOR_SHUFFLE: {
3467  // Collect the minimum number of sign bits that are shared by every vector
3468  // element referenced by the shuffle.
3469  APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3470  const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3471  assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3472  for (unsigned i = 0; i != NumElts; ++i) {
3473  int M = SVN->getMaskElt(i);
3474  if (!DemandedElts[i])
3475  continue;
3476  // For UNDEF elements, we don't know anything about the common state of
3477  // the shuffle result.
3478  if (M < 0)
3479  return 1;
3480  if ((unsigned)M < NumElts)
3481  DemandedLHS.setBit((unsigned)M % NumElts);
3482  else
3483  DemandedRHS.setBit((unsigned)M % NumElts);
3484  }
3486  if (!!DemandedLHS)
3487  Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3488  if (!!DemandedRHS) {
3489  Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3490  Tmp = std::min(Tmp, Tmp2);
3491  }
3492  // If we don't know anything, early out and try computeKnownBits fall-back.
3493  if (Tmp == 1)
3494  break;
3495  assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3496  return Tmp;
3497  }
3498 
3499  case ISD::BITCAST: {
3500  SDValue N0 = Op.getOperand(0);
3501  EVT SrcVT = N0.getValueType();
3502  unsigned SrcBits = SrcVT.getScalarSizeInBits();
3503 
3504  // Ignore bitcasts from unsupported types..
3505  if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3506  break;
3507 
3508  // Fast handling of 'identity' bitcasts.
3509  if (VTBits == SrcBits)
3510  return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3511 
3512  bool IsLE = getDataLayout().isLittleEndian();
3513 
3514  // Bitcast 'large element' scalar/vector to 'small element' vector.
3515  if ((SrcBits % VTBits) == 0) {
3516  assert(VT.isVector() && "Expected bitcast to vector");
3517 
3518  unsigned Scale = SrcBits / VTBits;
3519  APInt SrcDemandedElts(NumElts / Scale, 0);
3520  for (unsigned i = 0; i != NumElts; ++i)
3521  if (DemandedElts[i])
3522  SrcDemandedElts.setBit(i / Scale);
3523 
3524  // Fast case - sign splat can be simply split across the small elements.
3525  Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3526  if (Tmp == SrcBits)
3527  return VTBits;
3528 
3529  // Slow case - determine how far the sign extends into each sub-element.
3530  Tmp2 = VTBits;
3531  for (unsigned i = 0; i != NumElts; ++i)
3532  if (DemandedElts[i]) {
3533  unsigned SubOffset = i % Scale;
3534  SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3535  SubOffset = SubOffset * VTBits;
3536  if (Tmp <= SubOffset)
3537  return 1;
3538  Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3539  }
3540  return Tmp2;
3541  }
3542  break;
3543  }
3544 
3545  case ISD::SIGN_EXTEND:
3546  Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3547  return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3549  // Max of the input and what this extends.
3550  Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3551  Tmp = VTBits-Tmp+1;
3552  Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3553  return std::max(Tmp, Tmp2);
3555  SDValue Src = Op.getOperand(0);
3556  EVT SrcVT = Src.getValueType();
3557  APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3558  Tmp = VTBits - SrcVT.getScalarSizeInBits();
3559  return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3560  }
3561 
3562  case ISD::SRA:
3563  Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3564  // SRA X, C -> adds C sign bits.
3565  if (ConstantSDNode *C =
3566  isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3567  APInt ShiftVal = C->getAPIntValue();
3568  ShiftVal += Tmp;
3569  Tmp = ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
3570  }
3571  return Tmp;
3572  case ISD::SHL:
3573  if (ConstantSDNode *C =
3574  isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3575  // shl destroys sign bits.
3576  Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3577  if (C->getAPIntValue().uge(VTBits) || // Bad shift.
3578  C->getAPIntValue().uge(Tmp)) break; // Shifted all sign bits out.
3579  return Tmp - C->getZExtValue();
3580  }
3581  break;
3582  case ISD::AND:
3583  case ISD::OR:
3584  case ISD::XOR: // NOT is handled here.
3585  // Logical binary ops preserve the number of sign bits at the worst.
3586  Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3587  if (Tmp != 1) {
3588  Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3589  FirstAnswer = std::min(Tmp, Tmp2);
3590  // We computed what we know about the sign bits as our first
3591  // answer. Now proceed to the generic code that uses
3592  // computeKnownBits, and pick whichever answer is better.
3593  }
3594  break;
3595 
3596  case ISD::SELECT:
3597  case ISD::VSELECT:
3598  Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3599  if (Tmp == 1) return 1; // Early out.
3600  Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3601  return std::min(Tmp, Tmp2);
3602  case ISD::SELECT_CC:
3603  Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3604  if (Tmp == 1) return 1; // Early out.
3605  Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3606  return std::min(Tmp, Tmp2);
3607 
3608  case ISD::SMIN:
3609  case ISD::SMAX: {
3610  // If we have a clamp pattern, we know that the number of sign bits will be
3611  // the minimum of the clamp min/max range.
3612  bool IsMax = (Opcode == ISD::SMAX);
3613  ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3614  if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3615  if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3616  CstHigh =
3617  isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3618  if (CstLow && CstHigh) {
3619  if (!IsMax)
3620  std::swap(CstLow, CstHigh);
3621  if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3622  Tmp = CstLow->getAPIntValue().getNumSignBits();
3623  Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3624  return std::min(Tmp, Tmp2);
3625  }
3626  }
3627 
3628  // Fallback - just get the minimum number of sign bits of the operands.
3629  Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3630  if (Tmp == 1)
3631  return 1; // Early out.
3632  Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3633  return std::min(Tmp, Tmp2);
3634  }
3635  case ISD::UMIN:
3636  case ISD::UMAX:
3637  Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3638  if (Tmp == 1)
3639  return 1; // Early out.
3640  Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3641  return std::min(Tmp, Tmp2);
3642  case ISD::SADDO:
3643  case ISD::UADDO:
3644  case ISD::SSUBO:
3645  case ISD::USUBO:
3646  case ISD::SMULO:
3647  case ISD::UMULO:
3648  if (Op.getResNo() != 1)
3649  break;
3650  // The boolean result conforms to getBooleanContents. Fall through.
3651  // If setcc returns 0/-1, all bits are sign bits.
3652  // We know that we have an integer-based boolean since these operations
3653  // are only available for integer.
3654  if (TLI->getBooleanContents(VT.isVector(), false) ==
3656  return VTBits;
3657  break;
3658  case ISD::SETCC:
3659  // If setcc returns 0/-1, all bits are sign bits.
3660  if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3662  return VTBits;
3663  break;
3664  case ISD::ROTL:
3665  case ISD::ROTR:
3666  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3667  unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3668 
3669  // Handle rotate right by N like a rotate left by 32-N.
3670  if (Opcode == ISD::ROTR)
3671  RotAmt = (VTBits - RotAmt) % VTBits;
3672 
3673  // If we aren't rotating out all of the known-in sign bits, return the
3674  // number that are left. This handles rotl(sext(x), 1) for example.
3675  Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3676  if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3677  }
3678  break;
3679  case ISD::ADD:
3680  case ISD::ADDC:
3681  // Add can have at most one carry bit. Thus we know that the output
3682  // is, at worst, one more bit than the inputs.
3683  Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3684  if (Tmp == 1) return 1; // Early out.
3685 
3686  // Special case decrementing a value (ADD X, -1):
3687  if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3688  if (CRHS->isAllOnesValue()) {
3689  KnownBits Known = computeKnownBits(Op.getOperand(0), Depth+1);
3690 
3691  // If the input is known to be 0 or 1, the output is 0/-1, which is all
3692  // sign bits set.
3693  if ((Known.Zero | 1).isAllOnesValue())
3694  return VTBits;
3695 
3696  // If we are subtracting one from a positive number, there is no carry
3697  // out of the result.
3698  if (Known.isNonNegative())
3699  return Tmp;
3700  }
3701 
3702  Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3703  if (Tmp2 == 1) return 1;
3704  return std::min(Tmp, Tmp2)-1;
3705 
3706  case ISD::SUB:
3707  Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3708  if (Tmp2 == 1) return 1;
3709 
3710  // Handle NEG.
3711  if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0)))
3712  if (CLHS->isNullValue()) {
3713  KnownBits Known = computeKnownBits(Op.getOperand(1), Depth+1);
3714  // If the input is known to be 0 or 1, the output is 0/-1, which is all
3715  // sign bits set.
3716  if ((Known.Zero | 1).isAllOnesValue())
3717  return VTBits;
3718 
3719  // If the input is known to be positive (the sign bit is known clear),
3720  // the output of the NEG has the same number of sign bits as the input.
3721  if (Known.isNonNegative())
3722  return Tmp2;
3723 
3724  // Otherwise, we treat this like a SUB.
3725  }
3726 
3727  // Sub can have at most one carry bit. Thus we know that the output
3728  // is, at worst, one more bit than the inputs.
3729  Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3730  if (Tmp == 1) return 1; // Early out.
3731  return std::min(Tmp, Tmp2)-1;
3732  case ISD::TRUNCATE: {
3733  // Check if the sign bits of source go down as far as the truncated value.
3734  unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3735  unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3736  if (NumSrcSignBits > (NumSrcBits - VTBits))
3737  return NumSrcSignBits - (NumSrcBits - VTBits);
3738  break;
3739  }
3740  case ISD::EXTRACT_ELEMENT: {
3741  const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3742  const int BitWidth = Op.getValueSizeInBits();
3743  const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3744 
3745  // Get reverse index (starting from 1), Op1 value indexes elements from
3746  // little end. Sign starts at big end.
3747  const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3748 
3749  // If the sign portion ends in our element the subtraction gives correct
3750  // result. Otherwise it gives either negative or > bitwidth result
3751  return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3752  }
3753  case ISD::INSERT_VECTOR_ELT: {
3754  SDValue InVec = Op.getOperand(0);
3755  SDValue InVal = Op.getOperand(1);
3756  SDValue EltNo = Op.getOperand(2);
3757 
3758  ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3759  if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3760  // If we know the element index, split the demand between the
3761  // source vector and the inserted element.
3762  unsigned EltIdx = CEltNo->getZExtValue();
3763 
3764  // If we demand the inserted element then get its sign bits.
3766  if (DemandedElts[EltIdx]) {
3767  // TODO - handle implicit truncation of inserted elements.
3768  if (InVal.getScalarValueSizeInBits() != VTBits)
3769  break;
3770  Tmp = ComputeNumSignBits(InVal, Depth + 1);
3771  }
3772 
3773  // If we demand the source vector then get its sign bits, and determine
3774  // the minimum.
3775  APInt VectorElts = DemandedElts;
3776  VectorElts.clearBit(EltIdx);
3777  if (!!VectorElts) {
3778  Tmp2 = ComputeNumSignBits(InVec, VectorElts, Depth + 1);
3779  Tmp = std::min(Tmp, Tmp2);
3780  }
3781  } else {
3782  // Unknown element index, so ignore DemandedElts and demand them all.
3783  Tmp = ComputeNumSignBits(InVec, Depth + 1);
3784  Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
3785  Tmp = std::min(Tmp, Tmp2);
3786  }
3787  assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3788  return Tmp;
3789  }
3790  case ISD::EXTRACT_VECTOR_ELT: {
3791  SDValue InVec = Op.getOperand(0);
3792  SDValue EltNo = Op.getOperand(1);
3793  EVT VecVT = InVec.getValueType();
3794  const unsigned BitWidth = Op.getValueSizeInBits();
3795  const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
3796  const unsigned NumSrcElts = VecVT.getVectorNumElements();
3797 
3798  // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
3799  // anything about sign bits. But if the sizes match we can derive knowledge
3800  // about sign bits from the vector operand.
3801  if (BitWidth != EltBitWidth)
3802  break;
3803 
3804  // If we know the element index, just demand that vector element, else for
3805  // an unknown element index, ignore DemandedElts and demand them all.
3806  APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3807  ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3808  if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3809  DemandedSrcElts =
3810  APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3811 
3812  return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
3813  }
3814  case ISD::EXTRACT_SUBVECTOR: {
3815  // If we know the element index, just demand that subvector elements,
3816  // otherwise demand them all.
3817  SDValue Src = Op.getOperand(0);
3819  unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3820  if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
3821  // Offset the demanded elts by the subvector index.
3822  uint64_t Idx = SubIdx->getZExtValue();
3823  APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
3824  return ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
3825  }
3826  return ComputeNumSignBits(Src, Depth + 1);
3827  }
3828  case ISD::CONCAT_VECTORS: {
3829  // Determine the minimum number of sign bits across all demanded
3830  // elts of the input vectors. Early out if the result is already 1.
3832  EVT SubVectorVT = Op.getOperand(0).getValueType();
3833  unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3834  unsigned NumSubVectors = Op.getNumOperands();
3835  for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
3836  APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
3837  DemandedSub = DemandedSub.trunc(NumSubVectorElts);
3838  if (!DemandedSub)
3839  continue;
3840  Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
3841  Tmp = std::min(Tmp, Tmp2);
3842  }
3843  assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3844  return Tmp;
3845  }
3846  case ISD::INSERT_SUBVECTOR: {
3847  // If we know the element index, demand any elements from the subvector and
3848  // the remainder from the src its inserted into, otherwise demand them all.
3849  SDValue Src = Op.getOperand(0);
3850  SDValue Sub = Op.getOperand(1);
3851  auto *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3852  unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3853  if (SubIdx && SubIdx->getAPIntValue().ule(NumElts - NumSubElts)) {
3855  uint64_t Idx = SubIdx->getZExtValue();
3856  APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3857  if (!!DemandedSubElts) {
3858  Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
3859  if (Tmp == 1) return 1; // early-out
3860  }
3861  APInt SubMask = APInt::getBitsSet(NumElts, Idx, Idx + NumSubElts);
3862  APInt DemandedSrcElts = DemandedElts & ~SubMask;
3863  if (!!DemandedSrcElts) {
3864  Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
3865  Tmp = std::min(Tmp, Tmp2);
3866  }
3867  assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3868  return Tmp;
3869  }
3870 
3871  // Not able to determine the index so just assume worst case.
3872  Tmp = ComputeNumSignBits(Sub, Depth + 1);
3873  if (Tmp == 1) return 1; // early-out
3874  Tmp2 = ComputeNumSignBits(Src, Depth + 1);
3875  Tmp = std::min(Tmp, Tmp2);
3876  assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3877  return Tmp;
3878  }
3879  }
3880 
3881  // If we are looking at the loaded value of the SDNode.
3882  if (Op.getResNo() == 0) {
3883  // Handle LOADX separately here. EXTLOAD case will fallthrough.
3884  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
3885  unsigned ExtType = LD->getExtensionType();
3886  switch (ExtType) {
3887  default: break;
3888  case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
3889  Tmp = LD->getMemoryVT().getScalarSizeInBits();
3890  return VTBits - Tmp + 1;
3891  case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
3892  Tmp = LD->getMemoryVT().getScalarSizeInBits();
3893  return VTBits - Tmp;
3894  case ISD::NON_EXTLOAD:
3895  if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
3896  // We only need to handle vectors - computeKnownBits should handle
3897  // scalar cases.
3898  Type *CstTy = Cst->getType();
3899  if (CstTy->isVectorTy() &&
3900  (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
3901  Tmp = VTBits;
3902  for (unsigned i = 0; i != NumElts; ++i) {
3903  if (!DemandedElts[i])
3904  continue;
3905  if (Constant *Elt = Cst->getAggregateElement(i)) {
3906  if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3907  const APInt &Value = CInt->getValue();
3908  Tmp = std::min(Tmp, Value.getNumSignBits());
3909  continue;
3910  }
3911  if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3912  APInt Value = CFP->getValueAPF().bitcastToAPInt();
3913  Tmp = std::min(Tmp, Value.getNumSignBits());
3914  continue;
3915  }
3916  }
3917  // Unknown type. Conservatively assume no bits match sign bit.
3918  return 1;
3919  }
3920  return Tmp;
3921  }
3922  }
3923  break;
3924  }
3925  }
3926  }
3927 
3928  // Allow the target to implement this method for its nodes.
3929  if (Opcode >= ISD::BUILTIN_OP_END ||
3930  Opcode == ISD::INTRINSIC_WO_CHAIN ||
3931  Opcode == ISD::INTRINSIC_W_CHAIN ||
3932  Opcode == ISD::INTRINSIC_VOID) {
3933  unsigned NumBits =
3934  TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
3935  if (NumBits > 1)
3936  FirstAnswer = std::max(FirstAnswer, NumBits);
3937  }
3938 
3939  // Finally, if we can prove that the top bits of the result are 0's or 1's,
3940  // use this information.
3941  KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
3942 
3943  APInt Mask;
3944  if (Known.isNonNegative()) { // sign bit is 0
3945  Mask = Known.Zero;
3946  } else if (Known.isNegative()) { // sign bit is 1;
3947  Mask = Known.One;
3948  } else {
3949  // Nothing known.
3950  return FirstAnswer;
3951  }
3952 
3953  // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
3954  // the number of identical bits in the top of the input value.
3955  Mask = ~Mask;
3956  Mask <<= Mask.getBitWidth()-VTBits;
3957  // Return # leading zeros. We use 'min' here in case Val was zero before
3958  // shifting. We don't want to return '64' as for an i32 "0".
3959  return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
3960 }
3961 
3963  if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
3964  !isa<ConstantSDNode>(Op.getOperand(1)))
3965  return false;
3966 
3967  if (Op.getOpcode() == ISD::OR &&
3969  return false;
3970 
3971  return true;
3972 }
3973 
3974 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
3975  // If we're told that NaNs won't happen, assume they won't.
3976  if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
3977  return true;
3978 
3979  if (Depth == 6)
3980  return false; // Limit search depth.
3981 
3982  // TODO: Handle vectors.
3983  // If the value is a constant, we can obviously see if it is a NaN or not.
3984  if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
3985  return !C->getValueAPF().isNaN() ||
3986  (SNaN && !C->getValueAPF().isSignaling());
3987  }
3988 
3989  unsigned Opcode = Op.getOpcode();
3990  switch (Opcode) {
3991  case ISD::FADD:
3992  case ISD::FSUB:
3993  case ISD::FMUL:
3994  case ISD::FDIV:
3995  case ISD::FREM:
3996  case ISD::FSIN:
3997  case ISD::FCOS: {
3998  if (SNaN)
3999  return true;
4000  // TODO: Need isKnownNeverInfinity
4001  return false;
4002  }
4003  case ISD::FCANONICALIZE:
4004  case ISD::FEXP:
4005  case ISD::FEXP2:
4006  case ISD::FTRUNC:
4007  case ISD::FFLOOR:
4008  case ISD::FCEIL:
4009  case ISD::FROUND:
4010  case ISD::FRINT:
4011  case ISD::FNEARBYINT: {
4012  if (SNaN)
4013  return true;
4014  return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4015  }
4016  case ISD::FABS:
4017  case ISD::FNEG:
4018  case ISD::FCOPYSIGN: {
4019  return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4020  }
4021  case ISD::SELECT:
4022  return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4023  isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4024  case ISD::FP_EXTEND:
4025  case ISD::FP_ROUND: {
4026  if (SNaN)
4027  return true;
4028  return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4029  }
4030  case ISD::SINT_TO_FP:
4031  case ISD::UINT_TO_FP:
4032  return true;
4033  case ISD::FMA:
4034  case ISD::FMAD: {
4035  if (SNaN)
4036  return true;
4037  return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4038  isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4039  isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4040  }
4041  case ISD::FSQRT: // Need is known positive
4042  case ISD::FLOG:
4043  case ISD::FLOG2:
4044  case ISD::FLOG10:
4045  case ISD::FPOWI:
4046  case ISD::FPOW: {
4047  if (SNaN)
4048  return true;
4049  // TODO: Refine on operand
4050  return false;
4051  }
4052  case ISD::FMINNUM:
4053  case ISD::FMAXNUM: {
4054  // Only one needs to be known not-nan, since it will be returned if the
4055  // other ends up being one.
4056  return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4057  isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4058  }
4059  case ISD::FMINNUM_IEEE:
4060  case ISD::FMAXNUM_IEEE: {
4061  if (SNaN)
4062  return true;
4063  // This can return a NaN if either operand is an sNaN, or if both operands
4064  // are NaN.
4065  return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4066  isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4067  (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4068  isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4069  }
4070  case ISD::FMINIMUM:
4071  case ISD::FMAXIMUM: {
4072  // TODO: Does this quiet or return the origina NaN as-is?
4073  return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4074  isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4075  }
4076  case ISD::EXTRACT_VECTOR_ELT: {
4077  return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4078  }
4079  default:
4080  if (Opcode >= ISD::BUILTIN_OP_END ||
4081  Opcode == ISD::INTRINSIC_WO_CHAIN ||
4082  Opcode == ISD::INTRINSIC_W_CHAIN ||
4083  Opcode == ISD::INTRINSIC_VOID) {
4084  return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4085  }
4086 
4087  return false;
4088  }
4089 }
4090 
4093  "Floating point type expected");
4094 
4095  // If the value is a constant, we can obviously see if it is a zero or not.
4096  // TODO: Add BuildVector support.
4097  if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4098  return !C->isZero();
4099  return false;
4100 }
4101 
4104  "Floating point types unsupported - use isKnownNeverZeroFloat");
4105 
4106  // If the value is a constant, we can obviously see if it is a zero or not.
4108  Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
4109  return true;
4110 
4111  // TODO: Recognize more cases here.
4112  switch (Op.getOpcode()) {
4113  default: break;
4114  case ISD::OR:
4115  if (isKnownNeverZero(Op.getOperand(1)) ||
4117  return true;
4118  break;
4119  }
4120 
4121  return false;
4122 }
4123 
4125  // Check the obvious case.
4126  if (A == B) return true;
4127 
4128  // For for negative and positive zero.
4129  if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4130  if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4131  if (CA->isZero() && CB->isZero()) return true;
4132 
4133  // Otherwise they may not be equal.
4134  return false;
4135 }
4136 
4137 // FIXME: unify with llvm::haveNoCommonBitsSet.
4138 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4140  assert(A.getValueType() == B.getValueType() &&
4141  "Values must have the same type");
4142  return (computeKnownBits(A).Zero | computeKnownBits(B).Zero).isAllOnesValue();
4143 }
4144 
4145 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4146  ArrayRef<SDValue> Ops,
4147  SelectionDAG &DAG) {
4148  int NumOps = Ops.size();
4149  assert(NumOps != 0 && "Can't build an empty vector!");
4150  assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4151  "Incorrect element count in BUILD_VECTOR!");
4152 
4153  // BUILD_VECTOR of UNDEFs is UNDEF.
4154  if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4155  return DAG.getUNDEF(VT);
4156 
4157  // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4158  SDValue IdentitySrc;
4159  bool IsIdentity = true;
4160  for (int i = 0; i != NumOps; ++i) {
4161  if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4162  Ops[i].getOperand(0).getValueType() != VT ||
4163  (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4164  !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4165  cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4166  IsIdentity = false;
4167  break;
4168  }
4169  IdentitySrc = Ops[i].getOperand(0);
4170  }
4171  if (IsIdentity)
4172  return IdentitySrc;
4173 
4174  return SDValue();
4175 }
4176 
4177 /// Try to simplify vector concatenation to an input value, undef, or build
4178 /// vector.
4179 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4180  ArrayRef<SDValue> Ops,
4181  SelectionDAG &DAG) {
4182  assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4183  assert(llvm::all_of(Ops,
4184  [Ops](SDValue Op) {
4185  return Ops[0].getValueType() == Op.getValueType();
4186  }) &&
4187  "Concatenation of vectors with inconsistent value types!");
4188  assert((Ops.size() * Ops[0].getValueType().getVectorNumElements()) ==
4189  VT.getVectorNumElements() &&
4190  "Incorrect element count in vector concatenation!");
4191 
4192  if (Ops.size() == 1)
4193  return Ops[0];
4194 
4195  // Concat of UNDEFs is UNDEF.
4196  if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4197  return DAG.getUNDEF(VT);
4198 
4199  // Scan the operands and look for extract operations from a single source
4200  // that correspond to insertion at the same location via this concatenation:
4201  // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4202  SDValue IdentitySrc;
4203  bool IsIdentity = true;
4204  for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4205  SDValue Op = Ops[i];
4206  unsigned IdentityIndex = i * Op.getValueType().getVectorNumElements();
4207  if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4208  Op.getOperand(0).getValueType() != VT ||
4209  (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4210  !isa<ConstantSDNode>(Op.getOperand(1)) ||
4211  Op.getConstantOperandVal(1) != IdentityIndex) {
4212  IsIdentity = false;
4213  break;
4214  }
4215  assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4216  "Unexpected identity source vector for concat of extracts");
4217  IdentitySrc = Op.getOperand(0);
4218  }
4219  if (IsIdentity) {
4220  assert(IdentitySrc && "Failed to set source vector of extracts");
4221  return IdentitySrc;
4222  }
4223 
4224  // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4225  // simplified to one big BUILD_VECTOR.
4226  // FIXME: Add support for SCALAR_TO_VECTOR as well.
4227  EVT SVT = VT.getScalarType();
4229  for (SDValue Op : Ops) {
4230  EVT OpVT = Op.getValueType();
4231  if (Op.isUndef())
4232  Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4233  else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4234  Elts.append(Op->op_begin(), Op->op_end());
4235  else
4236  return SDValue();
4237  }
4238 
4239  // BUILD_VECTOR requires all inputs to be of the same type, find the
4240  // maximum type and extend them all.
4241  for (SDValue Op : Elts)
4242  SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4243 
4244  if (SVT.bitsGT(VT.getScalarType()))
4245  for (SDValue &Op : Elts)
4246  Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4247  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4248  : DAG.getSExtOrTrunc(Op, DL, SVT);
4249 
4250  SDValue V = DAG.getBuildVector(VT, DL, Elts);
4251  NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4252  return V;
4253 }
4254 
4255 /// Gets or creates the specified node.
4256 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4258  AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4259  void *IP = nullptr;
4260  if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4261  return SDValue(E, 0);
4262 
4263  auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4264  getVTList(VT));
4265  CSEMap.InsertNode(N, IP);
4266 
4267  InsertNode(N);
4268  SDValue V = SDValue(N, 0);
4269  NewSDValueDbgMsg(V, "Creating new node: ", this);
4270  return V;
4271 }
4272 
4273 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4274  SDValue Operand, const SDNodeFlags Flags) {
4275  // Constant fold unary operations with an integer constant operand. Even
4276  // opaque constant will be folded, because the folding of unary operations
4277  // doesn't create new constants with different values. Nevertheless, the
4278  // opaque flag is preserved during folding to prevent future folding with
4279  // other constants.
4280  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4281  const APInt &Val = C->getAPIntValue();
4282  switch (Opcode) {
4283  default: break;
4284  case ISD::SIGN_EXTEND:
4285  return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4286  C->isTargetOpcode(), C->isOpaque());
4287  case ISD::TRUNCATE:
4288  if (C->isOpaque())
4289  break;
4291  case ISD::ANY_EXTEND:
4292  case ISD::ZERO_EXTEND:
4293  return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4294  C->isTargetOpcode(), C->isOpaque());
4295  case ISD::UINT_TO_FP:
4296  case ISD::SINT_TO_FP: {
4299  (void)apf.convertFromAPInt(Val,
4300  Opcode==ISD::SINT_TO_FP,
4302  return getConstantFP(apf, DL, VT);
4303  }
4304  case ISD::BITCAST:
4305  if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4306  return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4307  if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4308  return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4309  if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4310  return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4311  if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4312  return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4313  break;
4314  case ISD::ABS:
4315  return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4316  C->isOpaque());
4317  case ISD::BITREVERSE:
4318  return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4319  C->isOpaque());
4320  case ISD::BSWAP:
4321  return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4322  C->isOpaque());
4323  case ISD::CTPOP:
4324  return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4325  C->isOpaque());
4326  case ISD::CTLZ:
4327  case ISD::CTLZ_ZERO_UNDEF:
4328  return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4329  C->isOpaque());
4330  case ISD::CTTZ:
4331  case ISD::CTTZ_ZERO_UNDEF:
4332  return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4333  C->isOpaque());
4334  case ISD::FP16_TO_FP: {
4335  bool Ignored;
4336  APFloat FPV(APFloat::IEEEhalf(),
4337  (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4338 
4339  // This can return overflow, underflow, or inexact; we don't care.
4340  // FIXME need to be more flexible about rounding mode.
4341  (void)FPV.convert(EVTToAPFloatSemantics(VT),
4342  APFloat::rmNearestTiesToEven, &Ignored);
4343  return getConstantFP(FPV, DL, VT);
4344  }
4345  }
4346  }
4347 
4348  // Constant fold unary operations with a floating point constant operand.
4349  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4350  APFloat V = C->getValueAPF(); // make copy
4351  switch (Opcode) {
4352  case ISD::FNEG:
4353  V.changeSign();
4354  return getConstantFP(V, DL, VT);
4355  case ISD::FABS:
4356  V.clearSign();
4357  return getConstantFP(V, DL, VT);
4358  case ISD::FCEIL: {
4360  if (fs == APFloat::opOK || fs == APFloat::opInexact)
4361  return getConstantFP(V, DL, VT);
4362  break;
4363  }
4364  case ISD::FTRUNC: {
4366  if (fs == APFloat::opOK || fs == APFloat::opInexact)
4367  return getConstantFP(V, DL, VT);
4368  break;
4369  }
4370  case ISD::FFLOOR: {
4372  if (fs == APFloat::opOK || fs == APFloat::opInexact)
4373  return getConstantFP(V, DL, VT);
4374  break;
4375  }
4376  case ISD::FP_EXTEND: {
4377  bool ignored;
4378  // This can return overflow, underflow, or inexact; we don't care.
4379  // FIXME need to be more flexible about rounding mode.
4380  (void)V.convert(EVTToAPFloatSemantics(VT),
4381  APFloat::rmNearestTiesToEven, &ignored);
4382  return getConstantFP(V, DL, VT);
4383  }
4384  case ISD::FP_TO_SINT:
4385  case ISD::FP_TO_UINT: {
4386  bool ignored;
4387  APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4388  // FIXME need to be more flexible about rounding mode.
4389  APFloat::opStatus s =
4391  if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4392  break;
4393  return getConstant(IntVal, DL, VT);
4394  }
4395  case ISD::BITCAST:
4396  if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4397  return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4398  else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4399  return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4400  else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4401  return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4402  break;
4403  case ISD::FP_TO_FP16: {
4404  bool Ignored;
4405  // This can return overflow, underflow, or inexact; we don't care.
4406  // FIXME need to be more flexible about rounding mode.
4407  (void)V.convert(APFloat::IEEEhalf(),
4408  APFloat::rmNearestTiesToEven, &Ignored);
4409  return getConstant(V.bitcastToAPInt(), DL, VT);
4410  }
4411  }
4412  }
4413 
4414  // Constant fold unary operations with a vector integer or float operand.
4415  if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
4416  if (BV->isConstant()) {
4417  switch (Opcode) {
4418  default:
4419  // FIXME: Entirely reasonable to perform folding of other unary
4420  // operations here as the need arises.
4421  break;
4422  case ISD::FNEG:
4423  case ISD::FABS:
4424  case ISD::FCEIL:
4425  case ISD::FTRUNC:
4426  case ISD::FFLOOR:
4427  case ISD::FP_EXTEND:
4428  case ISD::FP_TO_SINT:
4429  case ISD::FP_TO_UINT:
4430  case ISD::TRUNCATE:
4431  case ISD::ANY_EXTEND:
4432  case ISD::ZERO_EXTEND:
4433  case ISD::SIGN_EXTEND:
4434  case ISD::UINT_TO_FP:
4435  case ISD::SINT_TO_FP:
4436  case ISD::ABS:
4437  case ISD::BITREVERSE:
4438  case ISD::BSWAP:
4439  case ISD::CTLZ:
4440  case ISD::CTLZ_ZERO_UNDEF:
4441  case ISD::CTTZ:
4442  case ISD::CTTZ_ZERO_UNDEF:
4443  case ISD::CTPOP: {
4444  SDValue Ops = { Operand };
4445  if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4446  return Fold;
4447  }
4448  }
4449  }
4450  }
4451 
4452  unsigned OpOpcode = Operand.getNode()->getOpcode();
4453  switch (Opcode) {
4454  case ISD::TokenFactor:
4455  case ISD::MERGE_VALUES:
4456  case ISD::CONCAT_VECTORS:
4457  return Operand; // Factor, merge or concat of one node? No need.
4458  case ISD::BUILD_VECTOR: {
4459  // Attempt to simplify BUILD_VECTOR.
4460  SDValue Ops[] = {Operand};
4461  if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4462  return V;
4463  break;
4464  }
4465  case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4466  case ISD::FP_EXTEND:
4467  assert(VT.isFloatingPoint() &&
4468  Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4469  if (Operand.getValueType() == VT) return Operand; // noop conversion.
4470  assert((!VT.isVector() ||
4471  VT.getVectorNumElements() ==
4472  Operand.getValueType().getVectorNumElements()) &&
4473  "Vector element count mismatch!");
4474  assert(Operand.getValueType().bitsLT(VT) &&
4475  "Invalid fpext node, dst < src!");
4476  if (Operand.isUndef())
4477  return getUNDEF(VT);
4478  break;
4479  case ISD::FP_TO_SINT:
4480  case ISD::FP_TO_UINT:
4481  if (Operand.isUndef())
4482  return getUNDEF(VT);
4483  break;
4484  case ISD::SINT_TO_FP:
4485  case ISD::UINT_TO_FP:
4486  // [us]itofp(undef) = 0, because the result value is bounded.
4487  if (Operand.isUndef())
4488  return getConstantFP(0.0, DL, VT);
4489  break;
4490  case ISD::SIGN_EXTEND:
4491  assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4492  "Invalid SIGN_EXTEND!");
4493  assert(VT.isVector() == Operand.getValueType().isVector() &&
4494  "SIGN_EXTEND result type type should be vector iff the operand "
4495  "type is vector!");
4496  if (Operand.getValueType() == VT) return Operand; // noop extension
4497  assert((!VT.isVector() ||
4498  VT.getVectorNumElements() ==
4499  Operand.getValueType().getVectorNumElements()) &&
4500  "Vector element count mismatch!");
4501  assert(Operand.getValueType().bitsLT(VT) &&
4502  "Invalid sext node, dst < src!");
4503  if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4504  return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4505  else if (OpOpcode == ISD::UNDEF)
4506  // sext(undef) = 0, because the top bits will all be the same.
4507  return getConstant(0, DL, VT);
4508  break;
4509  case ISD::ZERO_EXTEND:
4510  assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4511  "Invalid ZERO_EXTEND!");
4512  assert(VT.isVector() == Operand.getValueType().isVector() &&
4513  "ZERO_EXTEND result type type should be vector iff the operand "
4514  "type is vector!");
4515  if (Operand.getValueType() == VT) return Operand; // noop extension
4516  assert((!VT.isVector() ||
4517  VT.getVectorNumElements() ==
4518  Operand.getValueType().getVectorNumElements()) &&
4519  "Vector element count mismatch!");
4520  assert(Operand.getValueType().bitsLT(VT) &&
4521  "Invalid zext node, dst < src!");
4522  if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
4523  return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4524  else if (OpOpcode == ISD::UNDEF)
4525  // zext(undef) = 0, because the top bits will be zero.
4526  return getConstant(0, DL, VT);
4527  break;
4528  case ISD::ANY_EXTEND:
4529  assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4530  "Invalid ANY_EXTEND!");
4531  assert(VT.isVector() == Operand.getValueType().isVector() &&
4532  "ANY_EXTEND result type type should be vector iff the operand "
4533  "type is vector!");
4534  if (Operand.getValueType() == VT) return Operand; // noop extension
4535  assert((!VT.isVector() ||
4536  VT.getVectorNumElements() ==
4537  Operand.getValueType().getVectorNumElements()) &&
4538  "Vector element count mismatch!");
4539  assert(Operand.getValueType().bitsLT(VT) &&
4540  "Invalid anyext node, dst < src!");
4541 
4542  if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4543  OpOpcode == ISD::ANY_EXTEND)
4544  // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
4545  return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4546  else if (OpOpcode == ISD::UNDEF)
4547  return getUNDEF(VT);
4548 
4549  // (ext (trunc x)) -> x
4550  if (OpOpcode == ISD::TRUNCATE) {
4551  SDValue OpOp = Operand.getOperand(0);
4552  if (OpOp.getValueType() == VT) {
4553  transferDbgValues(Operand, OpOp);
4554  return OpOp;
4555  }
4556  }
4557  break;
4558  case ISD::TRUNCATE:
4559  assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4560  "Invalid TRUNCATE!");
4561  assert(VT.isVector() == Operand.getValueType().isVector() &&
4562  "TRUNCATE result type type should be vector iff the operand "
4563  "type is vector!");
4564  if (Operand.getValueType() == VT) return Operand; // noop truncate
4565  assert((!VT.isVector() ||
4566  VT.getVectorNumElements() ==
4567  Operand.getValueType().getVectorNumElements()) &&
4568  "Vector element count mismatch!");
4569  assert(Operand.getValueType().bitsGT(VT) &&
4570  "Invalid truncate node, src < dst!");
4571  if (OpOpcode == ISD::TRUNCATE)
4572  return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4573  if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4574  OpOpcode == ISD::ANY_EXTEND) {
4575  // If the source is smaller than the dest, we still need an extend.
4576  if (Operand.getOperand(0).getValueType().getScalarType()
4577  .bitsLT(VT.getScalarType()))
4578  return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4579  if (Operand.getOperand(0).getValueType().bitsGT(VT))
4580  return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4581  return Operand.getOperand(0);
4582  }
4583  if (OpOpcode == ISD::UNDEF)
4584  return getUNDEF(VT);
4585  break;
4589  assert(VT.isVector() && "This DAG node is restricted to vector types.");
4590  assert(Operand.getValueType().bitsLE(VT) &&
4591  "The input must be the same size or smaller than the result.");
4593  Operand.getValueType().getVectorNumElements() &&
4594  "The destination vector type must have fewer lanes than the input.");
4595  break;
4596  case ISD::ABS:
4597  assert(VT.isInteger() && VT == Operand.getValueType() &&
4598  "Invalid ABS!");
4599  if (OpOpcode == ISD::UNDEF)
4600  return getUNDEF(VT);
4601  break;
4602  case ISD::BSWAP:
4603  assert(VT.isInteger() && VT == Operand.getValueType() &&
4604  "Invalid BSWAP!");
4605  assert((VT.getScalarSizeInBits() % 16 == 0) &&
4606  "BSWAP types must be a multiple of 16 bits!");
4607  if (OpOpcode == ISD::UNDEF)
4608  return getUNDEF(VT);
4609  break;
4610  case ISD::BITREVERSE:
4611  assert(VT.isInteger() && VT == Operand.getValueType() &&
4612  "Invalid BITREVERSE!");
4613  if (OpOpcode == ISD::UNDEF)
4614  return getUNDEF(VT);
4615  break;
4616  case ISD::BITCAST:
4617  // Basic sanity checking.
4618  assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
4619  "Cannot BITCAST between types of different sizes!");
4620  if (VT == Operand.getValueType()) return Operand; // noop conversion.
4621  if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
4622  return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
4623  if (OpOpcode == ISD::UNDEF)
4624  return getUNDEF(VT);
4625  break;
4626  case ISD::SCALAR_TO_VECTOR:
4627  assert(VT.isVector() && !Operand.getValueType().isVector() &&
4628  (VT.getVectorElementType() == Operand.getValueType() ||
4629  (VT.getVectorElementType().isInteger() &&
4630  Operand.getValueType().isInteger() &&
4631  VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
4632  "Illegal SCALAR_TO_VECTOR node!");
4633  if (OpOpcode == ISD::UNDEF)
4634  return getUNDEF(VT);
4635  // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
4636  if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
4637  isa<ConstantSDNode>(Operand.getOperand(1)) &&
4638  Operand.getConstantOperandVal(1) == 0 &&
4639  Operand.getOperand(0).getValueType() == VT)
4640  return Operand.getOperand(0);
4641  break;
4642  case ISD::FNEG:
4643  // Negation of an unknown bag of bits is still completely undefined.
4644  if (OpOpcode == ISD::UNDEF)
4645  return getUNDEF(VT);
4646 
4647  // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
4648  if ((getTarget().Options.UnsafeFPMath || Flags.hasNoSignedZeros()) &&
4649  OpOpcode == ISD::FSUB)
4650  return getNode(ISD::FSUB, DL, VT, Operand.getOperand(1),
4651  Operand.getOperand(0), Flags);
4652  if (OpOpcode == ISD::FNEG) // --X -> X
4653  return Operand.getOperand(0);
4654  break;
4655  case ISD::FABS:
4656  if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
4657  return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
4658  break;
4659  }
4660 
4661  SDNode *N;
4662  SDVTList VTs = getVTList(VT);
4663  SDValue Ops[] = {Operand};
4664  if (VT != MVT::Glue) { // Don't CSE flag producing nodes
4666  AddNodeIDNode(ID, Opcode, VTs, Ops);
4667  void *IP = nullptr;
4668  if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4669  E->intersectFlagsWith(Flags);
4670  return SDValue(E, 0);
4671  }
4672 
4673  N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4674  N->setFlags(Flags);
4675  createOperands(N, Ops);
4676  CSEMap.InsertNode(N, IP);
4677  } else {
4678  N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4679  createOperands(N, Ops);
4680  }
4681 
4682  InsertNode(N);
4683  SDValue V = SDValue(N, 0);
4684  NewSDValueDbgMsg(V, "Creating new node: ", this);
4685  return V;
4686 }
4687 
4688 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1,
4689  const APInt &C2) {
4690  switch (Opcode) {
4691  case ISD::ADD: return std::make_pair(C1 + C2, true);
4692  case ISD::SUB: return std::make_pair(C1 - C2, true);
4693  case ISD::MUL: return std::make_pair(C1 * C2, true);
4694  case ISD::AND: return std::make_pair(C1 & C2, true);
4695  case ISD::OR: return std::make_pair(C1 | C2, true);
4696  case ISD::XOR: return std::make_pair(C1 ^ C2, true);
4697  case ISD::SHL: return std::make_pair(C1 << C2, true);
4698  case ISD::SRL: return std::make_pair(C1.lshr(C2), true);
4699  case ISD::SRA: return std::make_pair(C1.ashr(C2), true);
4700  case ISD::ROTL: return std::make_pair(C1.rotl(C2), true);
4701  case ISD::ROTR: return std::make_pair(C1.rotr(C2), true);
4702  case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true);
4703  case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true);
4704  case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true);
4705  case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true);
4706  case ISD::SADDSAT: return std::make_pair(C1.sadd_sat(C2), true);
4707  case ISD::UADDSAT: return std::make_pair(C1.uadd_sat(C2), true);
4708  case ISD::SSUBSAT: return std::make_pair(C1.ssub_sat(C2), true);
4709  case ISD::USUBSAT: return std::make_pair(C1.usub_sat(C2), true);
4710  case ISD::UDIV:
4711  if (!C2.getBoolValue())
4712  break;
4713  return std::make_pair(C1.udiv(C2), true);
4714  case ISD::UREM:
4715  if (!C2.getBoolValue())
4716  break;
4717  return std::make_pair(C1.urem(C2), true);
4718  case ISD::SDIV:
4719  if (!C2.getBoolValue())
4720  break;
4721  return std::make_pair(C1.sdiv(C2), true);
4722  case ISD::SREM:
4723  if (!C2.getBoolValue())
4724  break;
4725  return std::make_pair(C1.srem(C2), true);
4726  }
4727  return std::make_pair(APInt(1, 0), false);
4728 }
4729 
4731  EVT VT, const ConstantSDNode *C1,
4732  const ConstantSDNode *C2) {
4733  if (C1->isOpaque() || C2->isOpaque())
4734  return SDValue();
4735 
4736  std::pair<APInt, bool> Folded = FoldValue(Opcode, C1->getAPIntValue(),
4737  C2->getAPIntValue());
4738  if (!Folded.second)
4739  return SDValue();
4740  return getConstant(Folded.first, DL, VT);
4741 }
4742 
4744  const GlobalAddressSDNode *GA,
4745  const SDNode *N2) {
4746  if (GA->getOpcode() != ISD::GlobalAddress)
4747  return SDValue();
4748  if (!TLI->isOffsetFoldingLegal(GA))
4749  return SDValue();
4750  auto *C2 = dyn_cast<ConstantSDNode>(N2);
4751  if (!C2)
4752  return SDValue();
4753  int64_t Offset = C2->getSExtValue();
4754  switch (Opcode) {
4755  case ISD::ADD: break;
4756  case ISD::SUB: Offset = -uint64_t(Offset); break;
4757  default: return SDValue();
4758  }
4759  return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
4760  GA->getOffset() + uint64_t(Offset));
4761 }
4762 
4763 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
4764  switch (Opcode) {
4765  case ISD::SDIV:
4766  case ISD::UDIV:
4767  case ISD::SREM:
4768  case ISD::UREM: {
4769  // If a divisor is zero/undef or any element of a divisor vector is
4770  // zero/undef, the whole op is undef.
4771  assert(Ops.size() == 2 && "Div/rem should have 2 operands");
4772  SDValue Divisor = Ops[1];
4773  if (Divisor.isUndef() || isNullConstant(Divisor))
4774  return true;
4775 
4776  return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
4777