LLVM  9.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) {
298  if (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 (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 Mask are used.
2127  switch (V.getOpcode()) {
2128  default:
2129  break;
2130  case ISD::Constant: {
2131  const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
2132  assert(CV && "Const value should be ConstSDNode.");
2133  const APInt &CVal = CV->getAPIntValue();
2134  APInt NewVal = CVal & Mask;
2135  if (NewVal != CVal)
2136  return getConstant(NewVal, SDLoc(V), V.getValueType());
2137  break;
2138  }
2139  case ISD::OR:
2140  case ISD::XOR:
2141  // If the LHS or RHS don't contribute bits to the or, drop them.
2142  if (MaskedValueIsZero(V.getOperand(0), Mask))
2143  return V.getOperand(1);
2144  if (MaskedValueIsZero(V.getOperand(1), Mask))
2145  return V.getOperand(0);
2146  break;
2147  case ISD::SRL:
2148  // Only look at single-use SRLs.
2149  if (!V.getNode()->hasOneUse())
2150  break;
2151  if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2152  // See if we can recursively simplify the LHS.
2153  unsigned Amt = RHSC->getZExtValue();
2154 
2155  // Watch out for shift count overflow though.
2156  if (Amt >= Mask.getBitWidth())
2157  break;
2158  APInt NewMask = Mask << Amt;
2159  if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
2160  return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2161  V.getOperand(1));
2162  }
2163  break;
2164  case ISD::AND: {
2165  // X & -1 -> X (ignoring bits which aren't demanded).
2166  // Also handle the case where masked out bits in X are known to be zero.
2167  if (ConstantSDNode *RHSC = isConstOrConstSplat(V.getOperand(1))) {
2168  const APInt &AndVal = RHSC->getAPIntValue();
2169  if (Mask.isSubsetOf(AndVal) ||
2170  Mask.isSubsetOf(computeKnownBits(V.getOperand(0)).Zero | AndVal))
2171  return V.getOperand(0);
2172  }
2173  break;
2174  }
2175  case ISD::ANY_EXTEND: {
2176  SDValue Src = V.getOperand(0);
2177  unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
2178  // Being conservative here - only peek through if we only demand bits in the
2179  // non-extended source (even though the extended bits are technically undef).
2180  if (Mask.getActiveBits() > SrcBitWidth)
2181  break;
2182  APInt SrcMask = Mask.trunc(SrcBitWidth);
2183  if (SDValue DemandedSrc = GetDemandedBits(Src, SrcMask))
2184  return getNode(ISD::ANY_EXTEND, SDLoc(V), V.getValueType(), DemandedSrc);
2185  break;
2186  }
2188  EVT ExVT = cast<VTSDNode>(V.getOperand(1))->getVT();
2189  unsigned ExVTBits = ExVT.getScalarSizeInBits();
2190 
2191  // If none of the extended bits are demanded, eliminate the sextinreg.
2192  if (Mask.getActiveBits() <= ExVTBits)
2193  return V.getOperand(0);
2194 
2195  break;
2196  }
2197  return SDValue();
2198 }
2199 
2200 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2201 /// use this predicate to simplify operations downstream.
2202 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2203  unsigned BitWidth = Op.getScalarValueSizeInBits();
2204  return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2205 }
2206 
2207 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2208 /// this predicate to simplify operations downstream. Mask is known to be zero
2209 /// for bits that V cannot have.
2211  unsigned Depth) const {
2212  return Mask.isSubsetOf(computeKnownBits(Op, Depth).Zero);
2213 }
2214 
2215 /// isSplatValue - Return true if the vector V has the same value
2216 /// across all DemandedElts.
2217 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2218  APInt &UndefElts) {
2219  if (!DemandedElts)
2220  return false; // No demanded elts, better to assume we don't know anything.
2221 
2222  EVT VT = V.getValueType();
2223  assert(VT.isVector() && "Vector type expected");
2224 
2225  unsigned NumElts = VT.getVectorNumElements();
2226  assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2227  UndefElts = APInt::getNullValue(NumElts);
2228 
2229  switch (V.getOpcode()) {
2230  case ISD::BUILD_VECTOR: {
2231  SDValue Scl;
2232  for (unsigned i = 0; i != NumElts; ++i) {
2233  SDValue Op = V.getOperand(i);
2234  if (Op.isUndef()) {
2235  UndefElts.setBit(i);
2236  continue;
2237  }
2238  if (!DemandedElts[i])
2239  continue;
2240  if (Scl && Scl != Op)
2241  return false;
2242  Scl = Op;
2243  }
2244  return true;
2245  }
2246  case ISD::VECTOR_SHUFFLE: {
2247  // Check if this is a shuffle node doing a splat.
2248  // TODO: Do we need to handle shuffle(splat, undef, mask)?
2249  int SplatIndex = -1;
2250  ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2251  for (int i = 0; i != (int)NumElts; ++i) {
2252  int M = Mask[i];
2253  if (M < 0) {
2254  UndefElts.setBit(i);
2255  continue;
2256  }
2257  if (!DemandedElts[i])
2258  continue;
2259  if (0 <= SplatIndex && SplatIndex != M)
2260  return false;
2261  SplatIndex = M;
2262  }
2263  return true;
2264  }
2265  case ISD::EXTRACT_SUBVECTOR: {
2266  SDValue Src = V.getOperand(0);
2268  unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2269  if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2270  // Offset the demanded elts by the subvector index.
2271  uint64_t Idx = SubIdx->getZExtValue();
2272  APInt UndefSrcElts;
2273  APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2274  if (isSplatValue(Src, DemandedSrc, UndefSrcElts)) {
2275  UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2276  return true;
2277  }
2278  }
2279  break;
2280  }
2281  case ISD::ADD:
2282  case ISD::SUB:
2283  case ISD::AND: {
2284  APInt UndefLHS, UndefRHS;
2285  SDValue LHS = V.getOperand(0);
2286  SDValue RHS = V.getOperand(1);
2287  if (isSplatValue(LHS, DemandedElts, UndefLHS) &&
2288  isSplatValue(RHS, DemandedElts, UndefRHS)) {
2289  UndefElts = UndefLHS | UndefRHS;
2290  return true;
2291  }
2292  break;
2293  }
2294  }
2295 
2296  return false;
2297 }
2298 
2299 /// Helper wrapper to main isSplatValue function.
2300 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2301  EVT VT = V.getValueType();
2302  assert(VT.isVector() && "Vector type expected");
2303  unsigned NumElts = VT.getVectorNumElements();
2304 
2305  APInt UndefElts;
2306  APInt DemandedElts = APInt::getAllOnesValue(NumElts);
2307  return isSplatValue(V, DemandedElts, UndefElts) &&
2308  (AllowUndefs || !UndefElts);
2309 }
2310 
2313 
2314  EVT VT = V.getValueType();
2315  unsigned Opcode = V.getOpcode();
2316  switch (Opcode) {
2317  default: {
2318  APInt UndefElts;
2319  APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2320  if (isSplatValue(V, DemandedElts, UndefElts)) {
2321  // Handle case where all demanded elements are UNDEF.
2322  if (DemandedElts.isSubsetOf(UndefElts)) {
2323  SplatIdx = 0;
2324  return getUNDEF(VT);
2325  }
2326  SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2327  return V;
2328  }
2329  break;
2330  }
2331  case ISD::VECTOR_SHUFFLE: {
2332  // Check if this is a shuffle node doing a splat.
2333  // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2334  // getTargetVShiftNode currently struggles without the splat source.
2335  auto *SVN = cast<ShuffleVectorSDNode>(V);
2336  if (!SVN->isSplat())
2337  break;
2338  int Idx = SVN->getSplatIndex();
2339  int NumElts = V.getValueType().getVectorNumElements();
2340  SplatIdx = Idx % NumElts;
2341  return V.getOperand(Idx / NumElts);
2342  }
2343  }
2344 
2345  return SDValue();
2346 }
2347 
2349  int SplatIdx;
2350  if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx))
2352  SrcVector.getValueType().getScalarType(), SrcVector,
2353  getIntPtrConstant(SplatIdx, SDLoc(V)));
2354  return SDValue();
2355 }
2356 
2357 /// If a SHL/SRA/SRL node has a constant or splat constant shift amount that
2358 /// is less than the element bit-width of the shift node, return it.
2360  if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1))) {
2361  // Shifting more than the bitwidth is not valid.
2362  const APInt &ShAmt = SA->getAPIntValue();
2363  if (ShAmt.ult(V.getScalarValueSizeInBits()))
2364  return &ShAmt;
2365  }
2366  return nullptr;
2367 }
2368 
2369 /// Determine which bits of Op are known to be either zero or one and return
2370 /// them in Known. For vectors, the known bits are those that are shared by
2371 /// every vector element.
2373  EVT VT = Op.getValueType();
2374  APInt DemandedElts = VT.isVector()
2376  : APInt(1, 1);
2377  return computeKnownBits(Op, DemandedElts, Depth);
2378 }
2379 
2380 /// Determine which bits of Op are known to be either zero or one and return
2381 /// them in Known. The DemandedElts argument allows us to only collect the known
2382 /// bits that are shared by the requested vector elements.
2384  unsigned Depth) const {
2385  unsigned BitWidth = Op.getScalarValueSizeInBits();
2386 
2387  KnownBits Known(BitWidth); // Don't know anything.
2388 
2389  if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2390  // We know all of the bits for a constant!
2391  Known.One = C->getAPIntValue();
2392  Known.Zero = ~Known.One;
2393  return Known;
2394  }
2395  if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2396  // We know all of the bits for a constant fp!
2397  Known.One = C->getValueAPF().bitcastToAPInt();
2398  Known.Zero = ~Known.One;
2399  return Known;
2400  }
2401 
2402  if (Depth == 6)
2403  return Known; // Limit search depth.
2404 
2405  KnownBits Known2;
2406  unsigned NumElts = DemandedElts.getBitWidth();
2407  assert((!Op.getValueType().isVector() ||
2408  NumElts == Op.getValueType().getVectorNumElements()) &&
2409  "Unexpected vector size");
2410 
2411  if (!DemandedElts)
2412  return Known; // No demanded elts, better to assume we don't know anything.
2413 
2414  unsigned Opcode = Op.getOpcode();
2415  switch (Opcode) {
2416  case ISD::BUILD_VECTOR:
2417  // Collect the known bits that are shared by every demanded vector element.
2418  Known.Zero.setAllBits(); Known.One.setAllBits();
2419  for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2420  if (!DemandedElts[i])
2421  continue;
2422 
2423  SDValue SrcOp = Op.getOperand(i);
2424  Known2 = computeKnownBits(SrcOp, Depth + 1);
2425 
2426  // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2427  if (SrcOp.getValueSizeInBits() != BitWidth) {
2428  assert(SrcOp.getValueSizeInBits() > BitWidth &&
2429  "Expected BUILD_VECTOR implicit truncation");
2430  Known2 = Known2.trunc(BitWidth);
2431  }
2432 
2433  // Known bits are the values that are shared by every demanded element.
2434  Known.One &= Known2.One;
2435  Known.Zero &= Known2.Zero;
2436 
2437  // If we don't know any bits, early out.
2438  if (Known.isUnknown())
2439  break;
2440  }
2441  break;
2442  case ISD::VECTOR_SHUFFLE: {
2443  // Collect the known bits that are shared by every vector element referenced
2444  // by the shuffle.
2445  APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2446  Known.Zero.setAllBits(); Known.One.setAllBits();
2447  const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2448  assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2449  for (unsigned i = 0; i != NumElts; ++i) {
2450  if (!DemandedElts[i])
2451  continue;
2452 
2453  int M = SVN->getMaskElt(i);
2454  if (M < 0) {
2455  // For UNDEF elements, we don't know anything about the common state of
2456  // the shuffle result.
2457  Known.resetAll();
2458  DemandedLHS.clearAllBits();
2459  DemandedRHS.clearAllBits();
2460  break;
2461  }
2462 
2463  if ((unsigned)M < NumElts)
2464  DemandedLHS.setBit((unsigned)M % NumElts);
2465  else
2466  DemandedRHS.setBit((unsigned)M % NumElts);
2467  }
2468  // Known bits are the values that are shared by every demanded element.
2469  if (!!DemandedLHS) {
2470  SDValue LHS = Op.getOperand(0);
2471  Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
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  if (!!DemandedRHS) {
2479  SDValue RHS = Op.getOperand(1);
2480  Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2481  Known.One &= Known2.One;
2482  Known.Zero &= Known2.Zero;
2483  }
2484  break;
2485  }
2486  case ISD::CONCAT_VECTORS: {
2487  // Split DemandedElts and test each of the demanded subvectors.
2488  Known.Zero.setAllBits(); Known.One.setAllBits();
2489  EVT SubVectorVT = Op.getOperand(0).getValueType();
2490  unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2491  unsigned NumSubVectors = Op.getNumOperands();
2492  for (unsigned i = 0; i != NumSubVectors; ++i) {
2493  APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2494  DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2495  if (!!DemandedSub) {
2496  SDValue Sub = Op.getOperand(i);
2497  Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2498  Known.One &= Known2.One;
2499  Known.Zero &= Known2.Zero;
2500  }
2501  // If we don't know any bits, early out.
2502  if (Known.isUnknown())
2503  break;
2504  }
2505  break;
2506  }
2507  case ISD::INSERT_SUBVECTOR: {
2508  // If we know the element index, demand any elements from the subvector and
2509  // the remainder from the src its inserted into, otherwise demand them all.
2510  SDValue Src = Op.getOperand(0);
2511  SDValue Sub = Op.getOperand(1);
2513  unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2514  if (SubIdx && SubIdx->getAPIntValue().ule(NumElts - NumSubElts)) {
2515  Known.One.setAllBits();
2516  Known.Zero.setAllBits();
2517  uint64_t Idx = SubIdx->getZExtValue();
2518  APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2519  if (!!DemandedSubElts) {
2520  Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2521  if (Known.isUnknown())
2522  break; // early-out.
2523  }
2524  APInt SubMask = APInt::getBitsSet(NumElts, Idx, Idx + NumSubElts);
2525  APInt DemandedSrcElts = DemandedElts & ~SubMask;
2526  if (!!DemandedSrcElts) {
2527  Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2528  Known.One &= Known2.One;
2529  Known.Zero &= Known2.Zero;
2530  }
2531  } else {
2532  Known = computeKnownBits(Sub, Depth + 1);
2533  if (Known.isUnknown())
2534  break; // early-out.
2535  Known2 = computeKnownBits(Src, Depth + 1);
2536  Known.One &= Known2.One;
2537  Known.Zero &= Known2.Zero;
2538  }
2539  break;
2540  }
2541  case ISD::EXTRACT_SUBVECTOR: {
2542  // If we know the element index, just demand that subvector elements,
2543  // otherwise demand them all.
2544  SDValue Src = Op.getOperand(0);
2546  unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2547  if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2548  // Offset the demanded elts by the subvector index.
2549  uint64_t Idx = SubIdx->getZExtValue();
2550  APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2551  Known = computeKnownBits(Src, DemandedSrc, Depth + 1);
2552  } else {
2553  Known = computeKnownBits(Src, Depth + 1);
2554  }
2555  break;
2556  }
2557  case ISD::SCALAR_TO_VECTOR: {
2558  // We know about scalar_to_vector as much as we know about it source,
2559  // which becomes the first element of otherwise unknown vector.
2560  if (DemandedElts != 1)
2561  break;
2562 
2563  SDValue N0 = Op.getOperand(0);
2564  Known = computeKnownBits(N0, Depth + 1);
2565  if (N0.getValueSizeInBits() != BitWidth)
2566  Known = Known.trunc(BitWidth);
2567 
2568  break;
2569  }
2570  case ISD::BITCAST: {
2571  SDValue N0 = Op.getOperand(0);
2572  EVT SubVT = N0.getValueType();
2573  unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2574 
2575  // Ignore bitcasts from unsupported types.
2576  if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2577  break;
2578 
2579  // Fast handling of 'identity' bitcasts.
2580  if (BitWidth == SubBitWidth) {
2581  Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2582  break;
2583  }
2584 
2585  bool IsLE = getDataLayout().isLittleEndian();
2586 
2587  // Bitcast 'small element' vector to 'large element' scalar/vector.
2588  if ((BitWidth % SubBitWidth) == 0) {
2589  assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2590 
2591  // Collect known bits for the (larger) output by collecting the known
2592  // bits from each set of sub elements and shift these into place.
2593  // We need to separately call computeKnownBits for each set of
2594  // sub elements as the knownbits for each is likely to be different.
2595  unsigned SubScale = BitWidth / SubBitWidth;
2596  APInt SubDemandedElts(NumElts * SubScale, 0);
2597  for (unsigned i = 0; i != NumElts; ++i)
2598  if (DemandedElts[i])
2599  SubDemandedElts.setBit(i * SubScale);
2600 
2601  for (unsigned i = 0; i != SubScale; ++i) {
2602  Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2603  Depth + 1);
2604  unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2605  Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts);
2606  Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts);
2607  }
2608  }
2609 
2610  // Bitcast 'large element' scalar/vector to 'small element' vector.
2611  if ((SubBitWidth % BitWidth) == 0) {
2612  assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2613 
2614  // Collect known bits for the (smaller) output by collecting the known
2615  // bits from the overlapping larger input elements and extracting the
2616  // sub sections we actually care about.
2617  unsigned SubScale = SubBitWidth / BitWidth;
2618  APInt SubDemandedElts(NumElts / SubScale, 0);
2619  for (unsigned i = 0; i != NumElts; ++i)
2620  if (DemandedElts[i])
2621  SubDemandedElts.setBit(i / SubScale);
2622 
2623  Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
2624 
2625  Known.Zero.setAllBits(); Known.One.setAllBits();
2626  for (unsigned i = 0; i != NumElts; ++i)
2627  if (DemandedElts[i]) {
2628  unsigned Shifts = IsLE ? i : NumElts - 1 - i;
2629  unsigned Offset = (Shifts % SubScale) * BitWidth;
2630  Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
2631  Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
2632  // If we don't know any bits, early out.
2633  if (Known.isUnknown())
2634  break;
2635  }
2636  }
2637  break;
2638  }
2639  case ISD::AND:
2640  // If either the LHS or the RHS are Zero, the result is zero.
2641  Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2642  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2643 
2644  // Output known-1 bits are only known if set in both the LHS & RHS.
2645  Known.One &= Known2.One;
2646  // Output known-0 are known to be clear if zero in either the LHS | RHS.
2647  Known.Zero |= Known2.Zero;
2648  break;
2649  case ISD::OR:
2650  Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2651  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2652 
2653  // Output known-0 bits are only known if clear in both the LHS & RHS.
2654  Known.Zero &= Known2.Zero;
2655  // Output known-1 are known to be set if set in either the LHS | RHS.
2656  Known.One |= Known2.One;
2657  break;
2658  case ISD::XOR: {
2659  Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2660  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2661 
2662  // Output known-0 bits are known if clear or set in both the LHS & RHS.
2663  APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
2664  // Output known-1 are known to be set if set in only one of the LHS, RHS.
2665  Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
2666  Known.Zero = KnownZeroOut;
2667  break;
2668  }
2669  case ISD::MUL: {
2670  Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2671  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2672 
2673  // If low bits are zero in either operand, output low known-0 bits.
2674  // Also compute a conservative estimate for high known-0 bits.
2675  // More trickiness is possible, but this is sufficient for the
2676  // interesting case of alignment computation.
2677  unsigned TrailZ = Known.countMinTrailingZeros() +
2678  Known2.countMinTrailingZeros();
2679  unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
2680  Known2.countMinLeadingZeros(),
2681  BitWidth) - BitWidth;
2682 
2683  Known.resetAll();
2684  Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
2685  Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
2686  break;
2687  }
2688  case ISD::UDIV: {
2689  // For the purposes of computing leading zeros we can conservatively
2690  // treat a udiv as a logical right shift by the power of 2 known to
2691  // be less than the denominator.
2692  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2693  unsigned LeadZ = Known2.countMinLeadingZeros();
2694 
2695  Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2696  unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
2697  if (RHSMaxLeadingZeros != BitWidth)
2698  LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
2699 
2700  Known.Zero.setHighBits(LeadZ);
2701  break;
2702  }
2703  case ISD::SELECT:
2704  case ISD::VSELECT:
2705  Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
2706  // If we don't know any bits, early out.
2707  if (Known.isUnknown())
2708  break;
2709  Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
2710 
2711  // Only known if known in both the LHS and RHS.
2712  Known.One &= Known2.One;
2713  Known.Zero &= Known2.Zero;
2714  break;
2715  case ISD::SELECT_CC:
2716  Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
2717  // If we don't know any bits, early out.
2718  if (Known.isUnknown())
2719  break;
2720  Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
2721 
2722  // Only known if known in both the LHS and RHS.
2723  Known.One &= Known2.One;
2724  Known.Zero &= Known2.Zero;
2725  break;
2726  case ISD::SMULO:
2727  case ISD::UMULO:
2729  if (Op.getResNo() != 1)
2730  break;
2731  // The boolean result conforms to getBooleanContents.
2732  // If we know the result of a setcc has the top bits zero, use this info.
2733  // We know that we have an integer-based boolean since these operations
2734  // are only available for integer.
2735  if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2737  BitWidth > 1)
2738  Known.Zero.setBitsFrom(1);
2739  break;
2740  case ISD::SETCC:
2741  // If we know the result of a setcc has the top bits zero, use this info.
2742  if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2744  BitWidth > 1)
2745  Known.Zero.setBitsFrom(1);
2746  break;
2747  case ISD::SHL:
2748  if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2749  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2750  unsigned Shift = ShAmt->getZExtValue();
2751  Known.Zero <<= Shift;
2752  Known.One <<= Shift;
2753  // Low bits are known zero.
2754  Known.Zero.setLowBits(Shift);
2755  }
2756  break;
2757  case ISD::SRL:
2758  if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2759  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2760  unsigned Shift = ShAmt->getZExtValue();
2761  Known.Zero.lshrInPlace(Shift);
2762  Known.One.lshrInPlace(Shift);
2763  // High bits are known zero.
2764  Known.Zero.setHighBits(Shift);
2765  } else if (auto *BV = dyn_cast<BuildVectorSDNode>(Op.getOperand(1))) {
2766  // If the shift amount is a vector of constants see if we can bound
2767  // the number of upper zero bits.
2768  unsigned ShiftAmountMin = BitWidth;
2769  for (unsigned i = 0; i != BV->getNumOperands(); ++i) {
2770  if (auto *C = dyn_cast<ConstantSDNode>(BV->getOperand(i))) {
2771  const APInt &ShAmt = C->getAPIntValue();
2772  if (ShAmt.ult(BitWidth)) {
2773  ShiftAmountMin = std::min<unsigned>(ShiftAmountMin,
2774  ShAmt.getZExtValue());
2775  continue;
2776  }
2777  }
2778  // Don't know anything.
2779  ShiftAmountMin = 0;
2780  break;
2781  }
2782 
2783  Known.Zero.setHighBits(ShiftAmountMin);
2784  }
2785  break;
2786  case ISD::SRA:
2787  if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2788  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2789  unsigned Shift = ShAmt->getZExtValue();
2790  // Sign extend known zero/one bit (else is unknown).
2791  Known.Zero.ashrInPlace(Shift);
2792  Known.One.ashrInPlace(Shift);
2793  }
2794  break;
2795  case ISD::FSHL:
2796  case ISD::FSHR:
2797  if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
2798  unsigned Amt = C->getAPIntValue().urem(BitWidth);
2799 
2800  // For fshl, 0-shift returns the 1st arg.
2801  // For fshr, 0-shift returns the 2nd arg.
2802  if (Amt == 0) {
2803  Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
2804  DemandedElts, Depth + 1);
2805  break;
2806  }
2807 
2808  // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
2809  // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
2810  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2811  Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2812  if (Opcode == ISD::FSHL) {
2813  Known.One <<= Amt;
2814  Known.Zero <<= Amt;
2815  Known2.One.lshrInPlace(BitWidth - Amt);
2816  Known2.Zero.lshrInPlace(BitWidth - Amt);
2817  } else {
2818  Known.One <<= BitWidth - Amt;
2819  Known.Zero <<= BitWidth - Amt;
2820  Known2.One.lshrInPlace(Amt);
2821  Known2.Zero.lshrInPlace(Amt);
2822  }
2823  Known.One |= Known2.One;
2824  Known.Zero |= Known2.Zero;
2825  }
2826  break;
2827  case ISD::SIGN_EXTEND_INREG: {
2828  EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2829  unsigned EBits = EVT.getScalarSizeInBits();
2830 
2831  // Sign extension. Compute the demanded bits in the result that are not
2832  // present in the input.
2833  APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
2834 
2835  APInt InSignMask = APInt::getSignMask(EBits);
2836  APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
2837 
2838  // If the sign extended bits are demanded, we know that the sign
2839  // bit is demanded.
2840  InSignMask = InSignMask.zext(BitWidth);
2841  if (NewBits.getBoolValue())
2842  InputDemandedBits |= InSignMask;
2843 
2844  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2845  Known.One &= InputDemandedBits;
2846  Known.Zero &= InputDemandedBits;
2847 
2848  // If the sign bit of the input is known set or clear, then we know the
2849  // top bits of the result.
2850  if (Known.Zero.intersects(InSignMask)) { // Input sign bit known clear
2851  Known.Zero |= NewBits;
2852  Known.One &= ~NewBits;
2853  } else if (Known.One.intersects(InSignMask)) { // Input sign bit known set
2854  Known.One |= NewBits;
2855  Known.Zero &= ~NewBits;
2856  } else { // Input sign bit unknown
2857  Known.Zero &= ~NewBits;
2858  Known.One &= ~NewBits;
2859  }
2860  break;
2861  }
2862  case ISD::CTTZ:
2863  case ISD::CTTZ_ZERO_UNDEF: {
2864  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2865  // If we have a known 1, its position is our upper bound.
2866  unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2867  unsigned LowBits = Log2_32(PossibleTZ) + 1;
2868  Known.Zero.setBitsFrom(LowBits);
2869  break;
2870  }
2871  case ISD::CTLZ:
2872  case ISD::CTLZ_ZERO_UNDEF: {
2873  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2874  // If we have a known 1, its position is our upper bound.
2875  unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2876  unsigned LowBits = Log2_32(PossibleLZ) + 1;
2877  Known.Zero.setBitsFrom(LowBits);
2878  break;
2879  }
2880  case ISD::CTPOP: {
2881  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2882  // If we know some of the bits are zero, they can't be one.
2883  unsigned PossibleOnes = Known2.countMaxPopulation();
2884  Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
2885  break;
2886  }
2887  case ISD::LOAD: {
2888  LoadSDNode *LD = cast<LoadSDNode>(Op);
2889  // If this is a ZEXTLoad and we are looking at the loaded value.
2890  if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
2891  EVT VT = LD->getMemoryVT();
2892  unsigned MemBits = VT.getScalarSizeInBits();
2893  Known.Zero.setBitsFrom(MemBits);
2894  } else if (const MDNode *Ranges = LD->getRanges()) {
2895  if (LD->getExtensionType() == ISD::NON_EXTLOAD)
2896  computeKnownBitsFromRangeMetadata(*Ranges, Known);
2897  }
2898  break;
2899  }
2901  EVT InVT = Op.getOperand(0).getValueType();
2902  APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
2903  Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
2904  Known = Known.zext(BitWidth, true /* ExtendedBitsAreKnownZero */);
2905  break;
2906  }
2907  case ISD::ZERO_EXTEND: {
2908  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2909  Known = Known.zext(BitWidth, true /* ExtendedBitsAreKnownZero */);
2910  break;
2911  }
2913  EVT InVT = Op.getOperand(0).getValueType();
2914  APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
2915  Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
2916  // If the sign bit is known to be zero or one, then sext will extend
2917  // it to the top bits, else it will just zext.
2918  Known = Known.sext(BitWidth);
2919  break;
2920  }
2921  case ISD::SIGN_EXTEND: {
2922  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2923  // If the sign bit is known to be zero or one, then sext will extend
2924  // it to the top bits, else it will just zext.
2925  Known = Known.sext(BitWidth);
2926  break;
2927  }
2928  case ISD::ANY_EXTEND: {
2929  Known = computeKnownBits(Op.getOperand(0), Depth+1);
2930  Known = Known.zext(BitWidth, false /* ExtendedBitsAreKnownZero */);
2931  break;
2932  }
2933  case ISD::TRUNCATE: {
2934  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2935  Known = Known.trunc(BitWidth);
2936  break;
2937  }
2938  case ISD::AssertZext: {
2939  EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2940  APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
2941  Known = computeKnownBits(Op.getOperand(0), Depth+1);
2942  Known.Zero |= (~InMask);
2943  Known.One &= (~Known.Zero);
2944  break;
2945  }
2946  case ISD::FGETSIGN:
2947  // All bits are zero except the low bit.
2948  Known.Zero.setBitsFrom(1);
2949  break;
2950  case ISD::USUBO:
2951  case ISD::SSUBO:
2952  if (Op.getResNo() == 1) {
2953  // If we know the result of a setcc has the top bits zero, use this info.
2954  if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2956  BitWidth > 1)
2957  Known.Zero.setBitsFrom(1);
2958  break;
2959  }
2961  case ISD::SUB:
2962  case ISD::SUBC: {
2963  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2964  Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2965  Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
2966  Known, Known2);
2967  break;
2968  }
2969  case ISD::UADDO:
2970  case ISD::SADDO:
2971  case ISD::ADDCARRY:
2972  if (Op.getResNo() == 1) {
2973  // If we know the result of a setcc has the top bits zero, use this info.
2974  if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2976  BitWidth > 1)
2977  Known.Zero.setBitsFrom(1);
2978  break;
2979  }
2981  case ISD::ADD:
2982  case ISD::ADDC:
2983  case ISD::ADDE: {
2984  assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
2985 
2986  // With ADDE and ADDCARRY, a carry bit may be added in.
2987  KnownBits Carry(1);
2988  if (Opcode == ISD::ADDE)
2989  // Can't track carry from glue, set carry to unknown.
2990  Carry.resetAll();
2991  else if (Opcode == ISD::ADDCARRY)
2992  // TODO: Compute known bits for the carry operand. Not sure if it is worth
2993  // the trouble (how often will we find a known carry bit). And I haven't
2994  // tested this very much yet, but something like this might work:
2995  // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
2996  // Carry = Carry.zextOrTrunc(1, false);
2997  Carry.resetAll();
2998  else
2999  Carry.setAllZero();
3000 
3001  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3002  Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3003  Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3004  break;
3005  }
3006  case ISD::SREM:
3007  if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
3008  const APInt &RA = Rem->getAPIntValue().abs();
3009  if (RA.isPowerOf2()) {
3010  APInt LowBits = RA - 1;
3011  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3012 
3013  // The low bits of the first operand are unchanged by the srem.
3014  Known.Zero = Known2.Zero & LowBits;
3015  Known.One = Known2.One & LowBits;
3016 
3017  // If the first operand is non-negative or has all low bits zero, then
3018  // the upper bits are all zero.
3019  if (Known2.Zero[BitWidth-1] || ((Known2.Zero & LowBits) == LowBits))
3020  Known.Zero |= ~LowBits;
3021 
3022  // If the first operand is negative and not all low bits are zero, then
3023  // the upper bits are all one.
3024  if (Known2.One[BitWidth-1] && ((Known2.One & LowBits) != 0))
3025  Known.One |= ~LowBits;
3026  assert((Known.Zero & Known.One) == 0&&"Bits known to be one AND zero?");
3027  }
3028  }
3029  break;
3030  case ISD::UREM: {
3031  if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
3032  const APInt &RA = Rem->getAPIntValue();
3033  if (RA.isPowerOf2()) {
3034  APInt LowBits = (RA - 1);
3035  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3036 
3037  // The upper bits are all zero, the lower ones are unchanged.
3038  Known.Zero = Known2.Zero | ~LowBits;
3039  Known.One = Known2.One & LowBits;
3040  break;
3041  }
3042  }
3043 
3044  // Since the result is less than or equal to either operand, any leading
3045  // zero bits in either operand must also exist in the result.
3046  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3047  Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3048 
3049  uint32_t Leaders =
3050  std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
3051  Known.resetAll();
3052  Known.Zero.setHighBits(Leaders);
3053  break;
3054  }
3055  case ISD::EXTRACT_ELEMENT: {
3056  Known = computeKnownBits(Op.getOperand(0), Depth+1);
3057  const unsigned Index = Op.getConstantOperandVal(1);
3058  const unsigned EltBitWidth = Op.getValueSizeInBits();
3059 
3060  // Remove low part of known bits mask
3061  Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3062  Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3063 
3064  // Remove high part of known bit mask
3065  Known = Known.trunc(EltBitWidth);
3066  break;
3067  }
3068  case ISD::EXTRACT_VECTOR_ELT: {
3069  SDValue InVec = Op.getOperand(0);
3070  SDValue EltNo = Op.getOperand(1);
3071  EVT VecVT = InVec.getValueType();
3072  const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3073  const unsigned NumSrcElts = VecVT.getVectorNumElements();
3074  // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3075  // anything about the extended bits.
3076  if (BitWidth > EltBitWidth)
3077  Known = Known.trunc(EltBitWidth);
3078  ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3079  if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) {
3080  // If we know the element index, just demand that vector element.
3081  unsigned Idx = ConstEltNo->getZExtValue();
3082  APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
3083  Known = computeKnownBits(InVec, DemandedElt, Depth + 1);
3084  } else {
3085  // Unknown element index, so ignore DemandedElts and demand them all.
3086  Known = computeKnownBits(InVec, Depth + 1);
3087  }
3088  if (BitWidth > EltBitWidth)
3089  Known = Known.zext(BitWidth, false /* => any extend */);
3090  break;
3091  }
3092  case ISD::INSERT_VECTOR_ELT: {
3093  SDValue InVec = Op.getOperand(0);
3094  SDValue InVal = Op.getOperand(1);
3095  SDValue EltNo = Op.getOperand(2);
3096 
3097  ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3098  if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3099  // If we know the element index, split the demand between the
3100  // source vector and the inserted element.
3101  Known.Zero = Known.One = APInt::getAllOnesValue(BitWidth);
3102  unsigned EltIdx = CEltNo->getZExtValue();
3103 
3104  // If we demand the inserted element then add its common known bits.
3105  if (DemandedElts[EltIdx]) {
3106  Known2 = computeKnownBits(InVal, Depth + 1);
3107  Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
3108  Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
3109  }
3110 
3111  // If we demand the source vector then add its common known bits, ensuring
3112  // that we don't demand the inserted element.
3113  APInt VectorElts = DemandedElts & ~(APInt::getOneBitSet(NumElts, EltIdx));
3114  if (!!VectorElts) {
3115  Known2 = computeKnownBits(InVec, VectorElts, Depth + 1);
3116  Known.One &= Known2.One;
3117  Known.Zero &= Known2.Zero;
3118  }
3119  } else {
3120  // Unknown element index, so ignore DemandedElts and demand them all.
3121  Known = computeKnownBits(InVec, Depth + 1);
3122  Known2 = computeKnownBits(InVal, Depth + 1);
3123  Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
3124  Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
3125  }
3126  break;
3127  }
3128  case ISD::BITREVERSE: {
3129  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3130  Known.Zero = Known2.Zero.reverseBits();
3131  Known.One = Known2.One.reverseBits();
3132  break;
3133  }
3134  case ISD::BSWAP: {
3135  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3136  Known.Zero = Known2.Zero.byteSwap();
3137  Known.One = Known2.One.byteSwap();
3138  break;
3139  }
3140  case ISD::ABS: {
3141  Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3142 
3143  // If the source's MSB is zero then we know the rest of the bits already.
3144  if (Known2.isNonNegative()) {
3145  Known.Zero = Known2.Zero;
3146  Known.One = Known2.One;
3147  break;
3148  }
3149 
3150  // We only know that the absolute values's MSB will be zero iff there is
3151  // a set bit that isn't the sign bit (otherwise it could be INT_MIN).
3152  Known2.One.clearSignBit();
3153  if (Known2.One.getBoolValue()) {
3154  Known.Zero = APInt::getSignMask(BitWidth);
3155  break;
3156  }
3157  break;
3158  }
3159  case ISD::UMIN: {
3160  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3161  Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3162 
3163  // UMIN - we know that the result will have the maximum of the
3164  // known zero leading bits of the inputs.
3165  unsigned LeadZero = Known.countMinLeadingZeros();
3166  LeadZero = std::max(LeadZero, Known2.countMinLeadingZeros());
3167 
3168  Known.Zero &= Known2.Zero;
3169  Known.One &= Known2.One;
3170  Known.Zero.setHighBits(LeadZero);
3171  break;
3172  }
3173  case ISD::UMAX: {
3174  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3175  Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3176 
3177  // UMAX - we know that the result will have the maximum of the
3178  // known one leading bits of the inputs.
3179  unsigned LeadOne = Known.countMinLeadingOnes();
3180  LeadOne = std::max(LeadOne, Known2.countMinLeadingOnes());
3181 
3182  Known.Zero &= Known2.Zero;
3183  Known.One &= Known2.One;
3184  Known.One.setHighBits(LeadOne);
3185  break;
3186  }
3187  case ISD::SMIN:
3188  case ISD::SMAX: {
3189  // If we have a clamp pattern, we know that the number of sign bits will be
3190  // the minimum of the clamp min/max range.
3191  bool IsMax = (Opcode == ISD::SMAX);
3192  ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3193  if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3194  if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3195  CstHigh =
3196  isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3197  if (CstLow && CstHigh) {
3198  if (!IsMax)
3199  std::swap(CstLow, CstHigh);
3200 
3201  const APInt &ValueLow = CstLow->getAPIntValue();
3202  const APInt &ValueHigh = CstHigh->getAPIntValue();
3203  if (ValueLow.sle(ValueHigh)) {
3204  unsigned LowSignBits = ValueLow.getNumSignBits();
3205  unsigned HighSignBits = ValueHigh.getNumSignBits();
3206  unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3207  if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3208  Known.One.setHighBits(MinSignBits);
3209  break;
3210  }
3211  if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3212  Known.Zero.setHighBits(MinSignBits);
3213  break;
3214  }
3215  }
3216  }
3217 
3218  // Fallback - just get the shared known bits of the operands.
3219  Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3220  if (Known.isUnknown()) break; // Early-out
3221  Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3222  Known.Zero &= Known2.Zero;
3223  Known.One &= Known2.One;
3224  break;
3225  }
3226  case ISD::FrameIndex:
3227  case ISD::TargetFrameIndex:
3228  TLI->computeKnownBitsForFrameIndex(Op, Known, DemandedElts, *this, Depth);
3229  break;
3230 
3231  default:
3232  if (Opcode < ISD::BUILTIN_OP_END)
3233  break;
3237  case ISD::INTRINSIC_VOID:
3238  // Allow the target to implement this method for its nodes.
3239  TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3240  break;
3241  }
3242 
3243  assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3244  return Known;
3245 }
3246 
3248  SDValue N1) const {
3249  // X + 0 never overflow
3250  if (isNullConstant(N1))
3251  return OFK_Never;
3252 
3253  KnownBits N1Known = computeKnownBits(N1);
3254  if (N1Known.Zero.getBoolValue()) {
3255  KnownBits N0Known = computeKnownBits(N0);
3256 
3257  bool overflow;
3258  (void)(~N0Known.Zero).uadd_ov(~N1Known.Zero, overflow);
3259  if (!overflow)
3260  return OFK_Never;
3261  }
3262 
3263  // mulhi + 1 never overflow
3264  if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3265  (~N1Known.Zero & 0x01) == ~N1Known.Zero)
3266  return OFK_Never;
3267 
3268  if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3269  KnownBits N0Known = computeKnownBits(N0);
3270 
3271  if ((~N0Known.Zero & 0x01) == ~N0Known.Zero)
3272  return OFK_Never;
3273  }
3274 
3275  return OFK_Sometime;
3276 }
3277 
3279  EVT OpVT = Val.getValueType();
3280  unsigned BitWidth = OpVT.getScalarSizeInBits();
3281 
3282  // Is the constant a known power of 2?
3283  if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3284  return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3285 
3286  // A left-shift of a constant one will have exactly one bit set because
3287  // shifting the bit off the end is undefined.
3288  if (Val.getOpcode() == ISD::SHL) {
3289  auto *C = isConstOrConstSplat(Val.getOperand(0));
3290  if (C && C->getAPIntValue() == 1)
3291  return true;
3292  }
3293 
3294  // Similarly, a logical right-shift of a constant sign-bit will have exactly
3295  // one bit set.
3296  if (Val.getOpcode() == ISD::SRL) {
3297  auto *C = isConstOrConstSplat(Val.getOperand(0));
3298  if (C && C->getAPIntValue().isSignMask())
3299  return true;
3300  }
3301 
3302  // Are all operands of a build vector constant powers of two?
3303  if (Val.getOpcode() == ISD::BUILD_VECTOR)
3304  if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3305  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3306  return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3307  return false;
3308  }))
3309  return true;
3310 
3311  // More could be done here, though the above checks are enough
3312  // to handle some common cases.
3313 
3314  // Fall back to computeKnownBits to catch other known cases.
3315  KnownBits Known = computeKnownBits(Val);
3316  return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3317 }
3318 
3319 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3320  EVT VT = Op.getValueType();
3321  APInt DemandedElts = VT.isVector()
3323  : APInt(1, 1);
3324  return ComputeNumSignBits(Op, DemandedElts, Depth);
3325 }
3326 
3327 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3328  unsigned Depth) const {
3329  EVT VT = Op.getValueType();
3330  assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3331  unsigned VTBits = VT.getScalarSizeInBits();
3332  unsigned NumElts = DemandedElts.getBitWidth();
3333  unsigned Tmp, Tmp2;
3334  unsigned FirstAnswer = 1;
3335 
3336  if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3337  const APInt &Val = C->getAPIntValue();
3338  return Val.getNumSignBits();
3339  }
3340 
3341  if (Depth == 6)
3342  return 1; // Limit search depth.
3343 
3344  if (!DemandedElts)
3345  return 1; // No demanded elts, better to assume we don't know anything.
3346 
3347  unsigned Opcode = Op.getOpcode();
3348  switch (Opcode) {
3349  default: break;
3350  case ISD::AssertSext:
3351  Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3352  return VTBits-Tmp+1;
3353  case ISD::AssertZext:
3354  Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3355  return VTBits-Tmp;
3356 
3357  case ISD::BUILD_VECTOR:
3358  Tmp = VTBits;
3359  for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3360  if (!DemandedElts[i])
3361  continue;
3362 
3363  SDValue SrcOp = Op.getOperand(i);
3364  Tmp2 = ComputeNumSignBits(Op.getOperand(i), Depth + 1);
3365 
3366  // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3367  if (SrcOp.getValueSizeInBits() != VTBits) {
3368  assert(SrcOp.getValueSizeInBits() > VTBits &&
3369  "Expected BUILD_VECTOR implicit truncation");
3370  unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3371  Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3372  }
3373  Tmp = std::min(Tmp, Tmp2);
3374  }
3375  return Tmp;
3376 
3377  case ISD::VECTOR_SHUFFLE: {
3378  // Collect the minimum number of sign bits that are shared by every vector
3379  // element referenced by the shuffle.
3380  APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3381  const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3382  assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3383  for (unsigned i = 0; i != NumElts; ++i) {
3384  int M = SVN->getMaskElt(i);
3385  if (!DemandedElts[i])
3386  continue;
3387  // For UNDEF elements, we don't know anything about the common state of
3388  // the shuffle result.
3389  if (M < 0)
3390  return 1;
3391  if ((unsigned)M < NumElts)
3392  DemandedLHS.setBit((unsigned)M % NumElts);
3393  else
3394  DemandedRHS.setBit((unsigned)M % NumElts);
3395  }
3397  if (!!DemandedLHS)
3398  Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3399  if (!!DemandedRHS) {
3400  Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3401  Tmp = std::min(Tmp, Tmp2);
3402  }
3403  // If we don't know anything, early out and try computeKnownBits fall-back.
3404  if (Tmp == 1)
3405  break;
3406  assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3407  return Tmp;
3408  }
3409 
3410  case ISD::BITCAST: {
3411  SDValue N0 = Op.getOperand(0);
3412  EVT SrcVT = N0.getValueType();
3413  unsigned SrcBits = SrcVT.getScalarSizeInBits();
3414 
3415  // Ignore bitcasts from unsupported types..
3416  if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3417  break;
3418 
3419  // Fast handling of 'identity' bitcasts.
3420  if (VTBits == SrcBits)
3421  return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3422 
3423  bool IsLE = getDataLayout().isLittleEndian();
3424 
3425  // Bitcast 'large element' scalar/vector to 'small element' vector.
3426  if ((SrcBits % VTBits) == 0) {
3427  assert(VT.isVector() && "Expected bitcast to vector");
3428 
3429  unsigned Scale = SrcBits / VTBits;
3430  APInt SrcDemandedElts(NumElts / Scale, 0);
3431  for (unsigned i = 0; i != NumElts; ++i)
3432  if (DemandedElts[i])
3433  SrcDemandedElts.setBit(i / Scale);
3434 
3435  // Fast case - sign splat can be simply split across the small elements.
3436  Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3437  if (Tmp == SrcBits)
3438  return VTBits;
3439 
3440  // Slow case - determine how far the sign extends into each sub-element.
3441  Tmp2 = VTBits;
3442  for (unsigned i = 0; i != NumElts; ++i)
3443  if (DemandedElts[i]) {
3444  unsigned SubOffset = i % Scale;
3445  SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3446  SubOffset = SubOffset * VTBits;
3447  if (Tmp <= SubOffset)
3448  return 1;
3449  Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3450  }
3451  return Tmp2;
3452  }
3453  break;
3454  }
3455 
3456  case ISD::SIGN_EXTEND:
3457  Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3458  return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3460  // Max of the input and what this extends.
3461  Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3462  Tmp = VTBits-Tmp+1;
3463  Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3464  return std::max(Tmp, Tmp2);
3466  SDValue Src = Op.getOperand(0);
3467  EVT SrcVT = Src.getValueType();
3468  APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3469  Tmp = VTBits - SrcVT.getScalarSizeInBits();
3470  return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3471  }
3472 
3473  case ISD::SRA:
3474  Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3475  // SRA X, C -> adds C sign bits.
3476  if (ConstantSDNode *C =
3477  isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3478  APInt ShiftVal = C->getAPIntValue();
3479  ShiftVal += Tmp;
3480  Tmp = ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
3481  }
3482  return Tmp;
3483  case ISD::SHL:
3484  if (ConstantSDNode *C =
3485  isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3486  // shl destroys sign bits.
3487  Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3488  if (C->getAPIntValue().uge(VTBits) || // Bad shift.
3489  C->getAPIntValue().uge(Tmp)) break; // Shifted all sign bits out.
3490  return Tmp - C->getZExtValue();
3491  }
3492  break;
3493  case ISD::AND:
3494  case ISD::OR:
3495  case ISD::XOR: // NOT is handled here.
3496  // Logical binary ops preserve the number of sign bits at the worst.
3497  Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3498  if (Tmp != 1) {
3499  Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3500  FirstAnswer = std::min(Tmp, Tmp2);
3501  // We computed what we know about the sign bits as our first
3502  // answer. Now proceed to the generic code that uses
3503  // computeKnownBits, and pick whichever answer is better.
3504  }
3505  break;
3506 
3507  case ISD::SELECT:
3508  case ISD::VSELECT:
3509  Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3510  if (Tmp == 1) return 1; // Early out.
3511  Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3512  return std::min(Tmp, Tmp2);
3513  case ISD::SELECT_CC:
3514  Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3515  if (Tmp == 1) return 1; // Early out.
3516  Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3517  return std::min(Tmp, Tmp2);
3518 
3519  case ISD::SMIN:
3520  case ISD::SMAX: {
3521  // If we have a clamp pattern, we know that the number of sign bits will be
3522  // the minimum of the clamp min/max range.
3523  bool IsMax = (Opcode == ISD::SMAX);
3524  ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3525  if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3526  if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3527  CstHigh =
3528  isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3529  if (CstLow && CstHigh) {
3530  if (!IsMax)
3531  std::swap(CstLow, CstHigh);
3532  if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3533  Tmp = CstLow->getAPIntValue().getNumSignBits();
3534  Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3535  return std::min(Tmp, Tmp2);
3536  }
3537  }
3538 
3539  // Fallback - just get the minimum number of sign bits of the operands.
3540  Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3541  if (Tmp == 1)
3542  return 1; // Early out.
3543  Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3544  return std::min(Tmp, Tmp2);
3545  }
3546  case ISD::UMIN:
3547  case ISD::UMAX:
3548  Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3549  if (Tmp == 1)
3550  return 1; // Early out.
3551  Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3552  return std::min(Tmp, Tmp2);
3553  case ISD::SADDO:
3554  case ISD::UADDO:
3555  case ISD::SSUBO:
3556  case ISD::USUBO:
3557  case ISD::SMULO:
3558  case ISD::UMULO:
3559  if (Op.getResNo() != 1)
3560  break;
3561  // The boolean result conforms to getBooleanContents. Fall through.
3562  // If setcc returns 0/-1, all bits are sign bits.
3563  // We know that we have an integer-based boolean since these operations
3564  // are only available for integer.
3565  if (TLI->getBooleanContents(VT.isVector(), false) ==
3567  return VTBits;
3568  break;
3569  case ISD::SETCC:
3570  // If setcc returns 0/-1, all bits are sign bits.
3571  if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3573  return VTBits;
3574  break;
3575  case ISD::ROTL:
3576  case ISD::ROTR:
3577  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3578  unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3579 
3580  // Handle rotate right by N like a rotate left by 32-N.
3581  if (Opcode == ISD::ROTR)
3582  RotAmt = (VTBits - RotAmt) % VTBits;
3583 
3584  // If we aren't rotating out all of the known-in sign bits, return the
3585  // number that are left. This handles rotl(sext(x), 1) for example.
3586  Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3587  if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3588  }
3589  break;
3590  case ISD::ADD:
3591  case ISD::ADDC:
3592  // Add can have at most one carry bit. Thus we know that the output
3593  // is, at worst, one more bit than the inputs.
3594  Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3595  if (Tmp == 1) return 1; // Early out.
3596 
3597  // Special case decrementing a value (ADD X, -1):
3598  if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3599  if (CRHS->isAllOnesValue()) {
3600  KnownBits Known = computeKnownBits(Op.getOperand(0), Depth+1);
3601 
3602  // If the input is known to be 0 or 1, the output is 0/-1, which is all
3603  // sign bits set.
3604  if ((Known.Zero | 1).isAllOnesValue())
3605  return VTBits;
3606 
3607  // If we are subtracting one from a positive number, there is no carry
3608  // out of the result.
3609  if (Known.isNonNegative())
3610  return Tmp;
3611  }
3612 
3613  Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3614  if (Tmp2 == 1) return 1;
3615  return std::min(Tmp, Tmp2)-1;
3616 
3617  case ISD::SUB:
3618  Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3619  if (Tmp2 == 1) return 1;
3620 
3621  // Handle NEG.
3622  if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0)))
3623  if (CLHS->isNullValue()) {
3624  KnownBits Known = computeKnownBits(Op.getOperand(1), Depth+1);
3625  // If the input is known to be 0 or 1, the output is 0/-1, which is all
3626  // sign bits set.
3627  if ((Known.Zero | 1).isAllOnesValue())
3628  return VTBits;
3629 
3630  // If the input is known to be positive (the sign bit is known clear),
3631  // the output of the NEG has the same number of sign bits as the input.
3632  if (Known.isNonNegative())
3633  return Tmp2;
3634 
3635  // Otherwise, we treat this like a SUB.
3636  }
3637 
3638  // Sub can have at most one carry bit. Thus we know that the output
3639  // is, at worst, one more bit than the inputs.
3640  Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3641  if (Tmp == 1) return 1; // Early out.
3642  return std::min(Tmp, Tmp2)-1;
3643  case ISD::TRUNCATE: {
3644  // Check if the sign bits of source go down as far as the truncated value.
3645  unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3646  unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3647  if (NumSrcSignBits > (NumSrcBits - VTBits))
3648  return NumSrcSignBits - (NumSrcBits - VTBits);
3649  break;
3650  }
3651  case ISD::EXTRACT_ELEMENT: {
3652  const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3653  const int BitWidth = Op.getValueSizeInBits();
3654  const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3655 
3656  // Get reverse index (starting from 1), Op1 value indexes elements from
3657  // little end. Sign starts at big end.
3658  const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3659 
3660  // If the sign portion ends in our element the subtraction gives correct
3661  // result. Otherwise it gives either negative or > bitwidth result
3662  return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3663  }
3664  case ISD::INSERT_VECTOR_ELT: {
3665  SDValue InVec = Op.getOperand(0);
3666  SDValue InVal = Op.getOperand(1);
3667  SDValue EltNo = Op.getOperand(2);
3668 
3669  ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3670  if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3671  // If we know the element index, split the demand between the
3672  // source vector and the inserted element.
3673  unsigned EltIdx = CEltNo->getZExtValue();
3674 
3675  // If we demand the inserted element then get its sign bits.
3677  if (DemandedElts[EltIdx]) {
3678  // TODO - handle implicit truncation of inserted elements.
3679  if (InVal.getScalarValueSizeInBits() != VTBits)
3680  break;
3681  Tmp = ComputeNumSignBits(InVal, Depth + 1);
3682  }
3683 
3684  // If we demand the source vector then get its sign bits, and determine
3685  // the minimum.
3686  APInt VectorElts = DemandedElts;
3687  VectorElts.clearBit(EltIdx);
3688  if (!!VectorElts) {
3689  Tmp2 = ComputeNumSignBits(InVec, VectorElts, Depth + 1);
3690  Tmp = std::min(Tmp, Tmp2);
3691  }
3692  } else {
3693  // Unknown element index, so ignore DemandedElts and demand them all.
3694  Tmp = ComputeNumSignBits(InVec, Depth + 1);
3695  Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
3696  Tmp = std::min(Tmp, Tmp2);
3697  }
3698  assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3699  return Tmp;
3700  }
3701  case ISD::EXTRACT_VECTOR_ELT: {
3702  SDValue InVec = Op.getOperand(0);
3703  SDValue EltNo = Op.getOperand(1);
3704  EVT VecVT = InVec.getValueType();
3705  const unsigned BitWidth = Op.getValueSizeInBits();
3706  const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
3707  const unsigned NumSrcElts = VecVT.getVectorNumElements();
3708 
3709  // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
3710  // anything about sign bits. But if the sizes match we can derive knowledge
3711  // about sign bits from the vector operand.
3712  if (BitWidth != EltBitWidth)
3713  break;
3714 
3715  // If we know the element index, just demand that vector element, else for
3716  // an unknown element index, ignore DemandedElts and demand them all.
3717  APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3718  ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3719  if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3720  DemandedSrcElts =
3721  APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3722 
3723  return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
3724  }
3725  case ISD::EXTRACT_SUBVECTOR: {
3726  // If we know the element index, just demand that subvector elements,
3727  // otherwise demand them all.
3728  SDValue Src = Op.getOperand(0);
3730  unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3731  if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
3732  // Offset the demanded elts by the subvector index.
3733  uint64_t Idx = SubIdx->getZExtValue();
3734  APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
3735  return ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
3736  }
3737  return ComputeNumSignBits(Src, Depth + 1);
3738  }
3739  case ISD::CONCAT_VECTORS: {
3740  // Determine the minimum number of sign bits across all demanded
3741  // elts of the input vectors. Early out if the result is already 1.
3743  EVT SubVectorVT = Op.getOperand(0).getValueType();
3744  unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3745  unsigned NumSubVectors = Op.getNumOperands();
3746  for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
3747  APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
3748  DemandedSub = DemandedSub.trunc(NumSubVectorElts);
3749  if (!DemandedSub)
3750  continue;
3751  Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
3752  Tmp = std::min(Tmp, Tmp2);
3753  }
3754  assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3755  return Tmp;
3756  }
3757  case ISD::INSERT_SUBVECTOR: {
3758  // If we know the element index, demand any elements from the subvector and
3759  // the remainder from the src its inserted into, otherwise demand them all.
3760  SDValue Src = Op.getOperand(0);
3761  SDValue Sub = Op.getOperand(1);
3762  auto *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3763  unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3764  if (SubIdx && SubIdx->getAPIntValue().ule(NumElts - NumSubElts)) {
3766  uint64_t Idx = SubIdx->getZExtValue();
3767  APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3768  if (!!DemandedSubElts) {
3769  Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
3770  if (Tmp == 1) return 1; // early-out
3771  }
3772  APInt SubMask = APInt::getBitsSet(NumElts, Idx, Idx + NumSubElts);
3773  APInt DemandedSrcElts = DemandedElts & ~SubMask;
3774  if (!!DemandedSrcElts) {
3775  Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
3776  Tmp = std::min(Tmp, Tmp2);
3777  }
3778  assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3779  return Tmp;
3780  }
3781 
3782  // Not able to determine the index so just assume worst case.
3783  Tmp = ComputeNumSignBits(Sub, Depth + 1);
3784  if (Tmp == 1) return 1; // early-out
3785  Tmp2 = ComputeNumSignBits(Src, Depth + 1);
3786  Tmp = std::min(Tmp, Tmp2);
3787  assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3788  return Tmp;
3789  }
3790  }
3791 
3792  // If we are looking at the loaded value of the SDNode.
3793  if (Op.getResNo() == 0) {
3794  // Handle LOADX separately here. EXTLOAD case will fallthrough.
3795  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
3796  unsigned ExtType = LD->getExtensionType();
3797  switch (ExtType) {
3798  default: break;
3799  case ISD::SEXTLOAD: // '17' bits known
3800  Tmp = LD->getMemoryVT().getScalarSizeInBits();
3801  return VTBits-Tmp+1;
3802  case ISD::ZEXTLOAD: // '16' bits known
3803  Tmp = LD->getMemoryVT().getScalarSizeInBits();
3804  return VTBits-Tmp;
3805  }
3806  }
3807  }
3808 
3809  // Allow the target to implement this method for its nodes.
3810  if (Opcode >= ISD::BUILTIN_OP_END ||
3811  Opcode == ISD::INTRINSIC_WO_CHAIN ||
3812  Opcode == ISD::INTRINSIC_W_CHAIN ||
3813  Opcode == ISD::INTRINSIC_VOID) {
3814  unsigned NumBits =
3815  TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
3816  if (NumBits > 1)
3817  FirstAnswer = std::max(FirstAnswer, NumBits);
3818  }
3819 
3820  // Finally, if we can prove that the top bits of the result are 0's or 1's,
3821  // use this information.
3822  KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
3823 
3824  APInt Mask;
3825  if (Known.isNonNegative()) { // sign bit is 0
3826  Mask = Known.Zero;
3827  } else if (Known.isNegative()) { // sign bit is 1;
3828  Mask = Known.One;
3829  } else {
3830  // Nothing known.
3831  return FirstAnswer;
3832  }
3833 
3834  // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
3835  // the number of identical bits in the top of the input value.
3836  Mask = ~Mask;
3837  Mask <<= Mask.getBitWidth()-VTBits;
3838  // Return # leading zeros. We use 'min' here in case Val was zero before
3839  // shifting. We don't want to return '64' as for an i32 "0".
3840  return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
3841 }
3842 
3844  if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
3845  !isa<ConstantSDNode>(Op.getOperand(1)))
3846  return false;
3847 
3848  if (Op.getOpcode() == ISD::OR &&
3850  return false;
3851 
3852  return true;
3853 }
3854 
3855 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
3856  // If we're told that NaNs won't happen, assume they won't.
3857  if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
3858  return true;
3859 
3860  if (Depth == 6)
3861  return false; // Limit search depth.
3862 
3863  // TODO: Handle vectors.
3864  // If the value is a constant, we can obviously see if it is a NaN or not.
3865  if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
3866  return !C->getValueAPF().isNaN() ||
3867  (SNaN && !C->getValueAPF().isSignaling());
3868  }
3869 
3870  unsigned Opcode = Op.getOpcode();
3871  switch (Opcode) {
3872  case ISD::FADD:
3873  case ISD::FSUB:
3874  case ISD::FMUL:
3875  case ISD::FDIV:
3876  case ISD::FREM:
3877  case ISD::FSIN:
3878  case ISD::FCOS: {
3879  if (SNaN)
3880  return true;
3881  // TODO: Need isKnownNeverInfinity
3882  return false;
3883  }
3884  case ISD::FCANONICALIZE:
3885  case ISD::FEXP:
3886  case ISD::FEXP2:
3887  case ISD::FTRUNC:
3888  case ISD::FFLOOR:
3889  case ISD::FCEIL:
3890  case ISD::FROUND:
3891  case ISD::FRINT:
3892  case ISD::FNEARBYINT: {
3893  if (SNaN)
3894  return true;
3895  return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
3896  }
3897  case ISD::FABS:
3898  case ISD::FNEG:
3899  case ISD::FCOPYSIGN: {
3900  return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
3901  }
3902  case ISD::SELECT:
3903  return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
3904  isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
3905  case ISD::FP_EXTEND:
3906  case ISD::FP_ROUND: {
3907  if (SNaN)
3908  return true;
3909  return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
3910  }
3911  case ISD::SINT_TO_FP:
3912  case ISD::UINT_TO_FP:
3913  return true;
3914  case ISD::FMA:
3915  case ISD::FMAD: {
3916  if (SNaN)
3917  return true;
3918  return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
3919  isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
3920  isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
3921  }
3922  case ISD::FSQRT: // Need is known positive
3923  case ISD::FLOG:
3924  case ISD::FLOG2:
3925  case ISD::FLOG10:
3926  case ISD::FPOWI:
3927  case ISD::FPOW: {
3928  if (SNaN)
3929  return true;
3930  // TODO: Refine on operand
3931  return false;
3932  }
3933  case ISD::FMINNUM:
3934  case ISD::FMAXNUM: {
3935  // Only one needs to be known not-nan, since it will be returned if the
3936  // other ends up being one.
3937  return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
3938  isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
3939  }
3940  case ISD::FMINNUM_IEEE:
3941  case ISD::FMAXNUM_IEEE: {
3942  if (SNaN)
3943  return true;
3944  // This can return a NaN if either operand is an sNaN, or if both operands
3945  // are NaN.
3946  return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
3947  isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
3948  (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
3949  isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
3950  }
3951  case ISD::FMINIMUM:
3952  case ISD::FMAXIMUM: {
3953  // TODO: Does this quiet or return the origina NaN as-is?
3954  return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
3955  isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
3956  }
3957  case ISD::EXTRACT_VECTOR_ELT: {
3958  return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
3959  }
3960  default:
3961  if (Opcode >= ISD::BUILTIN_OP_END ||
3962  Opcode == ISD::INTRINSIC_WO_CHAIN ||
3963  Opcode == ISD::INTRINSIC_W_CHAIN ||
3964  Opcode == ISD::INTRINSIC_VOID) {
3965  return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
3966  }
3967 
3968  return false;
3969  }
3970 }
3971 
3974  "Floating point type expected");
3975 
3976  // If the value is a constant, we can obviously see if it is a zero or not.
3977  // TODO: Add BuildVector support.
3978  if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
3979  return !C->isZero();
3980  return false;
3981 }
3982 
3985  "Floating point types unsupported - use isKnownNeverZeroFloat");
3986 
3987  // If the value is a constant, we can obviously see if it is a zero or not.
3989  Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
3990  return true;
3991 
3992  // TODO: Recognize more cases here.
3993  switch (Op.getOpcode()) {
3994  default: break;
3995  case ISD::OR:
3996  if (isKnownNeverZero(Op.getOperand(1)) ||
3998  return true;
3999  break;
4000  }
4001 
4002  return false;
4003 }
4004 
4006  // Check the obvious case.
4007  if (A == B) return true;
4008 
4009  // For for negative and positive zero.
4010  if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4011  if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4012  if (CA->isZero() && CB->isZero()) return true;
4013 
4014  // Otherwise they may not be equal.
4015  return false;
4016 }
4017 
4018 // FIXME: unify with llvm::haveNoCommonBitsSet.
4019 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4021  assert(A.getValueType() == B.getValueType() &&
4022  "Values must have the same type");
4023  return (computeKnownBits(A).Zero | computeKnownBits(B).Zero).isAllOnesValue();
4024 }
4025 
4026 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4027  ArrayRef<SDValue> Ops,
4028  SelectionDAG &DAG) {
4029  int NumOps = Ops.size();
4030  assert(NumOps != 0 && "Can't build an empty vector!");
4031  assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4032  "Incorrect element count in BUILD_VECTOR!");
4033 
4034  // BUILD_VECTOR of UNDEFs is UNDEF.
4035  if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4036  return DAG.getUNDEF(VT);
4037 
4038  // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4039  SDValue IdentitySrc;
4040  bool IsIdentity = true;
4041  for (int i = 0; i != NumOps; ++i) {
4042  if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4043  Ops[i].getOperand(0).getValueType() != VT ||
4044  (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4045  !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4046  cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4047  IsIdentity = false;
4048  break;
4049  }
4050  IdentitySrc = Ops[i].getOperand(0);
4051  }
4052  if (IsIdentity)
4053  return IdentitySrc;
4054 
4055  return SDValue();
4056 }
4057 
4058 static SDValue FoldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4059  ArrayRef<SDValue> Ops,
4060  SelectionDAG &DAG) {
4061  assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4062  assert(llvm::all_of(Ops,
4063  [Ops](SDValue Op) {
4064  return Ops[0].getValueType() == Op.getValueType();
4065  }) &&
4066  "Concatenation of vectors with inconsistent value types!");
4067  assert((Ops.size() * Ops[0].getValueType().getVectorNumElements()) ==
4068  VT.getVectorNumElements() &&
4069  "Incorrect element count in vector concatenation!");
4070 
4071  if (Ops.size() == 1)
4072  return Ops[0];
4073 
4074  // Concat of UNDEFs is UNDEF.
4075  if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4076  return DAG.getUNDEF(VT);
4077 
4078  // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4079  // simplified to one big BUILD_VECTOR.
4080  // FIXME: Add support for SCALAR_TO_VECTOR as well.
4081  EVT SVT = VT.getScalarType();
4083  for (SDValue Op : Ops) {
4084  EVT OpVT = Op.getValueType();
4085  if (Op.isUndef())
4086  Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4087  else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4088  Elts.append(Op->op_begin(), Op->op_end());
4089  else
4090  return SDValue();
4091  }
4092 
4093  // BUILD_VECTOR requires all inputs to be of the same type, find the
4094  // maximum type and extend them all.
4095  for (SDValue Op : Elts)
4096  SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4097 
4098  if (SVT.bitsGT(VT.getScalarType()))
4099  for (SDValue &Op : Elts)
4100  Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4101  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4102  : DAG.getSExtOrTrunc(Op, DL, SVT);
4103 
4104  SDValue V = DAG.getBuildVector(VT, DL, Elts);
4105  NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4106  return V;
4107 }
4108 
4109 /// Gets or creates the specified node.
4110 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4112  AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4113  void *IP = nullptr;
4114  if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4115  return SDValue(E, 0);
4116 
4117  auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4118  getVTList(VT));
4119  CSEMap.InsertNode(N, IP);
4120 
4121  InsertNode(N);
4122  SDValue V = SDValue(N, 0);
4123  NewSDValueDbgMsg(V, "Creating new node: ", this);
4124  return V;
4125 }
4126 
4127 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4128  SDValue Operand, const SDNodeFlags Flags) {
4129  // Constant fold unary operations with an integer constant operand. Even
4130  // opaque constant will be folded, because the folding of unary operations
4131  // doesn't create new constants with different values. Nevertheless, the
4132  // opaque flag is preserved during folding to prevent future folding with
4133  // other constants.
4134  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4135  const APInt &Val = C->getAPIntValue();
4136  switch (Opcode) {
4137  default: break;
4138  case ISD::SIGN_EXTEND:
4139  return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4140  C->isTargetOpcode(), C->isOpaque());
4141  case ISD::TRUNCATE:
4142  if (C->isOpaque())
4143  break;
4145  case ISD::ANY_EXTEND:
4146  case ISD::ZERO_EXTEND:
4147  return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4148  C->isTargetOpcode(), C->isOpaque());
4149  case ISD::UINT_TO_FP:
4150  case ISD::SINT_TO_FP: {
4153  (void)apf.convertFromAPInt(Val,
4154  Opcode==ISD::SINT_TO_FP,
4156  return getConstantFP(apf, DL, VT);
4157  }
4158  case ISD::BITCAST:
4159  if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4160  return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4161  if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4162  return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4163  if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4164  return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4165  if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4166  return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4167  break;
4168  case ISD::ABS:
4169  return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4170  C->isOpaque());
4171  case ISD::BITREVERSE:
4172  return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4173  C->isOpaque());
4174  case ISD::BSWAP:
4175  return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4176  C->isOpaque());
4177  case ISD::CTPOP:
4178  return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4179  C->isOpaque());
4180  case ISD::CTLZ:
4181  case ISD::CTLZ_ZERO_UNDEF:
4182  return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4183  C->isOpaque());
4184  case ISD::CTTZ:
4185  case ISD::CTTZ_ZERO_UNDEF:
4186  return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4187  C->isOpaque());
4188  case ISD::FP16_TO_FP: {
4189  bool Ignored;
4190  APFloat FPV(APFloat::IEEEhalf(),
4191  (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4192 
4193  // This can return overflow, underflow, or inexact; we don't care.
4194  // FIXME need to be more flexible about rounding mode.
4195  (void)FPV.convert(EVTToAPFloatSemantics(VT),
4196  APFloat::rmNearestTiesToEven, &Ignored);
4197  return getConstantFP(FPV, DL, VT);
4198  }
4199  }
4200  }
4201 
4202  // Constant fold unary operations with a floating point constant operand.
4203  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4204  APFloat V = C->getValueAPF(); // make copy
4205  switch (Opcode) {
4206  case ISD::FNEG:
4207  V.changeSign();
4208  return getConstantFP(V, DL, VT);
4209  case ISD::FABS:
4210  V.clearSign();
4211  return getConstantFP(V, DL, VT);
4212  case ISD::FCEIL: {
4214  if (fs == APFloat::opOK || fs == APFloat::opInexact)
4215  return getConstantFP(V, DL, VT);
4216  break;
4217  }
4218  case ISD::FTRUNC: {
4220  if (fs == APFloat::opOK || fs == APFloat::opInexact)
4221  return getConstantFP(V, DL, VT);
4222  break;
4223  }
4224  case ISD::FFLOOR: {
4226  if (fs == APFloat::opOK || fs == APFloat::opInexact)
4227  return getConstantFP(V, DL, VT);
4228  break;
4229  }
4230  case ISD::FP_EXTEND: {
4231  bool ignored;
4232  // This can return overflow, underflow, or inexact; we don't care.
4233  // FIXME need to be more flexible about rounding mode.
4234  (void)V.convert(EVTToAPFloatSemantics(VT),
4235  APFloat::rmNearestTiesToEven, &ignored);
4236  return getConstantFP(V, DL, VT);
4237  }
4238  case ISD::FP_TO_SINT:
4239  case ISD::FP_TO_UINT: {
4240  bool ignored;
4241  APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4242  // FIXME need to be more flexible about rounding mode.
4243  APFloat::opStatus s =
4245  if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4246  break;
4247  return getConstant(IntVal, DL, VT);
4248  }
4249  case ISD::BITCAST:
4250  if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4251  return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4252  else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4253  return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4254  else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4255  return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4256  break;
4257  case ISD::FP_TO_FP16: {
4258  bool Ignored;
4259  // This can return overflow, underflow, or inexact; we don't care.
4260  // FIXME need to be more flexible about rounding mode.
4261  (void)V.convert(APFloat::IEEEhalf(),
4262  APFloat::rmNearestTiesToEven, &Ignored);
4263  return getConstant(V.bitcastToAPInt(), DL, VT);
4264  }
4265  }
4266  }
4267 
4268  // Constant fold unary operations with a vector integer or float operand.
4269  if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
4270  if (BV->isConstant()) {
4271  switch (Opcode) {
4272  default:
4273  // FIXME: Entirely reasonable to perform folding of other unary
4274  // operations here as the need arises.
4275  break;
4276  case ISD::FNEG:
4277  case ISD::FABS:
4278  case ISD::FCEIL:
4279  case ISD::FTRUNC:
4280  case ISD::FFLOOR:
4281  case ISD::FP_EXTEND:
4282  case ISD::FP_TO_SINT:
4283  case ISD::FP_TO_UINT:
4284  case ISD::TRUNCATE:
4285  case ISD::ANY_EXTEND:
4286  case ISD::ZERO_EXTEND:
4287  case ISD::SIGN_EXTEND:
4288  case ISD::UINT_TO_FP:
4289  case ISD::SINT_TO_FP:
4290  case ISD::ABS:
4291  case ISD::BITREVERSE:
4292  case ISD::BSWAP:
4293  case ISD::CTLZ:
4294  case ISD::CTLZ_ZERO_UNDEF:
4295  case ISD::CTTZ:
4296  case ISD::CTTZ_ZERO_UNDEF:
4297  case ISD::CTPOP: {
4298  SDValue Ops = { Operand };
4299  if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4300  return Fold;
4301  }
4302  }
4303  }
4304  }
4305 
4306  unsigned OpOpcode = Operand.getNode()->getOpcode();
4307  switch (Opcode) {
4308  case ISD::TokenFactor:
4309  case ISD::MERGE_VALUES:
4310  case ISD::CONCAT_VECTORS:
4311  return Operand; // Factor, merge or concat of one node? No need.
4312  case ISD::BUILD_VECTOR: {
4313  // Attempt to simplify BUILD_VECTOR.
4314  SDValue Ops[] = {Operand};
4315  if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4316  return V;
4317  break;
4318  }
4319  case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4320  case ISD::FP_EXTEND:
4321  assert(VT.isFloatingPoint() &&
4322  Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4323  if (Operand.getValueType() == VT) return Operand; // noop conversion.
4324  assert((!VT.isVector() ||
4325  VT.getVectorNumElements() ==
4326  Operand.getValueType().getVectorNumElements()) &&
4327  "Vector element count mismatch!");
4328  assert(Operand.getValueType().bitsLT(VT) &&
4329  "Invalid fpext node, dst < src!");
4330  if (Operand.isUndef())
4331  return getUNDEF(VT);
4332  break;
4333  case ISD::SIGN_EXTEND:
4334  assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4335  "Invalid SIGN_EXTEND!");
4336  assert(VT.isVector() == Operand.getValueType().isVector() &&
4337  "SIGN_EXTEND result type type should be vector iff the operand "
4338  "type is vector!");
4339  if (Operand.getValueType() == VT) return Operand; // noop extension
4340  assert((!VT.isVector() ||
4341  VT.getVectorNumElements() ==
4342  Operand.getValueType().getVectorNumElements()) &&
4343  "Vector element count mismatch!");
4344  assert(Operand.getValueType().bitsLT(VT) &&
4345  "Invalid sext node, dst < src!");
4346  if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4347  return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4348  else if (OpOpcode == ISD::UNDEF)
4349  // sext(undef) = 0, because the top bits will all be the same.
4350  return getConstant(0, DL, VT);
4351  break;
4352  case ISD::ZERO_EXTEND:
4353  assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4354  "Invalid ZERO_EXTEND!");
4355  assert(VT.isVector() == Operand.getValueType().isVector() &&
4356  "ZERO_EXTEND result type type should be vector iff the operand "
4357  "type is vector!");
4358  if (Operand.getValueType() == VT) return Operand; // noop extension
4359  assert((!VT.isVector() ||
4360  VT.getVectorNumElements() ==
4361  Operand.getValueType().getVectorNumElements()) &&
4362  "Vector element count mismatch!");
4363  assert(Operand.getValueType().bitsLT(VT) &&
4364  "Invalid zext node, dst < src!");
4365  if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
4366  return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4367  else if (OpOpcode == ISD::UNDEF)
4368  // zext(undef) = 0, because the top bits will be zero.
4369  return getConstant(0, DL, VT);
4370  break;
4371  case ISD::ANY_EXTEND:
4372  assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4373  "Invalid ANY_EXTEND!");
4374  assert(VT.isVector() == Operand.getValueType().isVector() &&
4375  "ANY_EXTEND result type type should be vector iff the operand "
4376  "type is vector!");
4377  if (Operand.getValueType() == VT) return Operand; // noop extension
4378  assert((!VT.isVector() ||
4379  VT.getVectorNumElements() ==
4380  Operand.getValueType().getVectorNumElements()) &&
4381  "Vector element count mismatch!");
4382  assert(Operand.getValueType().bitsLT(VT) &&
4383  "Invalid anyext node, dst < src!");
4384 
4385  if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4386  OpOpcode == ISD::ANY_EXTEND)
4387  // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
4388  return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4389  else if (OpOpcode == ISD::UNDEF)
4390  return getUNDEF(VT);
4391 
4392  // (ext (trunc x)) -> x
4393  if (OpOpcode == ISD::TRUNCATE) {
4394  SDValue OpOp = Operand.getOperand(0);
4395  if (OpOp.getValueType() == VT) {
4396  transferDbgValues(Operand, OpOp);
4397  return OpOp;
4398  }
4399  }
4400  break;
4401  case ISD::TRUNCATE:
4402  assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4403  "Invalid TRUNCATE!");
4404  assert(VT.isVector() == Operand.getValueType().isVector() &&
4405  "TRUNCATE result type type should be vector iff the operand "
4406  "type is vector!");
4407  if (Operand.getValueType() == VT) return Operand; // noop truncate
4408  assert((!VT.isVector() ||
4409  VT.getVectorNumElements() ==
4410  Operand.getValueType().getVectorNumElements()) &&
4411  "Vector element count mismatch!");
4412  assert(Operand.getValueType().bitsGT(VT) &&
4413  "Invalid truncate node, src < dst!");
4414  if (OpOpcode == ISD::TRUNCATE)
4415  return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4416  if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4417  OpOpcode == ISD::ANY_EXTEND) {
4418  // If the source is smaller than the dest, we still need an extend.
4419  if (Operand.getOperand(0).getValueType().getScalarType()
4420  .bitsLT(VT.getScalarType()))
4421  return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4422  if (Operand.getOperand(0).getValueType().bitsGT(VT))
4423  return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4424  return Operand.getOperand(0);
4425  }
4426  if (OpOpcode == ISD::UNDEF)
4427  return getUNDEF(VT);
4428  break;
4432  assert(VT.isVector() && "This DAG node is restricted to vector types.");
4433  assert(Operand.getValueType().bitsLE(VT) &&
4434  "The input must be the same size or smaller than the result.");
4436  Operand.getValueType().getVectorNumElements() &&
4437  "The destination vector type must have fewer lanes than the input.");
4438  break;
4439  case ISD::ABS:
4440  assert(VT.isInteger() && VT == Operand.getValueType() &&
4441  "Invalid ABS!");
4442  if (OpOpcode == ISD::UNDEF)
4443  return getUNDEF(VT);
4444  break;
4445  case ISD::BSWAP:
4446  assert(VT.isInteger() && VT == Operand.getValueType() &&
4447  "Invalid BSWAP!");
4448  assert((VT.getScalarSizeInBits() % 16 == 0) &&
4449  "BSWAP types must be a multiple of 16 bits!");
4450  if (OpOpcode == ISD::UNDEF)
4451  return getUNDEF(VT);
4452  break;
4453  case ISD::BITREVERSE:
4454  assert(VT.isInteger() && VT == Operand.getValueType() &&
4455  "Invalid BITREVERSE!");
4456  if (OpOpcode == ISD::UNDEF)
4457  return getUNDEF(VT);
4458  break;
4459  case ISD::BITCAST:
4460  // Basic sanity checking.
4461  assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
4462  "Cannot BITCAST between types of different sizes!");
4463  if (VT == Operand.getValueType()) return Operand; // noop conversion.
4464  if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
4465  return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
4466  if (OpOpcode == ISD::UNDEF)
4467  return getUNDEF(VT);
4468  break;
4469  case ISD::SCALAR_TO_VECTOR:
4470  assert(VT.isVector() && !Operand.getValueType().isVector() &&
4471  (VT.getVectorElementType() == Operand.getValueType() ||
4472  (VT.getVectorElementType().isInteger() &&
4473  Operand.getValueType().isInteger() &&
4474  VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
4475  "Illegal SCALAR_TO_VECTOR node!");
4476  if (OpOpcode == ISD::UNDEF)
4477  return getUNDEF(VT);
4478  // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
4479  if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
4480  isa<ConstantSDNode>(Operand.getOperand(1)) &&
4481  Operand.getConstantOperandVal(1) == 0 &&
4482  Operand.getOperand(0).getValueType() == VT)
4483  return Operand.getOperand(0);
4484  break;
4485  case ISD::FNEG:
4486  // Negation of an unknown bag of bits is still completely undefined.
4487  if (OpOpcode == ISD::UNDEF)
4488  return getUNDEF(VT);
4489 
4490  // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
4491  if ((getTarget().Options.UnsafeFPMath || Flags.hasNoSignedZeros()) &&
4492  OpOpcode == ISD::FSUB)
4493  return getNode(ISD::FSUB, DL, VT, Operand.getOperand(1),
4494  Operand.getOperand(0), Flags);
4495  if (OpOpcode == ISD::FNEG) // --X -> X
4496  return Operand.getOperand(0);
4497  break;
4498  case ISD::FABS:
4499  if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
4500  return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
4501  break;
4502  }
4503 
4504  SDNode *N;
4505  SDVTList VTs = getVTList(VT);
4506  SDValue Ops[] = {Operand};
4507  if (VT != MVT::Glue) { // Don't CSE flag producing nodes
4509  AddNodeIDNode(ID, Opcode, VTs, Ops);
4510  void *IP = nullptr;
4511  if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4512  E->intersectFlagsWith(Flags);
4513  return SDValue(E, 0);
4514  }
4515 
4516  N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4517  N->setFlags(Flags);
4518  createOperands(N, Ops);
4519  CSEMap.InsertNode(N, IP);
4520  } else {
4521  N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4522  createOperands(N, Ops);
4523  }
4524 
4525  InsertNode(N);
4526  SDValue V = SDValue(N, 0);
4527  NewSDValueDbgMsg(V, "Creating new node: ", this);
4528  return V;
4529 }
4530 
4531 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1,
4532  const APInt &C2) {
4533  switch (Opcode) {
4534  case ISD::ADD: return std::make_pair(C1 + C2, true);
4535  case ISD::SUB: return std::make_pair(C1 - C2, true);
4536  case ISD::MUL: return std::make_pair(C1 * C2, true);
4537  case ISD::AND: return std::make_pair(C1 & C2, true);
4538  case ISD::OR: return std::make_pair(C1 | C2, true);
4539  case ISD::XOR: return std::make_pair(C1 ^ C2, true);
4540  case ISD::SHL: return std::make_pair(C1 << C2, true);
4541  case ISD::SRL: return std::make_pair(C1.lshr(C2), true);
4542  case ISD::SRA: return std::make_pair(C1.ashr(C2), true);
4543  case ISD::ROTL: return std::make_pair(C1.rotl(C2), true);
4544  case ISD::ROTR: return std::make_pair(C1.rotr(C2), true);
4545  case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true);
4546  case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true);
4547  case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true);
4548  case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true);
4549  case ISD::SADDSAT: return std::make_pair(C1.sadd_sat(C2), true);
4550  case ISD::UADDSAT: return std::make_pair(C1.uadd_sat(C2), true);
4551  case ISD::SSUBSAT: return std::make_pair(C1.ssub_sat(C2), true);
4552  case ISD::USUBSAT: return std::make_pair(C1.usub_sat(C2), true);
4553  case ISD::UDIV:
4554  if (!C2.getBoolValue())
4555  break;
4556  return std::make_pair(C1.udiv(C2), true);
4557  case ISD::UREM:
4558  if (!C2.getBoolValue())
4559  break;
4560  return std::make_pair(C1.urem(C2), true);
4561  case ISD::SDIV:
4562  if (!C2.getBoolValue())
4563  break;
4564  return std::make_pair(C1.sdiv(C2), true);
4565  case ISD::SREM:
4566  if (!C2.getBoolValue())
4567  break;
4568  return std::make_pair(C1.srem(C2), true);
4569  }
4570  return std::make_pair(APInt(1, 0), false);
4571 }
4572 
4574  EVT VT, const ConstantSDNode *C1,
4575  const ConstantSDNode *C2) {
4576  if (C1->isOpaque() || C2->isOpaque())
4577  return SDValue();
4578 
4579  std::pair<APInt, bool> Folded = FoldValue(Opcode, C1->getAPIntValue(),
4580  C2->getAPIntValue());
4581  if (!Folded.second)
4582  return SDValue();
4583  return getConstant(Folded.first, DL, VT);
4584 }
4585 
4587  const GlobalAddressSDNode *GA,
4588  const SDNode *N2) {
4589  if (GA->getOpcode() != ISD::GlobalAddress)
4590  return SDValue();
4591  if (!TLI->isOffsetFoldingLegal(GA))
4592  return SDValue();
4593  auto *C2 = dyn_cast<ConstantSDNode>(N2);
4594  if (!C2)
4595  return SDValue();
4596  int64_t Offset = C2->getSExtValue();
4597  switch (Opcode) {
4598  case ISD::ADD: break;
4599  case ISD::SUB: Offset = -uint64_t(Offset); break;
4600  default: return SDValue();
4601  }
4602  return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
4603  GA->getOffset() + uint64_t(Offset));
4604 }
4605 
4606 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
4607  switch (Opcode) {
4608  case ISD::SDIV:
4609  case ISD::UDIV:
4610  case ISD::SREM:
4611  case ISD::UREM: {
4612  // If a divisor is zero/undef or any element of a divisor vector is
4613  // zero/undef, the whole op is undef.
4614  assert(Ops.size() == 2 && "Div/rem should have 2 operands");
4615  SDValue Divisor = Ops[1];
4616  if (Divisor.isUndef() || isNullConstant(Divisor))
4617  return true;
4618 
4619  return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
4620  llvm::any_of(Divisor->op_values(),
4621  [](SDValue V) { return V.isUndef() ||
4622  isNullConstant(V); });
4623  // TODO: Handle signed overflow.
4624  }
4625  // TODO: Handle oversized shifts.
4626  default:
4627  return false;
4628  }
4629 }
4630 
4632  EVT VT, SDNode *N1, SDNode *N2) {
4633  // If the opcode is a target-specific ISD node, there's nothing we can
4634  // do here and the operand rules may not line up with the below, so
4635  // bail early.
4636  if (Opcode >= ISD::BUILTIN_OP_END)
4637  return SDValue();
4638 
4639  if (isUndef(Opcode, {SDValue(N1, 0), SDValue(N2, 0)}))
4640  return getUNDEF(VT);
4641 
4642  // Handle the case of two scalars.
4643  if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
4644  if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) {
4645  SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, C1, C2);
4646  assert((!Folded || !VT.isVector()) &&
4647  "Can't fold vectors ops with scalar operands");
4648  return Folded;
4649  }
4650  }
4651 
4652  // fold (add Sym, c) -> Sym+c
4653  if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1))
4654  return FoldSymbolOffset(Opcode, VT, GA, N2);
4655  if (TLI->isCommutativeBinOp(Opcode))
4656  if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2))
4657  return FoldSymbolOffset(Opcode, VT, GA, N1);
4658 
4659  // For vectors, extract each constant element and fold them individually.
4660  // Either input may be an undef value.
4661  auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
4662  if (!BV1 && !N1->isUndef())
4663  return SDValue();
4664  auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
4665  if (!BV2 && !N2->isUndef())
4666  return SDValue();
4667  // If both operands are undef, that's handled the same way as scalars.
4668  if (!BV1 && !BV2)
4669  return SDValue();
4670 
4671  assert((!BV1 || !BV2 || BV1->getNumOperands() == BV2->getNumOperands()) &&
4672  "Vector binop with different number of elements in operands?");
4673 
4674  EVT SVT = VT.getScalarType();
4675  EVT LegalSVT = SVT;
4676  if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
4677  LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
4678  if (LegalSVT.bitsLT(SVT))
4679  return SDValue();
4680  }
4681  SmallVector<SDValue, 4> Outputs;
4682  unsigned NumOps = BV1 ? BV1->getNumOperands() : BV2->getNumOperands();
4683  for (unsigned I = 0; I != NumOps; ++I) {
4684  SDValue V1 = BV1 ? BV1->getOperand(I) : getUNDEF(SVT);
4685  SDValue V2 = BV2 ? BV2->getOperand(I) : getUNDEF(SVT);
4686  if (SVT.isInteger()) {
4687  if (V1->getValueType(0).bitsGT(SVT))
4688  V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
4689  if (V2->getValueType(0).bitsGT(SVT))
4690  V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
4691  }
4692 
4693  if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
4694  return SDValue();
4695 
4696  // Fold one vector element.
4697  SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
4698  if (LegalSVT != SVT)
4699  ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
4700 
4701  // Scalar folding only succeeded if the result is a constant or UNDEF.
4702  if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
4703  ScalarResult.getOpcode() != ISD::ConstantFP)
4704  return SDValue();
4705  Outputs.push_back(ScalarResult);
4706  }
4707 
4708  assert(VT.getVectorNumElements() == Outputs.size() &&
4709  "Vector size mismatch!");
4710 
4711  // We may have a vector type but a scalar result. Create a splat.
4712  Outputs.resize(VT.getVectorNumElements(), Outputs.back());
4713 
4714  // Build a big vector out of the scalar elements we generated.
4715  return getBuildVector(VT, SDLoc(), Outputs);
4716 }
4717 
4718 // TODO: Merge with FoldConstantArithmetic
4720  const SDLoc &DL, EVT VT,
4721  ArrayRef<SDValue> Ops,
4722  const SDNodeFlags Flags) {
4723  // If the opcode is a target-specific ISD node, there's nothing we can
4724  // do here and the operand rules may not line up with the below, so
4725  // bail early.
4726  if (Opcode >= ISD::BUILTIN_OP_END)
4727  return SDValue();
4728 
4729  if (isUndef(Opcode, Ops))
4730  return getUNDEF(VT);
4731 
4732  // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
4733  if (!VT.isVector())
4734  return SDValue();
4735 
4736  unsigned NumElts = VT.getVectorNumElements();
4737 
4738  auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
4739  return !Op.getValueType().isVector() ||
4740  Op.getValueType().getVectorNumElements() == NumElts;
4741  };
4742 
4743  auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
4745  return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
4746  (BV && BV->isConstant());
4747  };
4748 
4749  // All operands must be vector types with the same number of elements as
4750  // the result type and must be either UNDEF or a build vector of constant
4751  // or UNDEF scalars.
4752  if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
4753  !llvm::all_of(Ops, IsScalarOrSameVectorSize))
4754  return SDValue();
4755 
4756  // If we are comparing vectors, then the result needs to be a i1 boolean
4757  // that is then sign-extended back to the legal result type.
4758  EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
4759 
4760  // Find legal integer scalar type for constant promotion and
4761  // ensure that its scalar size is at least as large as source.
4762  EVT LegalSVT = VT.getScalarType();
4763  if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
4764  LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
4765