LLVM  10.0.0svn
TargetLowering.cpp
Go to the documentation of this file.
1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
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 TargetLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCExpr.h"
30 #include "llvm/Support/KnownBits.h"
34 #include <cctype>
35 using namespace llvm;
36 
37 /// NOTE: The TargetMachine owns TLOF.
39  : TargetLoweringBase(tm) {}
40 
41 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
42  return nullptr;
43 }
44 
47 }
48 
49 /// Check whether a given call node is in tail position within its function. If
50 /// so, it sets Chain to the input chain of the tail call.
52  SDValue &Chain) const {
53  const Function &F = DAG.getMachineFunction().getFunction();
54 
55  // Conservatively require the attributes of the call to match those of
56  // the return. Ignore NoAlias and NonNull because they don't affect the
57  // call sequence.
58  AttributeList CallerAttrs = F.getAttributes();
59  if (AttrBuilder(CallerAttrs, AttributeList::ReturnIndex)
60  .removeAttribute(Attribute::NoAlias)
61  .removeAttribute(Attribute::NonNull)
62  .hasAttributes())
63  return false;
64 
65  // It's not safe to eliminate the sign / zero extension of the return value.
66  if (CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt) ||
67  CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
68  return false;
69 
70  // Check if the only use is a function return node.
71  return isUsedByReturnOnly(Node, Chain);
72 }
73 
75  const uint32_t *CallerPreservedMask,
76  const SmallVectorImpl<CCValAssign> &ArgLocs,
77  const SmallVectorImpl<SDValue> &OutVals) const {
78  for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
79  const CCValAssign &ArgLoc = ArgLocs[I];
80  if (!ArgLoc.isRegLoc())
81  continue;
82  Register Reg = ArgLoc.getLocReg();
83  // Only look at callee saved registers.
84  if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
85  continue;
86  // Check that we pass the value used for the caller.
87  // (We look for a CopyFromReg reading a virtual register that is used
88  // for the function live-in value of register Reg)
89  SDValue Value = OutVals[I];
90  if (Value->getOpcode() != ISD::CopyFromReg)
91  return false;
92  unsigned ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
93  if (MRI.getLiveInPhysReg(ArgReg) != Reg)
94  return false;
95  }
96  return true;
97 }
98 
99 /// Set CallLoweringInfo attribute flags based on a call instruction
100 /// and called function attributes.
102  unsigned ArgIdx) {
103  IsSExt = Call->paramHasAttr(ArgIdx, Attribute::SExt);
104  IsZExt = Call->paramHasAttr(ArgIdx, Attribute::ZExt);
105  IsInReg = Call->paramHasAttr(ArgIdx, Attribute::InReg);
106  IsSRet = Call->paramHasAttr(ArgIdx, Attribute::StructRet);
107  IsNest = Call->paramHasAttr(ArgIdx, Attribute::Nest);
108  IsByVal = Call->paramHasAttr(ArgIdx, Attribute::ByVal);
109  IsInAlloca = Call->paramHasAttr(ArgIdx, Attribute::InAlloca);
110  IsReturned = Call->paramHasAttr(ArgIdx, Attribute::Returned);
111  IsSwiftSelf = Call->paramHasAttr(ArgIdx, Attribute::SwiftSelf);
112  IsSwiftError = Call->paramHasAttr(ArgIdx, Attribute::SwiftError);
113  Alignment = Call->getParamAlignment(ArgIdx);
114  ByValType = nullptr;
115  if (Call->paramHasAttr(ArgIdx, Attribute::ByVal))
116  ByValType = Call->getParamByValType(ArgIdx);
117 }
118 
119 /// Generate a libcall taking the given operands as arguments and returning a
120 /// result of type RetVT.
121 std::pair<SDValue, SDValue>
123  ArrayRef<SDValue> Ops, bool isSigned,
124  const SDLoc &dl, bool doesNotReturn,
125  bool isReturnValueUsed,
126  bool isPostTypeLegalization) const {
128  Args.reserve(Ops.size());
129 
131  for (SDValue Op : Ops) {
132  Entry.Node = Op;
133  Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
134  Entry.IsSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
135  Entry.IsZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
136  Args.push_back(Entry);
137  }
138 
139  if (LC == RTLIB::UNKNOWN_LIBCALL)
140  report_fatal_error("Unsupported library call operation!");
142  getPointerTy(DAG.getDataLayout()));
143 
144  Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
146  bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned);
147  CLI.setDebugLoc(dl)
148  .setChain(DAG.getEntryNode())
149  .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
150  .setNoReturn(doesNotReturn)
151  .setDiscardResult(!isReturnValueUsed)
152  .setIsPostTypeLegalization(isPostTypeLegalization)
153  .setSExtResult(signExtend)
154  .setZExtResult(!signExtend);
155  return LowerCallTo(CLI);
156 }
157 
158 bool
160  unsigned Limit, uint64_t Size,
161  unsigned DstAlign, unsigned SrcAlign,
162  bool IsMemset,
163  bool ZeroMemset,
164  bool MemcpyStrSrc,
165  bool AllowOverlap,
166  unsigned DstAS, unsigned SrcAS,
167  const AttributeList &FuncAttributes) const {
168  // If 'SrcAlign' is zero, that means the memory operation does not need to
169  // load the value, i.e. memset or memcpy from constant string. Otherwise,
170  // it's the inferred alignment of the source. 'DstAlign', on the other hand,
171  // is the specified alignment of the memory operation. If it is zero, that
172  // means it's possible to change the alignment of the destination.
173  // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
174  // not need to be loaded.
175  if (!(SrcAlign == 0 || SrcAlign >= DstAlign))
176  return false;
177 
178  EVT VT = getOptimalMemOpType(Size, DstAlign, SrcAlign,
179  IsMemset, ZeroMemset, MemcpyStrSrc,
180  FuncAttributes);
181 
182  if (VT == MVT::Other) {
183  // Use the largest integer type whose alignment constraints are satisfied.
184  // We only need to check DstAlign here as SrcAlign is always greater or
185  // equal to DstAlign (or zero).
186  VT = MVT::i64;
187  while (DstAlign && DstAlign < VT.getSizeInBits() / 8 &&
188  !allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign))
189  VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
190  assert(VT.isInteger());
191 
192  // Find the largest legal integer type.
193  MVT LVT = MVT::i64;
194  while (!isTypeLegal(LVT))
195  LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
196  assert(LVT.isInteger());
197 
198  // If the type we've chosen is larger than the largest legal integer type
199  // then use that instead.
200  if (VT.bitsGT(LVT))
201  VT = LVT;
202  }
203 
204  unsigned NumMemOps = 0;
205  while (Size != 0) {
206  unsigned VTSize = VT.getSizeInBits() / 8;
207  while (VTSize > Size) {
208  // For now, only use non-vector load / store's for the left-over pieces.
209  EVT NewVT = VT;
210  unsigned NewVTSize;
211 
212  bool Found = false;
213  if (VT.isVector() || VT.isFloatingPoint()) {
214  NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
215  if (isOperationLegalOrCustom(ISD::STORE, NewVT) &&
216  isSafeMemOpType(NewVT.getSimpleVT()))
217  Found = true;
218  else if (NewVT == MVT::i64 &&
221  // i64 is usually not legal on 32-bit targets, but f64 may be.
222  NewVT = MVT::f64;
223  Found = true;
224  }
225  }
226 
227  if (!Found) {
228  do {
229  NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
230  if (NewVT == MVT::i8)
231  break;
232  } while (!isSafeMemOpType(NewVT.getSimpleVT()));
233  }
234  NewVTSize = NewVT.getSizeInBits() / 8;
235 
236  // If the new VT cannot cover all of the remaining bits, then consider
237  // issuing a (or a pair of) unaligned and overlapping load / store.
238  bool Fast;
239  if (NumMemOps && AllowOverlap && NewVTSize < Size &&
240  allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign,
241  MachineMemOperand::MONone, &Fast) &&
242  Fast)
243  VTSize = Size;
244  else {
245  VT = NewVT;
246  VTSize = NewVTSize;
247  }
248  }
249 
250  if (++NumMemOps > Limit)
251  return false;
252 
253  MemOps.push_back(VT);
254  Size -= VTSize;
255  }
256 
257  return true;
258 }
259 
260 /// Soften the operands of a comparison. This code is shared among BR_CC,
261 /// SELECT_CC, and SETCC handlers.
263  SDValue &NewLHS, SDValue &NewRHS,
264  ISD::CondCode &CCCode,
265  const SDLoc &dl) const {
266  assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
267  && "Unsupported setcc type!");
268 
269  // Expand into one or more soft-fp libcall(s).
270  RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
271  bool ShouldInvertCC = false;
272  switch (CCCode) {
273  case ISD::SETEQ:
274  case ISD::SETOEQ:
275  LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
276  (VT == MVT::f64) ? RTLIB::OEQ_F64 :
277  (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
278  break;
279  case ISD::SETNE:
280  case ISD::SETUNE:
281  LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
282  (VT == MVT::f64) ? RTLIB::UNE_F64 :
283  (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
284  break;
285  case ISD::SETGE:
286  case ISD::SETOGE:
287  LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
288  (VT == MVT::f64) ? RTLIB::OGE_F64 :
289  (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
290  break;
291  case ISD::SETLT:
292  case ISD::SETOLT:
293  LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
294  (VT == MVT::f64) ? RTLIB::OLT_F64 :
295  (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
296  break;
297  case ISD::SETLE:
298  case ISD::SETOLE:
299  LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
300  (VT == MVT::f64) ? RTLIB::OLE_F64 :
301  (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
302  break;
303  case ISD::SETGT:
304  case ISD::SETOGT:
305  LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
306  (VT == MVT::f64) ? RTLIB::OGT_F64 :
307  (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
308  break;
309  case ISD::SETUO:
310  LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
311  (VT == MVT::f64) ? RTLIB::UO_F64 :
312  (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
313  break;
314  case ISD::SETO:
315  LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
316  (VT == MVT::f64) ? RTLIB::O_F64 :
317  (VT == MVT::f128) ? RTLIB::O_F128 : RTLIB::O_PPCF128;
318  break;
319  case ISD::SETONE:
320  // SETONE = SETOLT | SETOGT
321  LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
322  (VT == MVT::f64) ? RTLIB::OLT_F64 :
323  (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
324  LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
325  (VT == MVT::f64) ? RTLIB::OGT_F64 :
326  (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
327  break;
328  case ISD::SETUEQ:
329  LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
330  (VT == MVT::f64) ? RTLIB::UO_F64 :
331  (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
332  LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
333  (VT == MVT::f64) ? RTLIB::OEQ_F64 :
334  (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
335  break;
336  default:
337  // Invert CC for unordered comparisons
338  ShouldInvertCC = true;
339  switch (CCCode) {
340  case ISD::SETULT:
341  LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
342  (VT == MVT::f64) ? RTLIB::OGE_F64 :
343  (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
344  break;
345  case ISD::SETULE:
346  LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
347  (VT == MVT::f64) ? RTLIB::OGT_F64 :
348  (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
349  break;
350  case ISD::SETUGT:
351  LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
352  (VT == MVT::f64) ? RTLIB::OLE_F64 :
353  (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
354  break;
355  case ISD::SETUGE:
356  LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
357  (VT == MVT::f64) ? RTLIB::OLT_F64 :
358  (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
359  break;
360  default: llvm_unreachable("Do not know how to soften this setcc!");
361  }
362  }
363 
364  // Use the target specific return value for comparions lib calls.
365  EVT RetVT = getCmpLibcallReturnType();
366  SDValue Ops[2] = {NewLHS, NewRHS};
367  NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, false /*sign irrelevant*/,
368  dl).first;
369  NewRHS = DAG.getConstant(0, dl, RetVT);
370 
371  CCCode = getCmpLibcallCC(LC1);
372  if (ShouldInvertCC)
373  CCCode = getSetCCInverse(CCCode, /*isInteger=*/true);
374 
375  if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
376  SDValue Tmp = DAG.getNode(
377  ISD::SETCC, dl,
378  getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
379  NewLHS, NewRHS, DAG.getCondCode(CCCode));
380  NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, false/*sign irrelevant*/,
381  dl).first;
382  NewLHS = DAG.getNode(
383  ISD::SETCC, dl,
384  getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
385  NewLHS, NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
386  NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
387  NewRHS = SDValue();
388  }
389 }
390 
391 /// Return the entry encoding for a jump table in the current function. The
392 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
394  // In non-pic modes, just use the address of a block.
395  if (!isPositionIndependent())
397 
398  // In PIC mode, if the target supports a GPRel32 directive, use it.
399  if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
401 
402  // Otherwise, use a label difference.
404 }
405 
407  SelectionDAG &DAG) const {
408  // If our PIC model is GP relative, use the global offset table as the base.
409  unsigned JTEncoding = getJumpTableEncoding();
410 
411  if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
414 
415  return Table;
416 }
417 
418 /// This returns the relocation base for the given PIC jumptable, the same as
419 /// getPICJumpTableRelocBase, but as an MCExpr.
420 const MCExpr *
422  unsigned JTI,MCContext &Ctx) const{
423  // The normal PIC reloc base is the label at the start of the jump table.
424  return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
425 }
426 
427 bool
429  const TargetMachine &TM = getTargetMachine();
430  const GlobalValue *GV = GA->getGlobal();
431 
432  // If the address is not even local to this DSO we will have to load it from
433  // a got and then add the offset.
434  if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
435  return false;
436 
437  // If the code is position independent we will have to add a base register.
438  if (isPositionIndependent())
439  return false;
440 
441  // Otherwise we can do it.
442  return true;
443 }
444 
445 //===----------------------------------------------------------------------===//
446 // Optimization Methods
447 //===----------------------------------------------------------------------===//
448 
449 /// If the specified instruction has a constant integer operand and there are
450 /// bits set in that constant that are not demanded, then clear those bits and
451 /// return true.
453  TargetLoweringOpt &TLO) const {
454  SDLoc DL(Op);
455  unsigned Opcode = Op.getOpcode();
456 
457  // Do target-specific constant optimization.
458  if (targetShrinkDemandedConstant(Op, Demanded, TLO))
459  return TLO.New.getNode();
460 
461  // FIXME: ISD::SELECT, ISD::SELECT_CC
462  switch (Opcode) {
463  default:
464  break;
465  case ISD::XOR:
466  case ISD::AND:
467  case ISD::OR: {
468  auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
469  if (!Op1C)
470  return false;
471 
472  // If this is a 'not' op, don't touch it because that's a canonical form.
473  const APInt &C = Op1C->getAPIntValue();
474  if (Opcode == ISD::XOR && Demanded.isSubsetOf(C))
475  return false;
476 
477  if (!C.isSubsetOf(Demanded)) {
478  EVT VT = Op.getValueType();
479  SDValue NewC = TLO.DAG.getConstant(Demanded & C, DL, VT);
480  SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC);
481  return TLO.CombineTo(Op, NewOp);
482  }
483 
484  break;
485  }
486  }
487 
488  return false;
489 }
490 
491 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
492 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
493 /// generalized for targets with other types of implicit widening casts.
495  const APInt &Demanded,
496  TargetLoweringOpt &TLO) const {
497  assert(Op.getNumOperands() == 2 &&
498  "ShrinkDemandedOp only supports binary operators!");
499  assert(Op.getNode()->getNumValues() == 1 &&
500  "ShrinkDemandedOp only supports nodes with one result!");
501 
502  SelectionDAG &DAG = TLO.DAG;
503  SDLoc dl(Op);
504 
505  // Early return, as this function cannot handle vector types.
506  if (Op.getValueType().isVector())
507  return false;
508 
509  // Don't do this if the node has another user, which may require the
510  // full value.
511  if (!Op.getNode()->hasOneUse())
512  return false;
513 
514  // Search for the smallest integer type with free casts to and from
515  // Op's type. For expedience, just check power-of-2 integer types.
516  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
517  unsigned DemandedSize = Demanded.getActiveBits();
518  unsigned SmallVTBits = DemandedSize;
519  if (!isPowerOf2_32(SmallVTBits))
520  SmallVTBits = NextPowerOf2(SmallVTBits);
521  for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
522  EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
523  if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
524  TLI.isZExtFree(SmallVT, Op.getValueType())) {
525  // We found a type with free casts.
526  SDValue X = DAG.getNode(
527  Op.getOpcode(), dl, SmallVT,
528  DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
529  DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)));
530  assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?");
531  SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), X);
532  return TLO.CombineTo(Op, Z);
533  }
534  }
535  return false;
536 }
537 
539  DAGCombinerInfo &DCI) const {
540  SelectionDAG &DAG = DCI.DAG;
541  TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
542  !DCI.isBeforeLegalizeOps());
543  KnownBits Known;
544 
545  bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO);
546  if (Simplified) {
547  DCI.AddToWorklist(Op.getNode());
548  DCI.CommitTargetLoweringOpt(TLO);
549  }
550  return Simplified;
551 }
552 
554  KnownBits &Known,
555  TargetLoweringOpt &TLO,
556  unsigned Depth,
557  bool AssumeSingleUse) const {
558  EVT VT = Op.getValueType();
559  APInt DemandedElts = VT.isVector()
561  : APInt(1, 1);
562  return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth,
563  AssumeSingleUse);
564 }
565 
566 // TODO: Can we merge SelectionDAG::GetDemandedBits into this?
567 // TODO: Under what circumstances can we create nodes? Constant folding?
569  SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
570  SelectionDAG &DAG, unsigned Depth) const {
571  // Limit search depth.
572  if (Depth >= 6)
573  return SDValue();
574 
575  // Ignore UNDEFs.
576  if (Op.isUndef())
577  return SDValue();
578 
579  // Not demanding any bits/elts from Op.
580  if (DemandedBits == 0 || DemandedElts == 0)
581  return DAG.getUNDEF(Op.getValueType());
582 
583  unsigned NumElts = DemandedElts.getBitWidth();
584  KnownBits LHSKnown, RHSKnown;
585  switch (Op.getOpcode()) {
586  case ISD::BITCAST: {
588  EVT SrcVT = Src.getValueType();
589  EVT DstVT = Op.getValueType();
590  unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
591  unsigned NumDstEltBits = DstVT.getScalarSizeInBits();
592 
593  if (NumSrcEltBits == NumDstEltBits)
595  Src, DemandedBits, DemandedElts, DAG, Depth + 1))
596  return DAG.getBitcast(DstVT, V);
597 
598  // TODO - bigendian once we have test coverage.
599  if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0 &&
600  DAG.getDataLayout().isLittleEndian()) {
601  unsigned Scale = NumDstEltBits / NumSrcEltBits;
602  unsigned NumSrcElts = SrcVT.getVectorNumElements();
603  APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits);
604  APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts);
605  for (unsigned i = 0; i != Scale; ++i) {
606  unsigned Offset = i * NumSrcEltBits;
607  APInt Sub = DemandedBits.extractBits(NumSrcEltBits, Offset);
608  if (!Sub.isNullValue()) {
609  DemandedSrcBits |= Sub;
610  for (unsigned j = 0; j != NumElts; ++j)
611  if (DemandedElts[j])
612  DemandedSrcElts.setBit((j * Scale) + i);
613  }
614  }
615 
617  Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
618  return DAG.getBitcast(DstVT, V);
619  }
620 
621  // TODO - bigendian once we have test coverage.
622  if ((NumSrcEltBits % NumDstEltBits) == 0 &&
623  DAG.getDataLayout().isLittleEndian()) {
624  unsigned Scale = NumSrcEltBits / NumDstEltBits;
625  unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
626  APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits);
627  APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts);
628  for (unsigned i = 0; i != NumElts; ++i)
629  if (DemandedElts[i]) {
630  unsigned Offset = (i % Scale) * NumDstEltBits;
631  DemandedSrcBits.insertBits(DemandedBits, Offset);
632  DemandedSrcElts.setBit(i / Scale);
633  }
634 
636  Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
637  return DAG.getBitcast(DstVT, V);
638  }
639 
640  break;
641  }
642  case ISD::AND: {
643  LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
644  RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
645 
646  // If all of the demanded bits are known 1 on one side, return the other.
647  // These bits cannot contribute to the result of the 'and' in this
648  // context.
649  if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
650  return Op.getOperand(0);
651  if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
652  return Op.getOperand(1);
653  break;
654  }
655  case ISD::OR: {
656  LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
657  RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
658 
659  // If all of the demanded bits are known zero on one side, return the
660  // other. These bits cannot contribute to the result of the 'or' in this
661  // context.
662  if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
663  return Op.getOperand(0);
664  if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
665  return Op.getOperand(1);
666  break;
667  }
668  case ISD::XOR: {
669  LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
670  RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
671 
672  // If all of the demanded bits are known zero on one side, return the
673  // other.
674  if (DemandedBits.isSubsetOf(RHSKnown.Zero))
675  return Op.getOperand(0);
676  if (DemandedBits.isSubsetOf(LHSKnown.Zero))
677  return Op.getOperand(1);
678  break;
679  }
680  case ISD::SIGN_EXTEND_INREG: {
681  // If none of the extended bits are demanded, eliminate the sextinreg.
682  EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
683  if (DemandedBits.getActiveBits() <= ExVT.getScalarSizeInBits())
684  return Op.getOperand(0);
685  break;
686  }
687  case ISD::INSERT_VECTOR_ELT: {
688  // If we don't demand the inserted element, return the base vector.
689  SDValue Vec = Op.getOperand(0);
690  auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
691  EVT VecVT = Vec.getValueType();
692  if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
693  !DemandedElts[CIdx->getZExtValue()])
694  return Vec;
695  break;
696  }
697  case ISD::VECTOR_SHUFFLE: {
698  ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
699 
700  // If all the demanded elts are from one operand and are inline,
701  // then we can use the operand directly.
702  bool AllUndef = true, IdentityLHS = true, IdentityRHS = true;
703  for (unsigned i = 0; i != NumElts; ++i) {
704  int M = ShuffleMask[i];
705  if (M < 0 || !DemandedElts[i])
706  continue;
707  AllUndef = false;
708  IdentityLHS &= (M == (int)i);
709  IdentityRHS &= ((M - NumElts) == i);
710  }
711 
712  if (AllUndef)
713  return DAG.getUNDEF(Op.getValueType());
714  if (IdentityLHS)
715  return Op.getOperand(0);
716  if (IdentityRHS)
717  return Op.getOperand(1);
718  break;
719  }
720  default:
721  if (Op.getOpcode() >= ISD::BUILTIN_OP_END)
723  Op, DemandedBits, DemandedElts, DAG, Depth))
724  return V;
725  break;
726  }
727  return SDValue();
728 }
729 
730 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the
731 /// result of Op are ever used downstream. If we can use this information to
732 /// simplify Op, create a new simplified DAG node and return true, returning the
733 /// original and new nodes in Old and New. Otherwise, analyze the expression and
734 /// return a mask of Known bits for the expression (used to simplify the
735 /// caller). The Known bits may only be accurate for those bits in the
736 /// OriginalDemandedBits and OriginalDemandedElts.
738  SDValue Op, const APInt &OriginalDemandedBits,
739  const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
740  unsigned Depth, bool AssumeSingleUse) const {
741  unsigned BitWidth = OriginalDemandedBits.getBitWidth();
742  assert(Op.getScalarValueSizeInBits() == BitWidth &&
743  "Mask size mismatches value type size!");
744 
745  unsigned NumElts = OriginalDemandedElts.getBitWidth();
746  assert((!Op.getValueType().isVector() ||
747  NumElts == Op.getValueType().getVectorNumElements()) &&
748  "Unexpected vector size");
749 
750  APInt DemandedBits = OriginalDemandedBits;
751  APInt DemandedElts = OriginalDemandedElts;
752  SDLoc dl(Op);
753  auto &DL = TLO.DAG.getDataLayout();
754 
755  // Don't know anything.
756  Known = KnownBits(BitWidth);
757 
758  // Undef operand.
759  if (Op.isUndef())
760  return false;
761 
762  if (Op.getOpcode() == ISD::Constant) {
763  // We know all of the bits for a constant!
764  Known.One = cast<ConstantSDNode>(Op)->getAPIntValue();
765  Known.Zero = ~Known.One;
766  return false;
767  }
768 
769  // Other users may use these bits.
770  EVT VT = Op.getValueType();
771  if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) {
772  if (Depth != 0) {
773  // If not at the root, Just compute the Known bits to
774  // simplify things downstream.
775  Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
776  return false;
777  }
778  // If this is the root being simplified, allow it to have multiple uses,
779  // just set the DemandedBits/Elts to all bits.
780  DemandedBits = APInt::getAllOnesValue(BitWidth);
781  DemandedElts = APInt::getAllOnesValue(NumElts);
782  } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) {
783  // Not demanding any bits/elts from Op.
784  return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
785  } else if (Depth >= 6) { // Limit search depth.
786  return false;
787  }
788 
789  KnownBits Known2, KnownOut;
790  switch (Op.getOpcode()) {
791  case ISD::SCALAR_TO_VECTOR: {
792  if (!DemandedElts[0])
793  return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
794 
795  KnownBits SrcKnown;
796  SDValue Src = Op.getOperand(0);
797  unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
798  APInt SrcDemandedBits = DemandedBits.zextOrSelf(SrcBitWidth);
799  if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1))
800  return true;
801  Known = SrcKnown.zextOrTrunc(BitWidth, false);
802  break;
803  }
804  case ISD::BUILD_VECTOR:
805  // Collect the known bits that are shared by every demanded element.
806  // TODO: Call SimplifyDemandedBits for non-constant demanded elements.
807  Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
808  return false; // Don't fall through, will infinitely loop.
809  case ISD::LOAD: {
810  LoadSDNode *LD = cast<LoadSDNode>(Op);
811  if (getTargetConstantFromLoad(LD)) {
812  Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
813  return false; // Don't fall through, will infinitely loop.
814  }
815  break;
816  }
817  case ISD::INSERT_VECTOR_ELT: {
818  SDValue Vec = Op.getOperand(0);
819  SDValue Scl = Op.getOperand(1);
820  auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
821  EVT VecVT = Vec.getValueType();
822 
823  // If index isn't constant, assume we need all vector elements AND the
824  // inserted element.
825  APInt DemandedVecElts(DemandedElts);
826  if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
827  unsigned Idx = CIdx->getZExtValue();
828  DemandedVecElts.clearBit(Idx);
829 
830  // Inserted element is not required.
831  if (!DemandedElts[Idx])
832  return TLO.CombineTo(Op, Vec);
833  }
834 
835  KnownBits KnownScl;
836  unsigned NumSclBits = Scl.getScalarValueSizeInBits();
837  APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits);
838  if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
839  return true;
840 
841  Known = KnownScl.zextOrTrunc(BitWidth, false);
842 
843  KnownBits KnownVec;
844  if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO,
845  Depth + 1))
846  return true;
847 
848  if (!!DemandedVecElts) {
849  Known.One &= KnownVec.One;
850  Known.Zero &= KnownVec.Zero;
851  }
852 
853  return false;
854  }
855  case ISD::INSERT_SUBVECTOR: {
856  SDValue Base = Op.getOperand(0);
857  SDValue Sub = Op.getOperand(1);
858  EVT SubVT = Sub.getValueType();
859  unsigned NumSubElts = SubVT.getVectorNumElements();
860 
861  // If index isn't constant, assume we need the original demanded base
862  // elements and ALL the inserted subvector elements.
863  APInt BaseElts = DemandedElts;
864  APInt SubElts = APInt::getAllOnesValue(NumSubElts);
865  if (isa<ConstantSDNode>(Op.getOperand(2))) {
866  const APInt &Idx = Op.getConstantOperandAPInt(2);
867  if (Idx.ule(NumElts - NumSubElts)) {
868  unsigned SubIdx = Idx.getZExtValue();
869  SubElts = DemandedElts.extractBits(NumSubElts, SubIdx);
870  BaseElts.insertBits(APInt::getNullValue(NumSubElts), SubIdx);
871  }
872  }
873 
874  KnownBits KnownSub, KnownBase;
875  if (SimplifyDemandedBits(Sub, DemandedBits, SubElts, KnownSub, TLO,
876  Depth + 1))
877  return true;
878  if (SimplifyDemandedBits(Base, DemandedBits, BaseElts, KnownBase, TLO,
879  Depth + 1))
880  return true;
881 
882  Known.Zero.setAllBits();
883  Known.One.setAllBits();
884  if (!!SubElts) {
885  Known.One &= KnownSub.One;
886  Known.Zero &= KnownSub.Zero;
887  }
888  if (!!BaseElts) {
889  Known.One &= KnownBase.One;
890  Known.Zero &= KnownBase.Zero;
891  }
892  break;
893  }
894  case ISD::CONCAT_VECTORS: {
895  Known.Zero.setAllBits();
896  Known.One.setAllBits();
897  EVT SubVT = Op.getOperand(0).getValueType();
898  unsigned NumSubVecs = Op.getNumOperands();
899  unsigned NumSubElts = SubVT.getVectorNumElements();
900  for (unsigned i = 0; i != NumSubVecs; ++i) {
901  APInt DemandedSubElts =
902  DemandedElts.extractBits(NumSubElts, i * NumSubElts);
903  if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts,
904  Known2, TLO, Depth + 1))
905  return true;
906  // Known bits are shared by every demanded subvector element.
907  if (!!DemandedSubElts) {
908  Known.One &= Known2.One;
909  Known.Zero &= Known2.Zero;
910  }
911  }
912  break;
913  }
914  case ISD::VECTOR_SHUFFLE: {
915  ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
916 
917  // Collect demanded elements from shuffle operands..
918  APInt DemandedLHS(NumElts, 0);
919  APInt DemandedRHS(NumElts, 0);
920  for (unsigned i = 0; i != NumElts; ++i) {
921  if (!DemandedElts[i])
922  continue;
923  int M = ShuffleMask[i];
924  if (M < 0) {
925  // For UNDEF elements, we don't know anything about the common state of
926  // the shuffle result.
927  DemandedLHS.clearAllBits();
928  DemandedRHS.clearAllBits();
929  break;
930  }
931  assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
932  if (M < (int)NumElts)
933  DemandedLHS.setBit(M);
934  else
935  DemandedRHS.setBit(M - NumElts);
936  }
937 
938  if (!!DemandedLHS || !!DemandedRHS) {
939  SDValue Op0 = Op.getOperand(0);
940  SDValue Op1 = Op.getOperand(1);
941 
942  Known.Zero.setAllBits();
943  Known.One.setAllBits();
944  if (!!DemandedLHS) {
945  if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO,
946  Depth + 1))
947  return true;
948  Known.One &= Known2.One;
949  Known.Zero &= Known2.Zero;
950  }
951  if (!!DemandedRHS) {
952  if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO,
953  Depth + 1))
954  return true;
955  Known.One &= Known2.One;
956  Known.Zero &= Known2.Zero;
957  }
958 
959  // Attempt to avoid multi-use ops if we don't need anything from them.
961  Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1);
963  Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1);
964  if (DemandedOp0 || DemandedOp1) {
965  Op0 = DemandedOp0 ? DemandedOp0 : Op0;
966  Op1 = DemandedOp1 ? DemandedOp1 : Op1;
967  SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask);
968  return TLO.CombineTo(Op, NewOp);
969  }
970  }
971  break;
972  }
973  case ISD::AND: {
974  SDValue Op0 = Op.getOperand(0);
975  SDValue Op1 = Op.getOperand(1);
976 
977  // If the RHS is a constant, check to see if the LHS would be zero without
978  // using the bits from the RHS. Below, we use knowledge about the RHS to
979  // simplify the LHS, here we're using information from the LHS to simplify
980  // the RHS.
981  if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) {
982  // Do not increment Depth here; that can cause an infinite loop.
983  KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth);
984  // If the LHS already has zeros where RHSC does, this 'and' is dead.
985  if ((LHSKnown.Zero & DemandedBits) ==
986  (~RHSC->getAPIntValue() & DemandedBits))
987  return TLO.CombineTo(Op, Op0);
988 
989  // If any of the set bits in the RHS are known zero on the LHS, shrink
990  // the constant.
991  if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits, TLO))
992  return true;
993 
994  // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
995  // constant, but if this 'and' is only clearing bits that were just set by
996  // the xor, then this 'and' can be eliminated by shrinking the mask of
997  // the xor. For example, for a 32-bit X:
998  // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
999  if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
1000  LHSKnown.One == ~RHSC->getAPIntValue()) {
1001  SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1);
1002  return TLO.CombineTo(Op, Xor);
1003  }
1004  }
1005 
1006  if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1007  Depth + 1))
1008  return true;
1009  assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1010  if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts,
1011  Known2, TLO, Depth + 1))
1012  return true;
1013  assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1014 
1015  // Attempt to avoid multi-use ops if we don't need anything from them.
1016  if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
1018  Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1020  Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1021  if (DemandedOp0 || DemandedOp1) {
1022  Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1023  Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1024  SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1025  return TLO.CombineTo(Op, NewOp);
1026  }
1027  }
1028 
1029  // If all of the demanded bits are known one on one side, return the other.
1030  // These bits cannot contribute to the result of the 'and'.
1031  if (DemandedBits.isSubsetOf(Known2.Zero | Known.One))
1032  return TLO.CombineTo(Op, Op0);
1033  if (DemandedBits.isSubsetOf(Known.Zero | Known2.One))
1034  return TLO.CombineTo(Op, Op1);
1035  // If all of the demanded bits in the inputs are known zeros, return zero.
1036  if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1037  return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
1038  // If the RHS is a constant, see if we can simplify it.
1039  if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, TLO))
1040  return true;
1041  // If the operation can be done in a smaller type, do so.
1042  if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1043  return true;
1044 
1045  // Output known-1 bits are only known if set in both the LHS & RHS.
1046  Known.One &= Known2.One;
1047  // Output known-0 are known to be clear if zero in either the LHS | RHS.
1048  Known.Zero |= Known2.Zero;
1049  break;
1050  }
1051  case ISD::OR: {
1052  SDValue Op0 = Op.getOperand(0);
1053  SDValue Op1 = Op.getOperand(1);
1054 
1055  if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1056  Depth + 1))
1057  return true;
1058  assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1059  if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts,
1060  Known2, TLO, Depth + 1))
1061  return true;
1062  assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1063 
1064  // Attempt to avoid multi-use ops if we don't need anything from them.
1065  if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
1067  Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1069  Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1070  if (DemandedOp0 || DemandedOp1) {
1071  Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1072  Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1073  SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1074  return TLO.CombineTo(Op, NewOp);
1075  }
1076  }
1077 
1078  // If all of the demanded bits are known zero on one side, return the other.
1079  // These bits cannot contribute to the result of the 'or'.
1080  if (DemandedBits.isSubsetOf(Known2.One | Known.Zero))
1081  return TLO.CombineTo(Op, Op0);
1082  if (DemandedBits.isSubsetOf(Known.One | Known2.Zero))
1083  return TLO.CombineTo(Op, Op1);
1084  // If the RHS is a constant, see if we can simplify it.
1085  if (ShrinkDemandedConstant(Op, DemandedBits, TLO))
1086  return true;
1087  // If the operation can be done in a smaller type, do so.
1088  if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1089  return true;
1090 
1091  // Output known-0 bits are only known if clear in both the LHS & RHS.
1092  Known.Zero &= Known2.Zero;
1093  // Output known-1 are known to be set if set in either the LHS | RHS.
1094  Known.One |= Known2.One;
1095  break;
1096  }
1097  case ISD::XOR: {
1098  SDValue Op0 = Op.getOperand(0);
1099  SDValue Op1 = Op.getOperand(1);
1100 
1101  if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1102  Depth + 1))
1103  return true;
1104  assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1105  if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO,
1106  Depth + 1))
1107  return true;
1108  assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1109 
1110  // Attempt to avoid multi-use ops if we don't need anything from them.
1111  if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
1113  Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1115  Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1116  if (DemandedOp0 || DemandedOp1) {
1117  Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1118  Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1119  SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1120  return TLO.CombineTo(Op, NewOp);
1121  }
1122  }
1123 
1124  // If all of the demanded bits are known zero on one side, return the other.
1125  // These bits cannot contribute to the result of the 'xor'.
1126  if (DemandedBits.isSubsetOf(Known.Zero))
1127  return TLO.CombineTo(Op, Op0);
1128  if (DemandedBits.isSubsetOf(Known2.Zero))
1129  return TLO.CombineTo(Op, Op1);
1130  // If the operation can be done in a smaller type, do so.
1131  if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1132  return true;
1133 
1134  // If all of the unknown bits are known to be zero on one side or the other
1135  // (but not both) turn this into an *inclusive* or.
1136  // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1137  if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1138  return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1));
1139 
1140  // Output known-0 bits are known if clear or set in both the LHS & RHS.
1141  KnownOut.Zero = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
1142  // Output known-1 are known to be set if set in only one of the LHS, RHS.
1143  KnownOut.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
1144 
1145  if (ConstantSDNode *C = isConstOrConstSplat(Op1)) {
1146  // If one side is a constant, and all of the known set bits on the other
1147  // side are also set in the constant, turn this into an AND, as we know
1148  // the bits will be cleared.
1149  // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1150  // NB: it is okay if more bits are known than are requested
1151  if (C->getAPIntValue() == Known2.One) {
1152  SDValue ANDC =
1153  TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT);
1154  return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC));
1155  }
1156 
1157  // If the RHS is a constant, see if we can change it. Don't alter a -1
1158  // constant because that's a 'not' op, and that is better for combining
1159  // and codegen.
1160  if (!C->isAllOnesValue()) {
1161  if (DemandedBits.isSubsetOf(C->getAPIntValue())) {
1162  // We're flipping all demanded bits. Flip the undemanded bits too.
1163  SDValue New = TLO.DAG.getNOT(dl, Op0, VT);
1164  return TLO.CombineTo(Op, New);
1165  }
1166  // If we can't turn this into a 'not', try to shrink the constant.
1167  if (ShrinkDemandedConstant(Op, DemandedBits, TLO))
1168  return true;
1169  }
1170  }
1171 
1172  Known = std::move(KnownOut);
1173  break;
1174  }
1175  case ISD::SELECT:
1176  if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO,
1177  Depth + 1))
1178  return true;
1179  if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO,
1180  Depth + 1))
1181  return true;
1182  assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1183  assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1184 
1185  // If the operands are constants, see if we can simplify them.
1186  if (ShrinkDemandedConstant(Op, DemandedBits, TLO))
1187  return true;
1188 
1189  // Only known if known in both the LHS and RHS.
1190  Known.One &= Known2.One;
1191  Known.Zero &= Known2.Zero;
1192  break;
1193  case ISD::SELECT_CC:
1194  if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO,
1195  Depth + 1))
1196  return true;
1197  if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO,
1198  Depth + 1))
1199  return true;
1200  assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1201  assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1202 
1203  // If the operands are constants, see if we can simplify them.
1204  if (ShrinkDemandedConstant(Op, DemandedBits, TLO))
1205  return true;
1206 
1207  // Only known if known in both the LHS and RHS.
1208  Known.One &= Known2.One;
1209  Known.Zero &= Known2.Zero;
1210  break;
1211  case ISD::SETCC: {
1212  SDValue Op0 = Op.getOperand(0);
1213  SDValue Op1 = Op.getOperand(1);
1214  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1215  // If (1) we only need the sign-bit, (2) the setcc operands are the same
1216  // width as the setcc result, and (3) the result of a setcc conforms to 0 or
1217  // -1, we may be able to bypass the setcc.
1218  if (DemandedBits.isSignMask() &&
1219  Op0.getScalarValueSizeInBits() == BitWidth &&
1220  getBooleanContents(VT) ==
1221  BooleanContent::ZeroOrNegativeOneBooleanContent) {
1222  // If we're testing X < 0, then this compare isn't needed - just use X!
1223  // FIXME: We're limiting to integer types here, but this should also work
1224  // if we don't care about FP signed-zero. The use of SETLT with FP means
1225  // that we don't care about NaNs.
1226  if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
1228  return TLO.CombineTo(Op, Op0);
1229 
1230  // TODO: Should we check for other forms of sign-bit comparisons?
1231  // Examples: X <= -1, X >= 0
1232  }
1233  if (getBooleanContents(Op0.getValueType()) ==
1235  BitWidth > 1)
1236  Known.Zero.setBitsFrom(1);
1237  break;
1238  }
1239  case ISD::SHL: {
1240  SDValue Op0 = Op.getOperand(0);
1241  SDValue Op1 = Op.getOperand(1);
1242 
1243  if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) {
1244  // If the shift count is an invalid immediate, don't do anything.
1245  if (SA->getAPIntValue().uge(BitWidth))
1246  break;
1247 
1248  unsigned ShAmt = SA->getZExtValue();
1249  if (ShAmt == 0)
1250  return TLO.CombineTo(Op, Op0);
1251 
1252  // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1253  // single shift. We can do this if the bottom bits (which are shifted
1254  // out) are never demanded.
1255  // TODO - support non-uniform vector amounts.
1256  if (Op0.getOpcode() == ISD::SRL) {
1257  if ((DemandedBits & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
1258  if (ConstantSDNode *SA2 =
1259  isConstOrConstSplat(Op0.getOperand(1), DemandedElts)) {
1260  if (SA2->getAPIntValue().ult(BitWidth)) {
1261  unsigned C1 = SA2->getZExtValue();
1262  unsigned Opc = ISD::SHL;
1263  int Diff = ShAmt - C1;
1264  if (Diff < 0) {
1265  Diff = -Diff;
1266  Opc = ISD::SRL;
1267  }
1268 
1269  SDValue NewSA = TLO.DAG.getConstant(Diff, dl, Op1.getValueType());
1270  return TLO.CombineTo(
1271  Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1272  }
1273  }
1274  }
1275  }
1276 
1277  if (SimplifyDemandedBits(Op0, DemandedBits.lshr(ShAmt), DemandedElts,
1278  Known, TLO, Depth + 1))
1279  return true;
1280 
1281  // Try shrinking the operation as long as the shift amount will still be
1282  // in range.
1283  if ((ShAmt < DemandedBits.getActiveBits()) &&
1284  ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1285  return true;
1286 
1287  // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
1288  // are not demanded. This will likely allow the anyext to be folded away.
1289  if (Op0.getOpcode() == ISD::ANY_EXTEND) {
1290  SDValue InnerOp = Op0.getOperand(0);
1291  EVT InnerVT = InnerOp.getValueType();
1292  unsigned InnerBits = InnerVT.getScalarSizeInBits();
1293  if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits &&
1294  isTypeDesirableForOp(ISD::SHL, InnerVT)) {
1295  EVT ShTy = getShiftAmountTy(InnerVT, DL);
1296  if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
1297  ShTy = InnerVT;
1298  SDValue NarrowShl =
1299  TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
1300  TLO.DAG.getConstant(ShAmt, dl, ShTy));
1301  return TLO.CombineTo(
1302  Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
1303  }
1304  // Repeat the SHL optimization above in cases where an extension
1305  // intervenes: (shl (anyext (shr x, c1)), c2) to
1306  // (shl (anyext x), c2-c1). This requires that the bottom c1 bits
1307  // aren't demanded (as above) and that the shifted upper c1 bits of
1308  // x aren't demanded.
1309  if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL &&
1310  InnerOp.hasOneUse()) {
1311  if (ConstantSDNode *SA2 =
1312  isConstOrConstSplat(InnerOp.getOperand(1))) {
1313  unsigned InnerShAmt = SA2->getLimitedValue(InnerBits);
1314  if (InnerShAmt < ShAmt && InnerShAmt < InnerBits &&
1315  DemandedBits.getActiveBits() <=
1316  (InnerBits - InnerShAmt + ShAmt) &&
1317  DemandedBits.countTrailingZeros() >= ShAmt) {
1318  SDValue NewSA = TLO.DAG.getConstant(ShAmt - InnerShAmt, dl,
1319  Op1.getValueType());
1320  SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
1321  InnerOp.getOperand(0));
1322  return TLO.CombineTo(
1323  Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA));
1324  }
1325  }
1326  }
1327  }
1328 
1329  Known.Zero <<= ShAmt;
1330  Known.One <<= ShAmt;
1331  // low bits known zero.
1332  Known.Zero.setLowBits(ShAmt);
1333  }
1334  break;
1335  }
1336  case ISD::SRL: {
1337  SDValue Op0 = Op.getOperand(0);
1338  SDValue Op1 = Op.getOperand(1);
1339 
1340  if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) {
1341  // If the shift count is an invalid immediate, don't do anything.
1342  if (SA->getAPIntValue().uge(BitWidth))
1343  break;
1344 
1345  unsigned ShAmt = SA->getZExtValue();
1346  if (ShAmt == 0)
1347  return TLO.CombineTo(Op, Op0);
1348 
1349  EVT ShiftVT = Op1.getValueType();
1350  APInt InDemandedMask = (DemandedBits << ShAmt);
1351 
1352  // If the shift is exact, then it does demand the low bits (and knows that
1353  // they are zero).
1354  if (Op->getFlags().hasExact())
1355  InDemandedMask.setLowBits(ShAmt);
1356 
1357  // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
1358  // single shift. We can do this if the top bits (which are shifted out)
1359  // are never demanded.
1360  // TODO - support non-uniform vector amounts.
1361  if (Op0.getOpcode() == ISD::SHL) {
1362  if (ConstantSDNode *SA2 =
1363  isConstOrConstSplat(Op0.getOperand(1), DemandedElts)) {
1364  if ((DemandedBits & APInt::getHighBitsSet(BitWidth, ShAmt)) == 0) {
1365  if (SA2->getAPIntValue().ult(BitWidth)) {
1366  unsigned C1 = SA2->getZExtValue();
1367  unsigned Opc = ISD::SRL;
1368  int Diff = ShAmt - C1;
1369  if (Diff < 0) {
1370  Diff = -Diff;
1371  Opc = ISD::SHL;
1372  }
1373 
1374  SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1375  return TLO.CombineTo(
1376  Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1377  }
1378  }
1379  }
1380  }
1381 
1382  // Compute the new bits that are at the top now.
1383  if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1384  Depth + 1))
1385  return true;
1386  assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1387  Known.Zero.lshrInPlace(ShAmt);
1388  Known.One.lshrInPlace(ShAmt);
1389 
1390  Known.Zero.setHighBits(ShAmt); // High bits known zero.
1391  }
1392  break;
1393  }
1394  case ISD::SRA: {
1395  SDValue Op0 = Op.getOperand(0);
1396  SDValue Op1 = Op.getOperand(1);
1397 
1398  // If this is an arithmetic shift right and only the low-bit is set, we can
1399  // always convert this into a logical shr, even if the shift amount is
1400  // variable. The low bit of the shift cannot be an input sign bit unless
1401  // the shift amount is >= the size of the datatype, which is undefined.
1402  if (DemandedBits.isOneValue())
1403  return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
1404 
1405  if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) {
1406  // If the shift count is an invalid immediate, don't do anything.
1407  if (SA->getAPIntValue().uge(BitWidth))
1408  break;
1409 
1410  unsigned ShAmt = SA->getZExtValue();
1411  if (ShAmt == 0)
1412  return TLO.CombineTo(Op, Op0);
1413 
1414  APInt InDemandedMask = (DemandedBits << ShAmt);
1415 
1416  // If the shift is exact, then it does demand the low bits (and knows that
1417  // they are zero).
1418  if (Op->getFlags().hasExact())
1419  InDemandedMask.setLowBits(ShAmt);
1420 
1421  // If any of the demanded bits are produced by the sign extension, we also
1422  // demand the input sign bit.
1423  if (DemandedBits.countLeadingZeros() < ShAmt)
1424  InDemandedMask.setSignBit();
1425 
1426  if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1427  Depth + 1))
1428  return true;
1429  assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1430  Known.Zero.lshrInPlace(ShAmt);
1431  Known.One.lshrInPlace(ShAmt);
1432 
1433  // If the input sign bit is known to be zero, or if none of the top bits
1434  // are demanded, turn this into an unsigned shift right.
1435  if (Known.Zero[BitWidth - ShAmt - 1] ||
1436  DemandedBits.countLeadingZeros() >= ShAmt) {
1437  SDNodeFlags Flags;
1438  Flags.setExact(Op->getFlags().hasExact());
1439  return TLO.CombineTo(
1440  Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags));
1441  }
1442 
1443  int Log2 = DemandedBits.exactLogBase2();
1444  if (Log2 >= 0) {
1445  // The bit must come from the sign.
1446  SDValue NewSA =
1447  TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, Op1.getValueType());
1448  return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA));
1449  }
1450 
1451  if (Known.One[BitWidth - ShAmt - 1])
1452  // New bits are known one.
1453  Known.One.setHighBits(ShAmt);
1454  }
1455  break;
1456  }
1457  case ISD::FSHL:
1458  case ISD::FSHR: {
1459  SDValue Op0 = Op.getOperand(0);
1460  SDValue Op1 = Op.getOperand(1);
1461  SDValue Op2 = Op.getOperand(2);
1462  bool IsFSHL = (Op.getOpcode() == ISD::FSHL);
1463 
1464  if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) {
1465  unsigned Amt = SA->getAPIntValue().urem(BitWidth);
1466 
1467  // For fshl, 0-shift returns the 1st arg.
1468  // For fshr, 0-shift returns the 2nd arg.
1469  if (Amt == 0) {
1470  if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts,
1471  Known, TLO, Depth + 1))
1472  return true;
1473  break;
1474  }
1475 
1476  // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
1477  // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
1478  APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt));
1479  APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt);
1480  if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
1481  Depth + 1))
1482  return true;
1483  if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO,
1484  Depth + 1))
1485  return true;
1486 
1487  Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt));
1488  Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt));
1489  Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
1490  Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
1491  Known.One |= Known2.One;
1492  Known.Zero |= Known2.Zero;
1493  }
1494  break;
1495  }
1496  case ISD::BITREVERSE: {
1497  SDValue Src = Op.getOperand(0);
1498  APInt DemandedSrcBits = DemandedBits.reverseBits();
1499  if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
1500  Depth + 1))
1501  return true;
1502  Known.One = Known2.One.reverseBits();
1503  Known.Zero = Known2.Zero.reverseBits();
1504  break;
1505  }
1506  case ISD::SIGN_EXTEND_INREG: {
1507  SDValue Op0 = Op.getOperand(0);
1508  EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1509  unsigned ExVTBits = ExVT.getScalarSizeInBits();
1510 
1511  // If we only care about the highest bit, don't bother shifting right.
1512  if (DemandedBits.isSignMask()) {
1513  unsigned NumSignBits = TLO.DAG.ComputeNumSignBits(Op0);
1514  bool AlreadySignExtended = NumSignBits >= BitWidth - ExVTBits + 1;
1515  // However if the input is already sign extended we expect the sign
1516  // extension to be dropped altogether later and do not simplify.
1517  if (!AlreadySignExtended) {
1518  // Compute the correct shift amount type, which must be getShiftAmountTy
1519  // for scalar types after legalization.
1520  EVT ShiftAmtTy = VT;
1521  if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
1522  ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL);
1523 
1524  SDValue ShiftAmt =
1525  TLO.DAG.getConstant(BitWidth - ExVTBits, dl, ShiftAmtTy);
1526  return TLO.CombineTo(Op,
1527  TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt));
1528  }
1529  }
1530 
1531  // If none of the extended bits are demanded, eliminate the sextinreg.
1532  if (DemandedBits.getActiveBits() <= ExVTBits)
1533  return TLO.CombineTo(Op, Op0);
1534 
1535  APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits);
1536 
1537  // Since the sign extended bits are demanded, we know that the sign
1538  // bit is demanded.
1539  InputDemandedBits.setBit(ExVTBits - 1);
1540 
1541  if (SimplifyDemandedBits(Op0, InputDemandedBits, Known, TLO, Depth + 1))
1542  return true;
1543  assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1544 
1545  // If the sign bit of the input is known set or clear, then we know the
1546  // top bits of the result.
1547 
1548  // If the input sign bit is known zero, convert this into a zero extension.
1549  if (Known.Zero[ExVTBits - 1])
1550  return TLO.CombineTo(
1551  Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT.getScalarType()));
1552 
1553  APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
1554  if (Known.One[ExVTBits - 1]) { // Input sign bit known set
1555  Known.One.setBitsFrom(ExVTBits);
1556  Known.Zero &= Mask;
1557  } else { // Input sign bit unknown
1558  Known.Zero &= Mask;
1559  Known.One &= Mask;
1560  }
1561  break;
1562  }
1563  case ISD::BUILD_PAIR: {
1564  EVT HalfVT = Op.getOperand(0).getValueType();
1565  unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
1566 
1567  APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
1568  APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
1569 
1570  KnownBits KnownLo, KnownHi;
1571 
1572  if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
1573  return true;
1574 
1575  if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
1576  return true;
1577 
1578  Known.Zero = KnownLo.Zero.zext(BitWidth) |
1579  KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth);
1580 
1581  Known.One = KnownLo.One.zext(BitWidth) |
1582  KnownHi.One.zext(BitWidth).shl(HalfBitWidth);
1583  break;
1584  }
1585  case ISD::ZERO_EXTEND:
1587  SDValue Src = Op.getOperand(0);
1588  EVT SrcVT = Src.getValueType();
1589  unsigned InBits = SrcVT.getScalarSizeInBits();
1590  unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
1591  bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
1592 
1593  // If none of the top bits are demanded, convert this into an any_extend.
1594  if (DemandedBits.getActiveBits() <= InBits) {
1595  // If we only need the non-extended bits of the bottom element
1596  // then we can just bitcast to the result.
1597  if (IsVecInReg && DemandedElts == 1 &&
1598  VT.getSizeInBits() == SrcVT.getSizeInBits() &&
1599  TLO.DAG.getDataLayout().isLittleEndian())
1600  return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
1601 
1602  unsigned Opc =
1604  if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
1605  return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
1606  }
1607 
1608  APInt InDemandedBits = DemandedBits.trunc(InBits);
1609  APInt InDemandedElts = DemandedElts.zextOrSelf(InElts);
1610  if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
1611  Depth + 1))
1612  return true;
1613  assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1614  assert(Known.getBitWidth() == InBits && "Src width has changed?");
1615  Known = Known.zext(BitWidth, true /* ExtendedBitsAreKnownZero */);
1616  break;
1617  }
1618  case ISD::SIGN_EXTEND:
1620  SDValue Src = Op.getOperand(0);
1621  EVT SrcVT = Src.getValueType();
1622  unsigned InBits = SrcVT.getScalarSizeInBits();
1623  unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
1624  bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
1625 
1626  // If none of the top bits are demanded, convert this into an any_extend.
1627  if (DemandedBits.getActiveBits() <= InBits) {
1628  // If we only need the non-extended bits of the bottom element
1629  // then we can just bitcast to the result.
1630  if (IsVecInReg && DemandedElts == 1 &&
1631  VT.getSizeInBits() == SrcVT.getSizeInBits() &&
1632  TLO.DAG.getDataLayout().isLittleEndian())
1633  return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
1634 
1635  unsigned Opc =
1637  if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
1638  return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
1639  }
1640 
1641  APInt InDemandedBits = DemandedBits.trunc(InBits);
1642  APInt InDemandedElts = DemandedElts.zextOrSelf(InElts);
1643 
1644  // Since some of the sign extended bits are demanded, we know that the sign
1645  // bit is demanded.
1646  InDemandedBits.setBit(InBits - 1);
1647 
1648  if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
1649  Depth + 1))
1650  return true;
1651  assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1652  assert(Known.getBitWidth() == InBits && "Src width has changed?");
1653 
1654  // If the sign bit is known one, the top bits match.
1655  Known = Known.sext(BitWidth);
1656 
1657  // If the sign bit is known zero, convert this to a zero extend.
1658  if (Known.isNonNegative()) {
1659  unsigned Opc =
1661  if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
1662  return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
1663  }
1664  break;
1665  }
1666  case ISD::ANY_EXTEND:
1668  SDValue Src = Op.getOperand(0);
1669  EVT SrcVT = Src.getValueType();
1670  unsigned InBits = SrcVT.getScalarSizeInBits();
1671  unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
1672  bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG;
1673 
1674  // If we only need the bottom element then we can just bitcast.
1675  // TODO: Handle ANY_EXTEND?
1676  if (IsVecInReg && DemandedElts == 1 &&
1677  VT.getSizeInBits() == SrcVT.getSizeInBits() &&
1678  TLO.DAG.getDataLayout().isLittleEndian())
1679  return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
1680 
1681  APInt InDemandedBits = DemandedBits.trunc(InBits);
1682  APInt InDemandedElts = DemandedElts.zextOrSelf(InElts);
1683  if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
1684  Depth + 1))
1685  return true;
1686  assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1687  assert(Known.getBitWidth() == InBits && "Src width has changed?");
1688  Known = Known.zext(BitWidth, false /* => any extend */);
1689  break;
1690  }
1691  case ISD::TRUNCATE: {
1692  SDValue Src = Op.getOperand(0);
1693 
1694  // Simplify the input, using demanded bit information, and compute the known
1695  // zero/one bits live out.
1696  unsigned OperandBitWidth = Src.getScalarValueSizeInBits();
1697  APInt TruncMask = DemandedBits.zext(OperandBitWidth);
1698  if (SimplifyDemandedBits(Src, TruncMask, Known, TLO, Depth + 1))
1699  return true;
1700  Known = Known.trunc(BitWidth);
1701 
1702  // Attempt to avoid multi-use ops if we don't need anything from them.
1704  Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1))
1705  return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc));
1706 
1707  // If the input is only used by this truncate, see if we can shrink it based
1708  // on the known demanded bits.
1709  if (Src.getNode()->hasOneUse()) {
1710  switch (Src.getOpcode()) {
1711  default:
1712  break;
1713  case ISD::SRL:
1714  // Shrink SRL by a constant if none of the high bits shifted in are
1715  // demanded.
1716  if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
1717  // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1718  // undesirable.
1719  break;
1720 
1721  auto *ShAmt = dyn_cast<ConstantSDNode>(Src.getOperand(1));
1722  if (!ShAmt || ShAmt->getAPIntValue().uge(BitWidth))
1723  break;
1724 
1725  SDValue Shift = Src.getOperand(1);
1726  uint64_t ShVal = ShAmt->getZExtValue();
1727 
1728  if (TLO.LegalTypes())
1729  Shift = TLO.DAG.getConstant(ShVal, dl, getShiftAmountTy(VT, DL));
1730 
1731  APInt HighBits =
1732  APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth);
1733  HighBits.lshrInPlace(ShVal);
1734  HighBits = HighBits.trunc(BitWidth);
1735 
1736  if (!(HighBits & DemandedBits)) {
1737  // None of the shifted in bits are needed. Add a truncate of the
1738  // shift input, then shift it.
1739  SDValue NewTrunc =
1740  TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0));
1741  return TLO.CombineTo(
1742  Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, Shift));
1743  }
1744  break;
1745  }
1746  }
1747 
1748  assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1749  break;
1750  }
1751  case ISD::AssertZext: {
1752  // AssertZext demands all of the high bits, plus any of the low bits
1753  // demanded by its users.
1754  EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1755  APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits());
1756  if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known,
1757  TLO, Depth + 1))
1758  return true;
1759  assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1760 
1761  Known.Zero |= ~InMask;
1762  break;
1763  }
1764  case ISD::EXTRACT_VECTOR_ELT: {
1765  SDValue Src = Op.getOperand(0);
1766  SDValue Idx = Op.getOperand(1);
1767  unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1768  unsigned EltBitWidth = Src.getScalarValueSizeInBits();
1769 
1770  // Demand the bits from every vector element without a constant index.
1771  APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
1772  if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx))
1773  if (CIdx->getAPIntValue().ult(NumSrcElts))
1774  DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue());
1775 
1776  // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
1777  // anything about the extended bits.
1778  APInt DemandedSrcBits = DemandedBits;
1779  if (BitWidth > EltBitWidth)
1780  DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth);
1781 
1782  if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO,
1783  Depth + 1))
1784  return true;
1785 
1786  Known = Known2;
1787  if (BitWidth > EltBitWidth)
1788  Known = Known.zext(BitWidth, false /* => any extend */);
1789  break;
1790  }
1791  case ISD::BITCAST: {
1792  SDValue Src = Op.getOperand(0);
1793  EVT SrcVT = Src.getValueType();
1794  unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
1795 
1796  // If this is an FP->Int bitcast and if the sign bit is the only
1797  // thing demanded, turn this into a FGETSIGN.
1798  if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() &&
1799  DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) &&
1800  SrcVT.isFloatingPoint()) {
1801  bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT);
1803  if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 &&
1804  SrcVT != MVT::f128) {
1805  // Cannot eliminate/lower SHL for f128 yet.
1806  EVT Ty = OpVTLegal ? VT : MVT::i32;
1807  // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1808  // place. We expect the SHL to be eliminated by other optimizations.
1809  SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src);
1810  unsigned OpVTSizeInBits = Op.getValueSizeInBits();
1811  if (!OpVTLegal && OpVTSizeInBits > 32)
1812  Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign);
1813  unsigned ShVal = Op.getValueSizeInBits() - 1;
1814  SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT);
1815  return TLO.CombineTo(Op,
1816  TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
1817  }
1818  }
1819 
1820  // Bitcast from a vector using SimplifyDemanded Bits/VectorElts.
1821  // Demand the elt/bit if any of the original elts/bits are demanded.
1822  // TODO - bigendian once we have test coverage.
1823  // TODO - bool vectors once SimplifyDemandedVectorElts has SETCC support.
1824  if (SrcVT.isVector() && NumSrcEltBits > 1 &&
1825  (BitWidth % NumSrcEltBits) == 0 &&
1826  TLO.DAG.getDataLayout().isLittleEndian()) {
1827  unsigned Scale = BitWidth / NumSrcEltBits;
1828  unsigned NumSrcElts = SrcVT.getVectorNumElements();
1829  APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits);
1830  APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts);
1831  for (unsigned i = 0; i != Scale; ++i) {
1832  unsigned Offset = i * NumSrcEltBits;
1833  APInt Sub = DemandedBits.extractBits(NumSrcEltBits, Offset);
1834  if (!Sub.isNullValue()) {
1835  DemandedSrcBits |= Sub;
1836  for (unsigned j = 0; j != NumElts; ++j)
1837  if (DemandedElts[j])
1838  DemandedSrcElts.setBit((j * Scale) + i);
1839  }
1840  }
1841 
1842  APInt KnownSrcUndef, KnownSrcZero;
1843  if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
1844  KnownSrcZero, TLO, Depth + 1))
1845  return true;
1846 
1847  KnownBits KnownSrcBits;
1848  if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
1849  KnownSrcBits, TLO, Depth + 1))
1850  return true;
1851  } else if ((NumSrcEltBits % BitWidth) == 0 &&
1852  TLO.DAG.getDataLayout().isLittleEndian()) {
1853  unsigned Scale = NumSrcEltBits / BitWidth;
1854  unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
1855  APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits);
1856  APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts);
1857  for (unsigned i = 0; i != NumElts; ++i)
1858  if (DemandedElts[i]) {
1859  unsigned Offset = (i % Scale) * BitWidth;
1860  DemandedSrcBits.insertBits(DemandedBits, Offset);
1861  DemandedSrcElts.setBit(i / Scale);
1862  }
1863 
1864  if (SrcVT.isVector()) {
1865  APInt KnownSrcUndef, KnownSrcZero;
1866  if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
1867  KnownSrcZero, TLO, Depth + 1))
1868  return true;
1869  }
1870 
1871  KnownBits KnownSrcBits;
1872  if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
1873  KnownSrcBits, TLO, Depth + 1))
1874  return true;
1875  }
1876 
1877  // If this is a bitcast, let computeKnownBits handle it. Only do this on a
1878  // recursive call where Known may be useful to the caller.
1879  if (Depth > 0) {
1880  Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1881  return false;
1882  }
1883  break;
1884  }
1885  case ISD::ADD:
1886  case ISD::MUL:
1887  case ISD::SUB: {
1888  // Add, Sub, and Mul don't demand any bits in positions beyond that
1889  // of the highest bit demanded of them.
1890  SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
1891  SDNodeFlags Flags = Op.getNode()->getFlags();
1892  unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros();
1893  APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
1894  if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO,
1895  Depth + 1) ||
1896  SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO,
1897  Depth + 1) ||
1898  // See if the operation should be performed at a smaller bit width.
1899  ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) {
1900  if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) {
1901  // Disable the nsw and nuw flags. We can no longer guarantee that we
1902  // won't wrap after simplification.
1903  Flags.setNoSignedWrap(false);
1904  Flags.setNoUnsignedWrap(false);
1905  SDValue NewOp =
1906  TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags);
1907  return TLO.CombineTo(Op, NewOp);
1908  }
1909  return true;
1910  }
1911 
1912  // Attempt to avoid multi-use ops if we don't need anything from them.
1913  if (!LoMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
1915  Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1);
1917  Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1);
1918  if (DemandedOp0 || DemandedOp1) {
1919  Flags.setNoSignedWrap(false);
1920  Flags.setNoUnsignedWrap(false);
1921  Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1922  Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1923  SDValue NewOp =
1924  TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags);
1925  return TLO.CombineTo(Op, NewOp);
1926  }
1927  }
1928 
1929  // If we have a constant operand, we may be able to turn it into -1 if we
1930  // do not demand the high bits. This can make the constant smaller to
1931  // encode, allow more general folding, or match specialized instruction
1932  // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
1933  // is probably not useful (and could be detrimental).
1935  APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ);
1936  if (C && !C->isAllOnesValue() && !C->isOne() &&
1937  (C->getAPIntValue() | HighMask).isAllOnesValue()) {
1938  SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
1939  // We can't guarantee that the new math op doesn't wrap, so explicitly
1940  // clear those flags to prevent folding with a potential existing node
1941  // that has those flags set.
1942  SDNodeFlags Flags;
1943  Flags.setNoSignedWrap(false);
1944  Flags.setNoUnsignedWrap(false);
1945  SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags);
1946  return TLO.CombineTo(Op, NewOp);
1947  }
1948 
1950  }
1951  default:
1952  if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1953  if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts,
1954  Known, TLO, Depth))
1955  return true;
1956  break;
1957  }
1958 
1959  // Just use computeKnownBits to compute output bits.
1960  Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1961  break;
1962  }
1963 
1964  // If we know the value of all of the demanded bits, return this as a
1965  // constant.
1966  if (DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
1967  // Avoid folding to a constant if any OpaqueConstant is involved.
1968  const SDNode *N = Op.getNode();
1970  E = SDNodeIterator::end(N);
1971  I != E; ++I) {
1972  SDNode *Op = *I;
1973  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
1974  if (C->isOpaque())
1975  return false;
1976  }
1977  // TODO: Handle float bits as well.
1978  if (VT.isInteger())
1979  return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
1980  }
1981 
1982  return false;
1983 }
1984 
1986  const APInt &DemandedElts,
1987  APInt &KnownUndef,
1988  APInt &KnownZero,
1989  DAGCombinerInfo &DCI) const {
1990  SelectionDAG &DAG = DCI.DAG;
1991  TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1992  !DCI.isBeforeLegalizeOps());
1993 
1994  bool Simplified =
1995  SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
1996  if (Simplified) {
1997  DCI.AddToWorklist(Op.getNode());
1998  DCI.CommitTargetLoweringOpt(TLO);
1999  }
2000 
2001  return Simplified;
2002 }
2003 
2004 /// Given a vector binary operation and known undefined elements for each input
2005 /// operand, compute whether each element of the output is undefined.
2007  const APInt &UndefOp0,
2008  const APInt &UndefOp1) {
2009  EVT VT = BO.getValueType();
2010  assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() &&
2011  "Vector binop only");
2012 
2013  EVT EltVT = VT.getVectorElementType();
2014  unsigned NumElts = VT.getVectorNumElements();
2015  assert(UndefOp0.getBitWidth() == NumElts &&
2016  UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
2017 
2018  auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
2019  const APInt &UndefVals) {
2020  if (UndefVals[Index])
2021  return DAG.getUNDEF(EltVT);
2022 
2023  if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2024  // Try hard to make sure that the getNode() call is not creating temporary
2025  // nodes. Ignore opaque integers because they do not constant fold.
2026  SDValue Elt = BV->getOperand(Index);
2027  auto *C = dyn_cast<ConstantSDNode>(Elt);
2028  if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
2029  return Elt;
2030  }
2031 
2032  return SDValue();
2033  };
2034 
2035  APInt KnownUndef = APInt::getNullValue(NumElts);
2036  for (unsigned i = 0; i != NumElts; ++i) {
2037  // If both inputs for this element are either constant or undef and match
2038  // the element type, compute the constant/undef result for this element of
2039  // the vector.
2040  // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
2041  // not handle FP constants. The code within getNode() should be refactored
2042  // to avoid the danger of creating a bogus temporary node here.
2043  SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
2044  SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
2045  if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
2046  if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
2047  KnownUndef.setBit(i);
2048  }
2049  return KnownUndef;
2050 }
2051 
2053  SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef,
2054  APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
2055  bool AssumeSingleUse) const {
2056  EVT VT = Op.getValueType();
2057  APInt DemandedElts = OriginalDemandedElts;
2058  unsigned NumElts = DemandedElts.getBitWidth();
2059  assert(VT.isVector() && "Expected vector op");
2060  assert(VT.getVectorNumElements() == NumElts &&
2061  "Mask size mismatches value type element count!");
2062 
2063  KnownUndef = KnownZero = APInt::getNullValue(NumElts);
2064 
2065  // Undef operand.
2066  if (Op.isUndef()) {
2067  KnownUndef.setAllBits();
2068  return false;
2069  }
2070 
2071  // If Op has other users, assume that all elements are needed.
2072  if (!Op.getNode()->hasOneUse() && !AssumeSingleUse)
2073  DemandedElts.setAllBits();
2074 
2075  // Not demanding any elements from Op.
2076  if (DemandedElts == 0) {
2077  KnownUndef.setAllBits();
2078  return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2079  }
2080 
2081  // Limit search depth.
2082  if (Depth >= 6)
2083  return false;
2084 
2085  SDLoc DL(Op);
2086  unsigned EltSizeInBits = VT.getScalarSizeInBits();
2087 
2088  switch (Op.getOpcode()) {
2089  case ISD::SCALAR_TO_VECTOR: {
2090  if (!DemandedElts[0]) {
2091  KnownUndef.setAllBits();
2092  return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2093  }
2094  KnownUndef.setHighBits(NumElts - 1);
2095  break;
2096  }
2097  case ISD::BITCAST: {
2098  SDValue Src = Op.getOperand(0);
2099  EVT SrcVT = Src.getValueType();
2100 
2101  // We only handle vectors here.
2102  // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits?
2103  if (!SrcVT.isVector())
2104  break;
2105 
2106  // Fast handling of 'identity' bitcasts.
2107  unsigned NumSrcElts = SrcVT.getVectorNumElements();
2108  if (NumSrcElts == NumElts)
2109  return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
2110  KnownZero, TLO, Depth + 1);
2111 
2112  APInt SrcZero, SrcUndef;
2113  APInt SrcDemandedElts = APInt::getNullValue(NumSrcElts);
2114 
2115  // Bitcast from 'large element' src vector to 'small element' vector, we
2116  // must demand a source element if any DemandedElt maps to it.
2117  if ((NumElts % NumSrcElts) == 0) {
2118  unsigned Scale = NumElts / NumSrcElts;
2119  for (unsigned i = 0; i != NumElts; ++i)
2120  if (DemandedElts[i])
2121  SrcDemandedElts.setBit(i / Scale);
2122 
2123  if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2124  TLO, Depth + 1))
2125  return true;
2126 
2127  // Try calling SimplifyDemandedBits, converting demanded elts to the bits
2128  // of the large element.
2129  // TODO - bigendian once we have test coverage.
2130  if (TLO.DAG.getDataLayout().isLittleEndian()) {
2131  unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
2132  APInt SrcDemandedBits = APInt::getNullValue(SrcEltSizeInBits);
2133  for (unsigned i = 0; i != NumElts; ++i)
2134  if (DemandedElts[i]) {
2135  unsigned Ofs = (i % Scale) * EltSizeInBits;
2136  SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
2137  }
2138 
2139  KnownBits Known;
2140  if (SimplifyDemandedBits(Src, SrcDemandedBits, Known, TLO, Depth + 1))
2141  return true;
2142  }
2143 
2144  // If the src element is zero/undef then all the output elements will be -
2145  // only demanded elements are guaranteed to be correct.
2146  for (unsigned i = 0; i != NumSrcElts; ++i) {
2147  if (SrcDemandedElts[i]) {
2148  if (SrcZero[i])
2149  KnownZero.setBits(i * Scale, (i + 1) * Scale);
2150  if (SrcUndef[i])
2151  KnownUndef.setBits(i * Scale, (i + 1) * Scale);
2152  }
2153  }
2154  }
2155 
2156  // Bitcast from 'small element' src vector to 'large element' vector, we
2157  // demand all smaller source elements covered by the larger demanded element
2158  // of this vector.
2159  if ((NumSrcElts % NumElts) == 0) {
2160  unsigned Scale = NumSrcElts / NumElts;
2161  for (unsigned i = 0; i != NumElts; ++i)
2162  if (DemandedElts[i])
2163  SrcDemandedElts.setBits(i * Scale, (i + 1) * Scale);
2164 
2165  if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2166  TLO, Depth + 1))
2167  return true;
2168 
2169  // If all the src elements covering an output element are zero/undef, then
2170  // the output element will be as well, assuming it was demanded.
2171  for (unsigned i = 0; i != NumElts; ++i) {
2172  if (DemandedElts[i]) {
2173  if (SrcZero.extractBits(Scale, i * Scale).isAllOnesValue())
2174  KnownZero.setBit(i);
2175  if (SrcUndef.extractBits(Scale, i * Scale).isAllOnesValue())
2176  KnownUndef.setBit(i);
2177  }
2178  }
2179  }
2180  break;
2181  }
2182  case ISD::BUILD_VECTOR: {
2183  // Check all elements and simplify any unused elements with UNDEF.
2184  if (!DemandedElts.isAllOnesValue()) {
2185  // Don't simplify BROADCASTS.
2186  if (llvm::any_of(Op->op_values(),
2187  [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
2188  SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end());
2189  bool Updated = false;
2190  for (unsigned i = 0; i != NumElts; ++i) {
2191  if (!DemandedElts[i] && !Ops[i].isUndef()) {
2192  Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
2193  KnownUndef.setBit(i);
2194  Updated = true;
2195  }
2196  }
2197  if (Updated)
2198  return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
2199  }
2200  }
2201  for (unsigned i = 0; i != NumElts; ++i) {
2202  SDValue SrcOp = Op.getOperand(i);
2203  if (SrcOp.isUndef()) {
2204  KnownUndef.setBit(i);
2205  } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
2206  (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) {
2207  KnownZero.setBit(i);
2208  }
2209  }
2210  break;
2211  }
2212  case ISD::CONCAT_VECTORS: {
2213  EVT SubVT = Op.getOperand(0).getValueType();
2214  unsigned NumSubVecs = Op.getNumOperands();
2215  unsigned NumSubElts = SubVT.getVectorNumElements();
2216  for (unsigned i = 0; i != NumSubVecs; ++i) {
2217  SDValue SubOp = Op.getOperand(i);
2218  APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
2219  APInt SubUndef, SubZero;
2220  if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
2221  Depth + 1))
2222  return true;
2223  KnownUndef.insertBits(SubUndef, i * NumSubElts);
2224  KnownZero.insertBits(SubZero, i * NumSubElts);
2225  }
2226  break;
2227  }
2228  case ISD::INSERT_SUBVECTOR: {
2229  if (!isa<ConstantSDNode>(Op.getOperand(2)))
2230  break;
2231  SDValue Base = Op.getOperand(0);
2232  SDValue Sub = Op.getOperand(1);
2233  EVT SubVT = Sub.getValueType();
2234  unsigned NumSubElts = SubVT.getVectorNumElements();
2235  const APInt &Idx = Op.getConstantOperandAPInt(2);
2236  if (Idx.ugt(NumElts - NumSubElts))
2237  break;
2238  unsigned SubIdx = Idx.getZExtValue();
2239  APInt SubElts = DemandedElts.extractBits(NumSubElts, SubIdx);
2240  APInt SubUndef, SubZero;
2241  if (SimplifyDemandedVectorElts(Sub, SubElts, SubUndef, SubZero, TLO,
2242  Depth + 1))
2243  return true;
2244  APInt BaseElts = DemandedElts;
2245  BaseElts.insertBits(APInt::getNullValue(NumSubElts), SubIdx);
2246 
2247  // If none of the base operand elements are demanded, replace it with undef.
2248  if (!BaseElts && !Base.isUndef())
2249  return TLO.CombineTo(Op,
2250  TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
2251  TLO.DAG.getUNDEF(VT),
2252  Op.getOperand(1),
2253  Op.getOperand(2)));
2254 
2255  if (SimplifyDemandedVectorElts(Base, BaseElts, KnownUndef, KnownZero, TLO,
2256  Depth + 1))
2257  return true;
2258  KnownUndef.insertBits(SubUndef, SubIdx);
2259  KnownZero.insertBits(SubZero, SubIdx);
2260  break;
2261  }
2262  case ISD::EXTRACT_SUBVECTOR: {
2263  SDValue Src = Op.getOperand(0);
2265  unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2266  if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2267  // Offset the demanded elts by the subvector index.
2268  uint64_t Idx = SubIdx->getZExtValue();
2269  APInt SrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2270  APInt SrcUndef, SrcZero;
2271  if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
2272  Depth + 1))
2273  return true;
2274  KnownUndef = SrcUndef.extractBits(NumElts, Idx);
2275  KnownZero = SrcZero.extractBits(NumElts, Idx);
2276  }
2277  break;
2278  }
2279  case ISD::INSERT_VECTOR_ELT: {
2280  SDValue Vec = Op.getOperand(0);
2281  SDValue Scl = Op.getOperand(1);
2282  auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2283 
2284  // For a legal, constant insertion index, if we don't need this insertion
2285  // then strip it, else remove it from the demanded elts.
2286  if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
2287  unsigned Idx = CIdx->getZExtValue();
2288  if (!DemandedElts[Idx])
2289  return TLO.CombineTo(Op, Vec);
2290 
2291  APInt DemandedVecElts(DemandedElts);
2292  DemandedVecElts.clearBit(Idx);
2293  if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
2294  KnownZero, TLO, Depth + 1))
2295  return true;
2296 
2297  KnownUndef.clearBit(Idx);
2298  if (Scl.isUndef())
2299  KnownUndef.setBit(Idx);
2300 
2301  KnownZero.clearBit(Idx);
2302  if (isNullConstant(Scl) || isNullFPConstant(Scl))
2303  KnownZero.setBit(Idx);
2304  break;
2305  }
2306 
2307  APInt VecUndef, VecZero;
2308  if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
2309  Depth + 1))
2310  return true;
2311  // Without knowing the insertion index we can't set KnownUndef/KnownZero.
2312  break;
2313  }
2314  case ISD::VSELECT: {
2315  // Try to transform the select condition based on the current demanded
2316  // elements.
2317  // TODO: If a condition element is undef, we can choose from one arm of the
2318  // select (and if one arm is undef, then we can propagate that to the
2319  // result).
2320  // TODO - add support for constant vselect masks (see IR version of this).
2321  APInt UnusedUndef, UnusedZero;
2322  if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UnusedUndef,
2323  UnusedZero, TLO, Depth + 1))
2324  return true;
2325 
2326  // See if we can simplify either vselect operand.
2327  APInt DemandedLHS(DemandedElts);
2328  APInt DemandedRHS(DemandedElts);
2329  APInt UndefLHS, ZeroLHS;
2330  APInt UndefRHS, ZeroRHS;
2331  if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS,
2332  ZeroLHS, TLO, Depth + 1))
2333  return true;
2334  if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS,
2335  ZeroRHS, TLO, Depth + 1))
2336  return true;
2337 
2338  KnownUndef = UndefLHS & UndefRHS;
2339  KnownZero = ZeroLHS & ZeroRHS;
2340  break;
2341  }
2342  case ISD::VECTOR_SHUFFLE: {
2343  ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
2344 
2345  // Collect demanded elements from shuffle operands..
2346  APInt DemandedLHS(NumElts, 0);
2347  APInt DemandedRHS(NumElts, 0);
2348  for (unsigned i = 0; i != NumElts; ++i) {
2349  int M = ShuffleMask[i];
2350  if (M < 0 || !DemandedElts[i])
2351  continue;
2352  assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
2353  if (M < (int)NumElts)
2354  DemandedLHS.setBit(M);
2355  else
2356  DemandedRHS.setBit(M - NumElts);
2357  }
2358 
2359  // See if we can simplify either shuffle operand.
2360  APInt UndefLHS, ZeroLHS;
2361  APInt UndefRHS, ZeroRHS;
2362  if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS,
2363  ZeroLHS, TLO, Depth + 1))
2364  return true;
2365  if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS,
2366  ZeroRHS, TLO, Depth + 1))
2367  return true;
2368 
2369  // Simplify mask using undef elements from LHS/RHS.
2370  bool Updated = false;
2371  bool IdentityLHS = true, IdentityRHS = true;
2372  SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end());
2373  for (unsigned i = 0; i != NumElts; ++i) {
2374  int &M = NewMask[i];
2375  if (M < 0)
2376  continue;
2377  if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
2378  (M >= (int)NumElts && UndefRHS[M - NumElts])) {
2379  Updated = true;
2380  M = -1;
2381  }
2382  IdentityLHS &= (M < 0) || (M == (int)i);
2383  IdentityRHS &= (M < 0) || ((M - NumElts) == i);
2384  }
2385 
2386  // Update legal shuffle masks based on demanded elements if it won't reduce
2387  // to Identity which can cause premature removal of the shuffle mask.
2388  if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps &&
2389  isShuffleMaskLegal(NewMask, VT))
2390  return TLO.CombineTo(Op,
2391  TLO.DAG.getVectorShuffle(VT, DL, Op.getOperand(0),
2392  Op.getOperand(1), NewMask));
2393 
2394  // Propagate undef/zero elements from LHS/RHS.
2395  for (unsigned i = 0; i != NumElts; ++i) {
2396  int M = ShuffleMask[i];
2397  if (M < 0) {
2398  KnownUndef.setBit(i);
2399  } else if (M < (int)NumElts) {
2400  if (UndefLHS[M])
2401  KnownUndef.setBit(i);
2402  if (ZeroLHS[M])
2403  KnownZero.setBit(i);
2404  } else {
2405  if (UndefRHS[M - NumElts])
2406  KnownUndef.setBit(i);
2407  if (ZeroRHS[M - NumElts])
2408  KnownZero.setBit(i);
2409  }
2410  }
2411  break;
2412  }
2416  APInt SrcUndef, SrcZero;
2417  SDValue Src = Op.getOperand(0);
2418  unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2419  APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts);
2420  if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
2421  Depth + 1))
2422  return true;
2423  KnownZero = SrcZero.zextOrTrunc(NumElts);
2424  KnownUndef = SrcUndef.zextOrTrunc(NumElts);
2425 
2427  Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
2428  DemandedSrcElts == 1 && TLO.DAG.getDataLayout().isLittleEndian()) {
2429  // aext - if we just need the bottom element then we can bitcast.
2430  return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2431  }
2432 
2434  // zext(undef) upper bits are guaranteed to be zero.
2435  if (DemandedElts.isSubsetOf(KnownUndef))
2436  return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
2437  KnownUndef.clearAllBits();
2438  }
2439  break;
2440  }
2441 
2442  // TODO: There are more binop opcodes that could be handled here - MUL, MIN,
2443  // MAX, saturated math, etc.
2444  case ISD::OR:
2445  case ISD::XOR:
2446  case ISD::ADD:
2447  case ISD::SUB:
2448  case ISD::FADD:
2449  case ISD::FSUB:
2450  case ISD::FMUL:
2451  case ISD::FDIV:
2452  case ISD::FREM: {
2453  APInt UndefRHS, ZeroRHS;
2454  if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, UndefRHS,
2455  ZeroRHS, TLO, Depth + 1))
2456  return true;
2457  APInt UndefLHS, ZeroLHS;
2458  if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UndefLHS,
2459  ZeroLHS, TLO, Depth + 1))
2460  return true;
2461 
2462  KnownZero = ZeroLHS & ZeroRHS;
2463  KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
2464  break;
2465  }
2466  case ISD::SHL:
2467  case ISD::SRL:
2468  case ISD::SRA:
2469  case ISD::ROTL:
2470  case ISD::ROTR: {
2471  APInt UndefRHS, ZeroRHS;
2472  if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, UndefRHS,
2473  ZeroRHS, TLO, Depth + 1))
2474  return true;
2475  APInt UndefLHS, ZeroLHS;
2476  if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UndefLHS,
2477  ZeroLHS, TLO, Depth + 1))
2478  return true;
2479 
2480  KnownZero = ZeroLHS;
2481  KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
2482  break;
2483  }
2484  case ISD::MUL:
2485  case ISD::AND: {
2486  APInt SrcUndef, SrcZero;
2487  if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, SrcUndef,
2488  SrcZero, TLO, Depth + 1))
2489  return true;
2490  if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
2491  KnownZero, TLO, Depth + 1))
2492  return true;
2493 
2494  // If either side has a zero element, then the result element is zero, even
2495  // if the other is an UNDEF.
2496  // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
2497  // and then handle 'and' nodes with the rest of the binop opcodes.
2498  KnownZero |= SrcZero;
2499  KnownUndef &= SrcUndef;
2500  KnownUndef &= ~KnownZero;
2501  break;
2502  }
2503  case ISD::TRUNCATE:
2504  case ISD::SIGN_EXTEND:
2505  case ISD::ZERO_EXTEND:
2506  if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
2507  KnownZero, TLO, Depth + 1))
2508  return true;
2509 
2510  if (Op.getOpcode() == ISD::ZERO_EXTEND) {
2511  // zext(undef) upper bits are guaranteed to be zero.
2512  if (DemandedElts.isSubsetOf(KnownUndef))
2513  return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
2514  KnownUndef.clearAllBits();
2515  }
2516  break;
2517  default: {
2518  if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
2519  if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
2520  KnownZero, TLO, Depth))
2521  return true;
2522  } else {
2523  KnownBits Known;
2524  APInt DemandedBits = APInt::getAllOnesValue(EltSizeInBits);
2525  if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
2526  TLO, Depth, AssumeSingleUse))
2527  return true;
2528  }
2529  break;
2530  }
2531  }
2532  assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
2533 
2534  // Constant fold all undef cases.
2535  // TODO: Handle zero cases as well.
2536  if (DemandedElts.isSubsetOf(KnownUndef))
2537  return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2538 
2539  return false;
2540 }
2541 
2542 /// Determine which of the bits specified in Mask are known to be either zero or
2543 /// one and return them in the Known.
2545  KnownBits &Known,
2546  const APInt &DemandedElts,
2547  const SelectionDAG &DAG,
2548  unsigned Depth) const {
2552  Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2553  "Should use MaskedValueIsZero if you don't know whether Op"
2554  " is a target node!");
2555  Known.resetAll();
2556 }
2557 
2559  Register R, KnownBits &Known, const APInt &DemandedElts,
2560  const MachineRegisterInfo &MRI, unsigned Depth) const {
2561  Known.resetAll();
2562 }
2563 
2565  KnownBits &Known,
2566  const APInt &DemandedElts,
2567  const SelectionDAG &DAG,
2568  unsigned Depth) const {
2569  assert(isa<FrameIndexSDNode>(Op) && "expected FrameIndex");
2570 
2571  if (unsigned Align = DAG.InferPtrAlignment(Op)) {
2572  // The low bits are known zero if the pointer is aligned.
2573  Known.Zero.setLowBits(Log2_32(Align));
2574  }
2575 }
2576 
2577 /// This method can be implemented by targets that want to expose additional
2578 /// information about sign bits to the DAG Combiner.
2580  const APInt &,
2581  const SelectionDAG &,
2582  unsigned Depth) const {
2586  Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2587  "Should use ComputeNumSignBits if you don't know whether Op"
2588  " is a target node!");
2589  return 1;
2590 }
2591 
2593  SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
2594  TargetLoweringOpt &TLO, unsigned Depth) const {
2598  Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2599  "Should use SimplifyDemandedVectorElts if you don't know whether Op"
2600  " is a target node!");
2601  return false;
2602 }
2603 
2605  SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
2606  KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
2610  Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2611  "Should use SimplifyDemandedBits if you don't know whether Op"
2612  " is a target node!");
2613  computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
2614  return false;
2615 }
2616 
2618  SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
2619  SelectionDAG &DAG, unsigned Depth) const {
2620  assert(
2621  (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2624  Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2625  "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
2626  " is a target node!");
2627  return SDValue();
2628 }
2629 
2631  return nullptr;
2632 }
2633 
2635  const SelectionDAG &DAG,
2636  bool SNaN,
2637  unsigned Depth) const {
2641  Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2642  "Should use isKnownNeverNaN if you don't know whether Op"
2643  " is a target node!");
2644  return false;
2645 }
2646 
2647 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
2648 // work with truncating build vectors and vectors with elements of less than
2649 // 8 bits.
2651  if (!N)
2652  return false;
2653 
2654  APInt CVal;
2655  if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
2656  CVal = CN->getAPIntValue();
2657  } else if (auto *BV = dyn_cast<BuildVectorSDNode>(N)) {
2658  auto *CN = BV->getConstantSplatNode();
2659  if (!CN)
2660  return false;
2661 
2662  // If this is a truncating build vector, truncate the splat value.
2663  // Otherwise, we may fail to match the expected values below.
2664  unsigned BVEltWidth = BV->getValueType(0).getScalarSizeInBits();
2665  CVal = CN->getAPIntValue();
2666  if (BVEltWidth < CVal.getBitWidth())
2667  CVal = CVal.trunc(BVEltWidth);
2668  } else {
2669  return false;
2670  }
2671 
2672  switch (getBooleanContents(N->getValueType(0))) {
2674  return CVal[0];
2676  return CVal.isOneValue();
2678  return CVal.isAllOnesValue();
2679  }
2680 
2681  llvm_unreachable("Invalid boolean contents");
2682 }
2683 
2685  if (!N)
2686  return false;
2687 
2688  const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
2689  if (!CN) {
2691  if (!BV)
2692  return false;
2693 
2694  // Only interested in constant splats, we don't care about undef
2695  // elements in identifying boolean constants and getConstantSplatNode
2696  // returns NULL if all ops are undef;
2697  CN = BV->getConstantSplatNode();
2698  if (!CN)
2699  return false;
2700  }
2701 
2703  return !CN->getAPIntValue()[0];
2704 
2705  return CN->isNullValue();
2706 }
2707 
2709  bool SExt) const {
2710  if (VT == MVT::i1)
2711  return N->isOne();
2712 
2714  switch (Cnt) {
2716  // An extended value of 1 is always true, unless its original type is i1,
2717  // in which case it will be sign extended to -1.
2718  return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
2721  return N->isAllOnesValue() && SExt;
2722  }
2723  llvm_unreachable("Unexpected enumeration.");
2724 }
2725 
2726 /// This helper function of SimplifySetCC tries to optimize the comparison when
2727 /// either operand of the SetCC node is a bitwise-and instruction.
2728 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
2729  ISD::CondCode Cond, const SDLoc &DL,
2730  DAGCombinerInfo &DCI) const {
2731  // Match these patterns in any of their permutations:
2732  // (X & Y) == Y
2733  // (X & Y) != Y
2734  if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
2735  std::swap(N0, N1);
2736 
2737  EVT OpVT = N0.getValueType();
2738  if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
2739  (Cond != ISD::SETEQ && Cond != ISD::SETNE))
2740  return SDValue();
2741 
2742  SDValue X, Y;
2743  if (N0.getOperand(0) == N1) {
2744  X = N0.getOperand(1);
2745  Y = N0.getOperand(0);
2746  } else if (N0.getOperand(1) == N1) {
2747  X = N0.getOperand(0);
2748  Y = N0.getOperand(1);
2749  } else {
2750  return SDValue();
2751  }
2752 
2753  SelectionDAG &DAG = DCI.DAG;
2754  SDValue Zero = DAG.getConstant(0, DL, OpVT);
2755  if (DAG.isKnownToBeAPowerOfTwo(Y)) {
2756  // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
2757  // Note that where Y is variable and is known to have at most one bit set
2758  // (for example, if it is Z & 1) we cannot do this; the expressions are not
2759  // equivalent when Y == 0.
2760  Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
2761  if (DCI.isBeforeLegalizeOps() ||
2762  isCondCodeLegal(Cond, N0.getSimpleValueType()))
2763  return DAG.getSetCC(DL, VT, N0, Zero, Cond);
2764  } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
2765  // If the target supports an 'and-not' or 'and-complement' logic operation,
2766  // try to use that to make a comparison operation more efficient.
2767  // But don't do this transform if the mask is a single bit because there are
2768  // more efficient ways to deal with that case (for example, 'bt' on x86 or
2769  // 'rlwinm' on PPC).
2770 
2771  // Bail out if the compare operand that we want to turn into a zero is
2772  // already a zero (otherwise, infinite loop).
2773  auto *YConst = dyn_cast<ConstantSDNode>(Y);
2774  if (YConst && YConst->isNullValue())
2775  return SDValue();
2776 
2777  // Transform this into: ~X & Y == 0.
2778  SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
2779  SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
2780  return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
2781  }
2782 
2783  return SDValue();
2784 }
2785 
2786 /// There are multiple IR patterns that could be checking whether certain
2787 /// truncation of a signed number would be lossy or not. The pattern which is
2788 /// best at IR level, may not lower optimally. Thus, we want to unfold it.
2789 /// We are looking for the following pattern: (KeptBits is a constant)
2790 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
2791 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
2792 /// KeptBits also can't be 1, that would have been folded to %x dstcond 0
2793 /// We will unfold it into the natural trunc+sext pattern:
2794 /// ((%x << C) a>> C) dstcond %x
2795 /// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x)
2796 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
2797  EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
2798  const SDLoc &DL) const {
2799  // We must be comparing with a constant.
2800  ConstantSDNode *C1;
2801  if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
2802  return SDValue();
2803 
2804  // N0 should be: add %x, (1 << (KeptBits-1))
2805  if (N0->getOpcode() != ISD::ADD)
2806  return SDValue();
2807 
2808  // And we must be 'add'ing a constant.
2809  ConstantSDNode *C01;
2810  if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
2811  return SDValue();
2812 
2813  SDValue X = N0->getOperand(0);
2814  EVT XVT = X.getValueType();
2815 
2816  // Validate constants ...
2817 
2818  APInt I1 = C1->getAPIntValue();
2819 
2820  ISD::CondCode NewCond;
2821  if (Cond == ISD::CondCode::SETULT) {
2822  NewCond = ISD::CondCode::SETEQ;
2823  } else if (Cond == ISD::CondCode::SETULE) {
2824  NewCond = ISD::CondCode::SETEQ;
2825  // But need to 'canonicalize' the constant.
2826  I1 += 1;
2827  } else if (Cond == ISD::CondCode::SETUGT) {
2828  NewCond = ISD::CondCode::SETNE;
2829  // But need to 'canonicalize' the constant.
2830  I1 += 1;
2831  } else if (Cond == ISD::CondCode::SETUGE) {
2832  NewCond = ISD::CondCode::SETNE;
2833  } else
2834  return SDValue();
2835 
2836  APInt I01 = C01->getAPIntValue();
2837 
2838  auto checkConstants = [&I1, &I01]() -> bool {
2839  // Both of them must be power-of-two, and the constant from setcc is bigger.
2840  return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
2841  };
2842 
2843  if (checkConstants()) {
2844  // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256
2845  } else {
2846  // What if we invert constants? (and the target predicate)
2847  I1.negate();
2848  I01.negate();
2849  NewCond = getSetCCInverse(NewCond, /*isInteger=*/true);
2850  if (!checkConstants())
2851  return SDValue();
2852  // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256
2853  }
2854 
2855  // They are power-of-two, so which bit is set?
2856  const unsigned KeptBits = I1.logBase2();
2857  const unsigned KeptBitsMinusOne = I01.logBase2();
2858 
2859  // Magic!
2860  if (KeptBits != (KeptBitsMinusOne + 1))
2861  return SDValue();
2862  assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
2863 
2864  // We don't want to do this in every single case.
2865  SelectionDAG &DAG = DCI.DAG;
2866  if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck(
2867  XVT, KeptBits))
2868  return SDValue();
2869 
2870  const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits;
2871  assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable");
2872 
2873  // Unfold into: ((%x << C) a>> C) cond %x
2874  // Where 'cond' will be either 'eq' or 'ne'.
2875  SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT);
2876  SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt);
2877  SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt);
2878  SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond);
2879 
2880  return T2;
2881 }
2882 
2883 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
2884 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
2885  EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
2886  DAGCombinerInfo &DCI, const SDLoc &DL) const {
2887  assert(isConstOrConstSplat(N1C) &&
2888  isConstOrConstSplat(N1C)->getAPIntValue().isNullValue() &&
2889  "Should be a comparison with 0.");
2890  assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2891  "Valid only for [in]equality comparisons.");
2892 
2893  unsigned NewShiftOpcode;
2894  SDValue X, C, Y;
2895 
2896  SelectionDAG &DAG = DCI.DAG;
2897  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2898 
2899  // Look for '(C l>>/<< Y)'.
2900  auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) {
2901  // The shift should be one-use.
2902  if (!V.hasOneUse())
2903  return false;
2904  unsigned OldShiftOpcode = V.getOpcode();
2905  switch (OldShiftOpcode) {
2906  case ISD::SHL:
2907  NewShiftOpcode = ISD::SRL;
2908  break;
2909  case ISD::SRL:
2910  NewShiftOpcode = ISD::SHL;
2911  break;
2912  default:
2913  return false; // must be a logical shift.
2914  }
2915  // We should be shifting a constant.
2916  // FIXME: best to use isConstantOrConstantVector().
2917  C = V.getOperand(0);
2918  ConstantSDNode *CC =
2919  isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
2920  if (!CC)
2921  return false;
2922  Y = V.getOperand(1);
2923 
2924  ConstantSDNode *XC =
2925  isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
2926  return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
2927  X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
2928  };
2929 
2930  // LHS of comparison should be an one-use 'and'.
2931  if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
2932  return SDValue();
2933 
2934  X = N0.getOperand(0);
2935  SDValue Mask = N0.getOperand(1);
2936 
2937  // 'and' is commutative!
2938  if (!Match(Mask)) {
2939  std::swap(X, Mask);
2940  if (!Match(Mask))
2941  return SDValue();
2942  }
2943 
2944  EVT VT = X.getValueType();
2945 
2946  // Produce:
2947  // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
2948  SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
2949  SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
2950  SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
2951  return T2;
2952 }
2953 
2954 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as
2955 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
2956 /// handle the commuted versions of these patterns.
2957 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
2958  ISD::CondCode Cond, const SDLoc &DL,
2959  DAGCombinerInfo &DCI) const {
2960  unsigned BOpcode = N0.getOpcode();
2961  assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
2962  "Unexpected binop");
2963  assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
2964 
2965  // (X + Y) == X --> Y == 0
2966  // (X - Y) == X --> Y == 0
2967  // (X ^ Y) == X --> Y == 0
2968  SelectionDAG &DAG = DCI.DAG;
2969  EVT OpVT = N0.getValueType();
2970  SDValue X = N0.getOperand(0);
2971  SDValue Y = N0.getOperand(1);
2972  if (X == N1)
2973  return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
2974 
2975  if (Y != N1)
2976  return SDValue();
2977 
2978  // (X + Y) == Y --> X == 0
2979  // (X ^ Y) == Y --> X == 0
2980  if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
2981  return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
2982 
2983  // The shift would not be valid if the operands are boolean (i1).
2984  if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
2985  return SDValue();
2986 
2987  // (X - Y) == Y --> X == Y << 1
2988  EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(),
2989  !DCI.isBeforeLegalize());
2990  SDValue One = DAG.getConstant(1, DL, ShiftVT);
2991  SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
2992  if (!DCI.isCalledByLegalizer())
2993  DCI.AddToWorklist(YShl1.getNode());
2994  return DAG.getSetCC(DL, VT, X, YShl1, Cond);
2995 }
2996 
2997 /// Try to simplify a setcc built with the specified operands and cc. If it is
2998 /// unable to simplify it, return a null SDValue.
3000  ISD::CondCode Cond, bool foldBooleans,
3001  DAGCombinerInfo &DCI,
3002  const SDLoc &dl) const {
3003  SelectionDAG &DAG = DCI.DAG;
3004  EVT OpVT = N0.getValueType();
3005 
3006  // Constant fold or commute setcc.
3007  if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
3008  return Fold;
3009 
3010  // Ensure that the constant occurs on the RHS and fold constant comparisons.
3011  // TODO: Handle non-splat vector constants. All undef causes trouble.
3012  ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
3013  if (isConstOrConstSplat(N0) &&
3014  (DCI.isBeforeLegalizeOps() ||
3015  isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
3016  return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
3017 
3018  // If we have a subtract with the same 2 non-constant operands as this setcc
3019  // -- but in reverse order -- then try to commute the operands of this setcc
3020  // to match. A matching pair of setcc (cmp) and sub may be combined into 1
3021  // instruction on some targets.
3022  if (!isConstOrConstSplat(N0) && !isConstOrConstSplat(N1) &&
3023  (DCI.isBeforeLegalizeOps() ||
3024  isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
3025  DAG.getNodeIfExists(ISD::SUB, DAG.getVTList(OpVT), { N1, N0 } ) &&
3026  !DAG.getNodeIfExists(ISD::SUB, DAG.getVTList(OpVT), { N0, N1 } ))
3027  return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
3028 
3029  if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
3030  const APInt &C1 = N1C->getAPIntValue();
3031 
3032  // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
3033  // equality comparison, then we're just comparing whether X itself is
3034  // zero.
3035  if (N0.getOpcode() == ISD::SRL && (C1.isNullValue() || C1.isOneValue()) &&
3036  N0.getOperand(0).getOpcode() == ISD::CTLZ &&
3037  N0.getOperand(1).getOpcode() == ISD::Constant) {
3038  const APInt &ShAmt = N0.getConstantOperandAPInt(1);
3039  if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3040  ShAmt == Log2_32(N0.getValueSizeInBits())) {
3041  if ((C1 == 0) == (Cond == ISD::SETEQ)) {
3042  // (srl (ctlz x), 5) == 0 -> X != 0
3043  // (srl (ctlz x), 5) != 1 -> X != 0
3044  Cond = ISD::SETNE;
3045  } else {
3046  // (srl (ctlz x), 5) != 0 -> X == 0
3047  // (srl (ctlz x), 5) == 1 -> X == 0
3048  Cond = ISD::SETEQ;
3049  }
3050  SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
3051  return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
3052  Zero, Cond);
3053  }
3054  }
3055 
3056  SDValue CTPOP = N0;
3057  // Look through truncs that don't change the value of a ctpop.
3058  if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
3059  CTPOP = N0.getOperand(0);
3060 
3061  if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
3062  (N0 == CTPOP ||
3064  EVT CTVT = CTPOP.getValueType();
3065  SDValue CTOp = CTPOP.getOperand(0);
3066 
3067  // (ctpop x) u< 2 -> (x & x-1) == 0
3068  // (ctpop x) u> 1 -> (x & x-1) != 0
3069  if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
3070  SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
3071  SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
3072  SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
3074  return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC);
3075  }
3076 
3077  // If ctpop is not supported, expand a power-of-2 comparison based on it.
3078  if (C1 == 1 && !isOperationLegalOrCustom(ISD::CTPOP, CTVT) &&
3079  (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3080  // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0)
3081  // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0)
3082  SDValue Zero = DAG.getConstant(0, dl, CTVT);
3083  SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
3084  ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, true);
3085  SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
3086  SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
3087  SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond);
3088  SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
3089  unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR;
3090  return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS);
3091  }
3092  }
3093 
3094  // (zext x) == C --> x == (trunc C)
3095  // (sext x) == C --> x == (trunc C)
3096  if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3097  DCI.isBeforeLegalize() && N0->hasOneUse()) {
3098  unsigned MinBits = N0.getValueSizeInBits();
3099  SDValue PreExt;
3100  bool Signed = false;
3101  if (N0->getOpcode() == ISD::ZERO_EXTEND) {
3102  // ZExt
3103  MinBits = N0->getOperand(0).getValueSizeInBits();
3104  PreExt = N0->getOperand(0);
3105  } else if (N0->getOpcode() == ISD::AND) {
3106  // DAGCombine turns costly ZExts into ANDs
3107  if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
3108  if ((C->getAPIntValue()+1).isPowerOf2()) {
3109  MinBits = C->getAPIntValue().countTrailingOnes();
3110  PreExt = N0->getOperand(0);
3111  }
3112  } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
3113  // SExt
3114  MinBits = N0->getOperand(0).getValueSizeInBits();
3115  PreExt = N0->getOperand(0);
3116  Signed = true;
3117  } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
3118  // ZEXTLOAD / SEXTLOAD
3119  if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
3120  MinBits = LN0->getMemoryVT().getSizeInBits();
3121  PreExt = N0;
3122  } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
3123  Signed = true;
3124  MinBits = LN0->getMemoryVT().getSizeInBits();
3125  PreExt = N0;
3126  }
3127  }
3128 
3129  // Figure out how many bits we need to preserve this constant.
3130  unsigned ReqdBits = Signed ?
3131  C1.getBitWidth() - C1.getNumSignBits() + 1 :
3132  C1.getActiveBits();
3133 
3134  // Make sure we're not losing bits from the constant.
3135  if (MinBits > 0 &&
3136  MinBits < C1.getBitWidth() &&
3137  MinBits >= ReqdBits) {
3138  EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
3139  if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
3140  // Will get folded away.
3141  SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
3142  if (MinBits == 1 && C1 == 1)
3143  // Invert the condition.
3144  return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
3145  Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3146  SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
3147  return DAG.getSetCC(dl, VT, Trunc, C, Cond);
3148  }
3149 
3150  // If truncating the setcc operands is not desirable, we can still
3151  // simplify the expression in some cases:
3152  // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
3153  // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
3154  // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
3155  // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
3156  // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
3157  // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
3158  SDValue TopSetCC = N0->getOperand(0);
3159  unsigned N0Opc = N0->getOpcode();
3160  bool SExt = (N0Opc == ISD::SIGN_EXTEND);
3161  if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
3162  TopSetCC.getOpcode() == ISD::SETCC &&
3163  (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
3164  (isConstFalseVal(N1C) ||
3165  isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
3166 
3167  bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) ||
3168  (!N1C->isNullValue() && Cond == ISD::SETNE);
3169 
3170  if (!Inverse)
3171  return TopSetCC;
3172 
3174  cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
3175  TopSetCC.getOperand(0).getValueType().isInteger());
3176  return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
3177  TopSetCC.getOperand(1),
3178  InvCond);
3179  }
3180  }
3181  }
3182 
3183  // If the LHS is '(and load, const)', the RHS is 0, the test is for
3184  // equality or unsigned, and all 1 bits of the const are in the same
3185  // partial word, see if we can shorten the load.
3186  if (DCI.isBeforeLegalize() &&
3187  !ISD::isSignedIntSetCC(Cond) &&
3188  N0.getOpcode() == ISD::AND && C1 == 0 &&
3189  N0.getNode()->hasOneUse() &&
3190  isa<LoadSDNode>(N0.getOperand(0)) &&
3191  N0.getOperand(0).getNode()->hasOneUse() &&
3192  isa<ConstantSDNode>(N0.getOperand(1))) {
3193  LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
3194  APInt bestMask;
3195  unsigned bestWidth = 0, bestOffset = 0;
3196  if (!Lod->isVolatile() && Lod->isUnindexed()) {
3197  unsigned origWidth = N0.getValueSizeInBits();
3198  unsigned maskWidth = origWidth;
3199  // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
3200  // 8 bits, but have to be careful...
3201  if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
3202  origWidth = Lod->getMemoryVT().getSizeInBits();
3203  const APInt &Mask = N0.getConstantOperandAPInt(1);
3204  for (unsigned width = origWidth / 2; width>=8; width /= 2) {
3205  APInt newMask = APInt::getLowBitsSet(maskWidth, width);
3206  for (unsigned offset=0; offset<origWidth/width; offset++) {
3207  if (Mask.isSubsetOf(newMask)) {
3208  if (DAG.getDataLayout().isLittleEndian())
3209  bestOffset = (uint64_t)offset * (width/8);
3210  else
3211  bestOffset = (origWidth/width - offset - 1) * (width/8);
3212  bestMask = Mask.lshr(offset * (width/8) * 8);
3213  bestWidth = width;
3214  break;
3215  }
3216  newMask <<= width;
3217  }
3218  }
3219  }
3220  if (bestWidth) {
3221  EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
3222  if (newVT.isRound() &&
3223  shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) {
3224  EVT PtrType = Lod->getOperand(1).getValueType();
3225  SDValue Ptr = Lod->getBasePtr();
3226  if (bestOffset != 0)
3227  Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
3228  DAG.getConstant(bestOffset, dl, PtrType));
3229  unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
3230  SDValue NewLoad = DAG.getLoad(
3231  newVT, dl, Lod->getChain(), Ptr,
3232  Lod->getPointerInfo().getWithOffset(bestOffset), NewAlign);
3233  return DAG.getSetCC(dl, VT,
3234  DAG.getNode(ISD::AND, dl, newVT, NewLoad,
3235  DAG.getConstant(bestMask.trunc(bestWidth),
3236  dl, newVT)),
3237  DAG.getConstant(0LL, dl, newVT), Cond);
3238  }
3239  }
3240  }
3241 
3242  // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
3243  if (N0.getOpcode() == ISD::ZERO_EXTEND) {
3244  unsigned InSize = N0.getOperand(0).getValueSizeInBits();
3245 
3246  // If the comparison constant has bits in the upper part, the
3247  // zero-extended value could never match.
3248  if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
3249  C1.getBitWidth() - InSize))) {
3250  switch (Cond) {
3251  case ISD::SETUGT:
3252  case ISD::SETUGE:
3253  case ISD::SETEQ:
3254  return DAG.getConstant(0, dl, VT);
3255  case ISD::SETULT:
3256  case ISD::SETULE:
3257  case ISD::SETNE:
3258  return DAG.getConstant(1, dl, VT);
3259  case ISD::SETGT:
3260  case ISD::SETGE:
3261  // True if the sign bit of C1 is set.
3262  return DAG.getConstant(C1.isNegative(), dl, VT);
3263  case ISD::SETLT:
3264  case ISD::SETLE:
3265  // True if the sign bit of C1 isn't set.
3266  return DAG.getConstant(C1.isNonNegative(), dl, VT);
3267  default:
3268  break;
3269  }
3270  }
3271 
3272  // Otherwise, we can perform the comparison with the low bits.
3273  switch (Cond) {
3274  case ISD::SETEQ:
3275  case ISD::SETNE:
3276  case ISD::SETUGT:
3277  case ISD::SETUGE:
3278  case ISD::SETULT:
3279  case ISD::SETULE: {
3280  EVT newVT = N0.getOperand(0).getValueType();
3281  if (DCI.isBeforeLegalizeOps() ||
3282  (isOperationLegal(ISD::SETCC, newVT) &&
3283  isCondCodeLegal(Cond, newVT.getSimpleVT()))) {
3284  EVT NewSetCCVT =
3285  getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT);
3286  SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
3287 
3288  SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
3289  NewConst, Cond);
3290  return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
3291  }
3292  break;
3293  }
3294  default:
3295  break; // todo, be more careful with signed comparisons
3296  }
3297  } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3298  (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3299  EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
3300  unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
3301  EVT ExtDstTy = N0.getValueType();
3302  unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
3303 
3304  // If the constant doesn't fit into the number of bits for the source of
3305  // the sign extension, it is impossible for both sides to be equal.
3306  if (C1.getMinSignedBits() > ExtSrcTyBits)
3307  return DAG.getConstant(Cond == ISD::SETNE, dl, VT);
3308 
3309  SDValue ZextOp;
3310  EVT Op0Ty = N0.getOperand(0).getValueType();
3311  if (Op0Ty == ExtSrcTy) {
3312  ZextOp = N0.getOperand(0);
3313  } else {
3314  APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
3315  ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
3316  DAG.getConstant(Imm, dl, Op0Ty));
3317  }
3318  if (!DCI.isCalledByLegalizer())
3319  DCI.AddToWorklist(ZextOp.getNode());
3320  // Otherwise, make this a use of a zext.
3321  return DAG.getSetCC(dl, VT, ZextOp,
3323  ExtDstTyBits,
3324  ExtSrcTyBits),
3325  dl, ExtDstTy),
3326  Cond);
3327  } else if ((N1C->isNullValue() || N1C->isOne()) &&
3328  (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3329  // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC
3330  if (N0.getOpcode() == ISD::SETCC &&
3331  isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
3332  bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
3333  if (TrueWhenTrue)
3334  return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
3335  // Invert the condition.
3336  ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
3337  CC = ISD::getSetCCInverse(CC,
3338  N0.getOperand(0).getValueType().isInteger());
3339  if (DCI.isBeforeLegalizeOps() ||
3340  isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
3341  return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
3342  }
3343 
3344  if ((N0.getOpcode() == ISD::XOR ||
3345  (N0.getOpcode() == ISD::AND &&
3346  N0.getOperand(0).getOpcode() == ISD::XOR &&
3347  N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
3348  isa<ConstantSDNode>(N0.getOperand(1)) &&
3349  cast<ConstantSDNode>(N0.getOperand(1))->isOne()) {
3350  // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
3351  // can only do this if the top bits are known zero.
3352  unsigned BitWidth = N0.getValueSizeInBits();
3353  if (DAG.MaskedValueIsZero(N0,
3354  APInt::getHighBitsSet(BitWidth,
3355  BitWidth-1))) {
3356  // Okay, get the un-inverted input value.
3357  SDValue Val;
3358  if (N0.getOpcode() == ISD::XOR) {
3359  Val = N0.getOperand(0);
3360  } else {
3361  assert(N0.getOpcode() == ISD::AND &&
3362  N0.getOperand(0).getOpcode() == ISD::XOR);
3363  // ((X^1)&1)^1 -> X & 1
3364  Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
3365  N0.getOperand(0).getOperand(0),
3366  N0.getOperand(1));
3367  }
3368 
3369  return DAG.getSetCC(dl, VT, Val, N1,
3370  Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3371  }
3372  } else if (N1C->isOne() &&
3373  (VT == MVT::i1 ||
3374  getBooleanContents(N0->getValueType(0)) ==
3376  SDValue Op0 = N0;
3377  if (Op0.getOpcode() == ISD::TRUNCATE)
3378  Op0 = Op0.getOperand(0);
3379 
3380  if ((Op0.getOpcode() == ISD::XOR) &&
3381  Op0.getOperand(0).getOpcode() == ISD::SETCC &&
3382  Op0.getOperand(1).getOpcode() == ISD::SETCC) {
3383  // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
3384  Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
3385  return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
3386  Cond);
3387  }
3388  if (Op0.getOpcode() == ISD::AND &&
3389  isa<ConstantSDNode>(Op0.getOperand(1)) &&
3390  cast<ConstantSDNode>(Op0.getOperand(1))->isOne()) {
3391  // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
3392  if (Op0.getValueType().bitsGT(VT))
3393  Op0 = DAG.getNode(ISD::AND, dl, VT,
3394  DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
3395  DAG.getConstant(1, dl, VT));
3396  else if (Op0.getValueType().bitsLT(VT))
3397  Op0 = DAG.getNode(ISD::AND, dl, VT,
3398  DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
3399  DAG.getConstant(1, dl, VT));
3400 
3401  return DAG.getSetCC(dl, VT, Op0,
3402  DAG.getConstant(0, dl, Op0.getValueType()),
3403  Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3404  }
3405  if (Op0.getOpcode() == ISD::AssertZext &&
3406  cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
3407  return DAG.getSetCC(dl, VT, Op0,
3408  DAG.getConstant(0, dl, Op0.getValueType()),
3409  Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3410  }
3411  }
3412 
3413  // Given:
3414  // icmp eq/ne (urem %x, %y), 0
3415  // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
3416  // icmp eq/ne %x, 0
3417  if (N0.getOpcode() == ISD::UREM && N1C->isNullValue() &&
3418  (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3419  KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
3420  KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
3421  if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
3422  return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
3423  }
3424 
3425  if (SDValue V =
3426  optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
3427  return V;
3428  }
3429 
3430  // These simplifications apply to splat vectors as well.
3431  // TODO: Handle more splat vector cases.
3432  if (auto *N1C = isConstOrConstSplat(N1)) {
3433  const APInt &C1 = N1C->getAPIntValue();
3434 
3435  APInt MinVal, MaxVal;
3436  unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
3437  if (ISD::isSignedIntSetCC(Cond)) {
3438  MinVal = APInt::getSignedMinValue(OperandBitSize);
3439  MaxVal = APInt::getSignedMaxValue(OperandBitSize);
3440  } else {
3441  MinVal = APInt::getMinValue(OperandBitSize);
3442  MaxVal = APInt::getMaxValue(OperandBitSize);
3443  }
3444 
3445  // Canonicalize GE/LE comparisons to use GT/LT comparisons.
3446  if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
3447  // X >= MIN --> true
3448  if (C1 == MinVal)
3449  return DAG.getBoolConstant(true, dl, VT, OpVT);
3450 
3451  if (!VT.isVector()) { // TODO: Support this for vectors.
3452  // X >= C0 --> X > (C0 - 1)
3453  APInt C = C1 - 1;
3454  ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
3455  if ((DCI.isBeforeLegalizeOps() ||
3456  isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
3457  (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
3459  return DAG.getSetCC(dl, VT, N0,
3460  DAG.getConstant(C, dl, N1.getValueType()),
3461  NewCC);
3462  }
3463  }
3464  }
3465 
3466  if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
3467  // X <= MAX --> true
3468  if (C1 == MaxVal)
3469  return DAG.getBoolConstant(true, dl, VT, OpVT);
3470 
3471  // X <= C0 --> X < (C0 + 1)
3472  if (!VT.isVector()) { // TODO: Support this for vectors.
3473  APInt C = C1 + 1;
3474  ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
3475  if ((DCI.isBeforeLegalizeOps() ||
3476  isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
3477  (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
3479  return DAG.getSetCC(dl, VT, N0,
3480  DAG.getConstant(C, dl, N1.getValueType()),
3481  NewCC);
3482  }
3483  }
3484  }
3485 
3486  if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
3487  if (C1 == MinVal)
3488  return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
3489 
3490  // TODO: Support this for vectors after legalize ops.
3491  if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
3492  // Canonicalize setlt X, Max --> setne X, Max
3493  if (C1 == MaxVal)
3494  return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
3495 
3496  // If we have setult X, 1, turn it into seteq X, 0
3497  if (C1 == MinVal+1)
3498  return DAG.getSetCC(dl, VT, N0,
3499  DAG.getConstant(MinVal, dl, N0.getValueType()),
3500  ISD::SETEQ);
3501  }
3502  }
3503 
3504  if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
3505  if (C1 == MaxVal)
3506  return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
3507 
3508  // TODO: Support this for vectors after legalize ops.
3509  if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
3510  // Canonicalize setgt X, Min --> setne X, Min
3511  if (C1 == MinVal)
3512  return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
3513 
3514  // If we have setugt X, Max-1, turn it into seteq X, Max
3515  if (C1 == MaxVal-1)
3516  return DAG.getSetCC(dl, VT, N0,
3517  DAG.getConstant(MaxVal, dl, N0.getValueType()),
3518  ISD::SETEQ);
3519  }
3520  }
3521 
3522  if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
3523  // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
3524  if (C1.isNullValue())
3525  if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
3526  VT, N0, N1, Cond, DCI, dl))
3527  return CC;
3528  }
3529 
3530  // If we have "setcc X, C0", check to see if we can shrink the immediate
3531  // by changing cc.
3532  // TODO: Support this for vectors after legalize ops.
3533  if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
3534  // SETUGT X, SINTMAX -> SETLT X, 0
3535  if (Cond == ISD::SETUGT &&
3536  C1 == APInt::getSignedMaxValue(OperandBitSize))
3537  return DAG.getSetCC(dl, VT, N0,
3538  DAG.getConstant(0, dl, N1.getValueType()),
3539  ISD::SETLT);
3540 
3541  // SETULT X, SINTMIN -> SETGT X, -1
3542  if (Cond == ISD::SETULT &&
3543  C1 == APInt::getSignedMinValue(OperandBitSize)) {
3544  SDValue ConstMinusOne =
3545  DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl,
3546  N1.getValueType());
3547  return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
3548  }
3549  }
3550  }
3551 
3552  // Back to non-vector simplifications.
3553  // TODO: Can we do these for vector splats?
3554  if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
3555  const APInt &C1 = N1C->getAPIntValue();
3556 
3557  // Fold bit comparisons when we can.
3558  if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3559  (VT == N0.getValueType() ||
3560  (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
3561  N0.getOpcode() == ISD::AND) {
3562  auto &DL = DAG.getDataLayout();
3563  if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3564  EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL,
3565  !DCI.isBeforeLegalize());
3566  if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
3567  // Perform the xform if the AND RHS is a single bit.
3568  if (AndRHS->getAPIntValue().isPowerOf2()) {
3569  return DAG.getNode(ISD::TRUNCATE, dl, VT,
3570  DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
3571  DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl,
3572  ShiftTy)));
3573  }
3574  } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
3575  // (X & 8) == 8 --> (X & 8) >> 3
3576  // Perform the xform if C1 is a single bit.
3577  if (C1.isPowerOf2()) {
3578  return DAG.getNode(ISD::TRUNCATE, dl, VT,
3579  DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
3580  DAG.getConstant(C1.logBase2(), dl,
3581  ShiftTy)));
3582  }
3583  }
3584  }
3585  }
3586 
3587  if (C1.getMinSignedBits() <= 64 &&
3589  // (X & -256) == 256 -> (X >> 8) == 1
3590  if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3591  N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
3592  if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3593  const APInt &AndRHSC = AndRHS->getAPIntValue();
3594  if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
3595  unsigned ShiftBits = AndRHSC.countTrailingZeros();
3596  auto &DL = DAG.getDataLayout();
3597  EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL,
3598  !DCI.isBeforeLegalize());
3599  EVT CmpTy = N0.getValueType();
3600  SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
3601  DAG.getConstant(ShiftBits, dl,
3602  ShiftTy));
3603  SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy);
3604  return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
3605  }
3606  }
3607  } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
3608  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
3609  bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
3610  // X < 0x100000000 -> (X >> 32) < 1
3611  // X >= 0x100000000 -> (X >> 32) >= 1
3612  // X <= 0x0ffffffff -> (X >> 32) < 1
3613  // X > 0x0ffffffff -> (X >> 32) >= 1
3614  unsigned ShiftBits;
3615  APInt NewC = C1;
3616  ISD::CondCode NewCond = Cond;
3617  if (AdjOne) {
3618  ShiftBits = C1.countTrailingOnes();
3619  NewC = NewC + 1;
3620  NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3621  } else {
3622  ShiftBits = C1.countTrailingZeros();
3623  }
3624  NewC.lshrInPlace(ShiftBits);
3625  if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
3627  auto &DL = DAG.getDataLayout();
3628  EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL,
3629  !DCI.isBeforeLegalize());
3630  EVT CmpTy = N0.getValueType();
3631  SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
3632  DAG.getConstant(ShiftBits, dl, ShiftTy));
3633  SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy);
3634  return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
3635  }
3636  }
3637  }
3638  }
3639 
3640  if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) {
3641  auto *CFP = cast<ConstantFPSDNode>(N1);
3642  assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
3643 
3644  // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
3645  // constant if knowing that the operand is non-nan is enough. We prefer to
3646  // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
3647  // materialize 0.0.
3648  if (Cond == ISD::SETO || Cond == ISD::SETUO)
3649  return DAG.getSetCC(dl, VT, N0, N0, Cond);
3650 
3651  // setcc (fneg x), C -> setcc swap(pred) x, -C
3652  if (N0.getOpcode() == ISD::FNEG) {
3654  if (DCI.isBeforeLegalizeOps() ||
3655  isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
3656  SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
3657  return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
3658  }
3659  }
3660 
3661  // If the condition is not legal, see if we can find an equivalent one
3662  // which is legal.
3663  if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
3664  // If the comparison was an awkward floating-point == or != and one of
3665  // the comparison operands is infinity or negative infinity, convert the
3666  // condition to a less-awkward <= or >=.
3667  if (CFP->getValueAPF().isInfinity()) {
3668  if (CFP->getValueAPF().isNegative()) {
3669  if (Cond == ISD::SETOEQ &&
3671  return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
3672  if (Cond == ISD::SETUEQ &&
3674  return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
3675  if (Cond == ISD::SETUNE &&
3677  return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
3678  if (Cond == ISD::SETONE &&
3680  return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
3681  } else {
3682  if (Cond == ISD::SETOEQ &&
3684  return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
3685  if (Cond == ISD::SETUEQ &&
3687  return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
3688  if (Cond == ISD::SETUNE &&
3690  return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
3691  if (Cond == ISD::SETONE &&
3693  return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
3694  }
3695  }
3696  }
3697  }
3698 
3699  if (N0 == N1) {
3700  // The sext(setcc()) => setcc() optimization relies on the appropriate
3701  // constant being emitted.
3702  assert(!N0.getValueType().isInteger() &&
3703  "Integer types should be handled by FoldSetCC");
3704 
3705  bool EqTrue = ISD::isTrueWhenEqual(Cond);
3706  unsigned UOF = ISD::getUnorderedFlavor(Cond);
3707  if (UOF == 2) // FP operators that are undefined on NaNs.
3708  return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
3709  if (UOF == unsigned(EqTrue))
3710  return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
3711  // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
3712  // if it is not already.
3713  ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
3714  if (NewCond != Cond &&
3715  (DCI.isBeforeLegalizeOps() ||
3716  isCondCodeLegal(NewCond, N0.getSimpleValueType())))
3717  return DAG.getSetCC(dl, VT, N0, N1, NewCond);
3718  }
3719 
3720  if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3721  N0.getValueType().isInteger()) {
3722  if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
3723  N0.getOpcode() == ISD::XOR) {
3724  // Simplify (X+Y) == (X+Z) --> Y == Z
3725  if (N0.getOpcode() == N1.getOpcode()) {
3726  if (N0.getOperand(0) == N1.getOperand(0))
3727  return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
3728  if (N0.getOperand(1) == N1.getOperand(1))
3729  return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
3730  if (isCommutativeBinOp(N0.getOpcode())) {
3731  // If X op Y == Y op X, try other combinations.
3732  if (N0.getOperand(0) == N1.getOperand(1))
3733  return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
3734  Cond);
3735  if (N0.getOperand(1) == N1.getOperand(0))
3736  return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
3737  Cond);
3738  }
3739  }
3740 
3741  // If RHS is a legal immediate value for a compare instruction, we need
3742  // to be careful about increasing register pressure needlessly.
3743  bool LegalRHSImm = false;
3744 
3745  if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
3746  if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3747  // Turn (X+C1) == C2 --> X == C2-C1
3748  if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
3749  return DAG.getSetCC(dl, VT, N0.getOperand(0),
3750  DAG.getConstant(RHSC->getAPIntValue()-
3751  LHSR->getAPIntValue(),
3752  dl, N0.getValueType()), Cond);
3753  }
3754 
3755  // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
3756  if (N0.getOpcode() == ISD::XOR)
3757  // If we know that all of the inverted bits are zero, don't bother
3758  // performing the inversion.
3759  if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
3760  return
3761  DAG.getSetCC(dl, VT, N0.getOperand(0),
3762  DAG.getConstant(LHSR->getAPIntValue() ^
3763  RHSC->getAPIntValue(),
3764  dl, N0.getValueType()),
3765  Cond);
3766  }
3767 
3768  // Turn (C1-X) == C2 --> X == C1-C2
3769  if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
3770  if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
3771  return
3772  DAG.getSetCC(dl, VT, N0.getOperand(1),
3773  DAG.getConstant(SUBC->getAPIntValue() -
3774  RHSC->getAPIntValue(),
3775  dl, N0.getValueType()),
3776  Cond);
3777  }
3778  }
3779 
3780  // Could RHSC fold directly into a compare?
3781  if (RHSC->getValueType(0).getSizeInBits() <= 64)
3782  LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
3783  }
3784 
3785  // (X+Y) == X --> Y == 0 and similar folds.
3786  // Don't do this if X is an immediate that can fold into a cmp
3787  // instruction and X+Y has other uses. It could be an induction variable
3788  // chain, and the transform would increase register pressure.
3789  if (!LegalRHSImm || N0.hasOneUse())
3790  if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
3791  return V;
3792  }
3793 
3794  if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
3795  N1.getOpcode() == ISD::XOR)
3796  if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
3797  return V;
3798 
3799  if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
3800  return V;
3801  }
3802 
3803  // Fold remainder of division by a constant.
3804  if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
3805  N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3807 
3808  // When division is cheap or optimizing for minimum size,
3809  // fall through to DIVREM creation by skipping this fold.
3810  if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttribute(Attribute::MinSize)) {
3811  if (N0.getOpcode() == ISD::UREM) {
3812  if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
3813  return Folded;
3814  } else if (N0.getOpcode() == ISD::SREM) {
3815  if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
3816  return Folded;
3817  }
3818  }
3819  }
3820 
3821  // Fold away ALL boolean setcc's.
3822  if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
3823  SDValue Temp;
3824  switch (Cond) {
3825  default: llvm_unreachable("Unknown integer setcc!");
3826  case ISD::SETEQ: // X == Y -> ~(X^Y)
3827  Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
3828  N0 = DAG.getNOT(dl, Temp, OpVT);
3829  if (!DCI.isCalledByLegalizer())
3830  DCI.AddToWorklist(Temp.getNode());
3831  break;
3832  case ISD::SETNE: // X != Y --> (X^Y)
3833  N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
3834  break;
3835  case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
3836  case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
3837  Temp = DAG.getNOT(dl, N0, OpVT);
3838  N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
3839  if (!DCI.isCalledByLegalizer())
3840  DCI.AddToWorklist(Temp.getNode());
3841  break;
3842  case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
3843  case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
3844  Temp = DAG.getNOT(dl, N1, OpVT);
3845  N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
3846  if (!DCI.isCalledByLegalizer())
3847  DCI.AddToWorklist(Temp.getNode());
3848  break;
3849  case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
3850  case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
3851  Temp = DAG.getNOT(dl, N0, OpVT);
3852  N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
3853  if (!DCI.isCalledByLegalizer())
3854  DCI.AddToWorklist(Temp.getNode());
3855  break;
3856  case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
3857  case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
3858  Temp = DAG.getNOT(dl, N1, OpVT);
3859  N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
3860  break;
3861  }
3862  if (VT.getScalarType() != MVT::i1) {
3863  if (!DCI.isCalledByLegalizer())
3864  DCI.AddToWorklist(N0.getNode());
3865  // FIXME: If running after legalize, we probably can't do this.
3867  N0 = DAG.getNode(ExtendCode, dl, VT, N0);
3868  }
3869  return N0;
3870  }
3871 
3872  // Could not fold it.
3873  return SDValue();
3874 }
3875 
3876 /// Returns true (and the GlobalValue and the offset) if the node is a
3877 /// GlobalAddress + offset.
3879  int64_t &Offset) const {
3880 
3881  SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
3882 
3883  if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
3884  GA = GASD->getGlobal();
3885  Offset += GASD->getOffset();
3886  return true;
3887  }
3888 
3889  if (N->getOpcode() == ISD::ADD) {
3890  SDValue N1 = N->getOperand(0);
3891  SDValue N2 = N->getOperand(1);
3892  if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
3893  if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
3894  Offset += V->getSExtValue();
3895  return true;
3896  }
3897  } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
3898  if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
3899  Offset += V->getSExtValue();
3900  return true;
3901  }
3902  }
3903  }
3904 
3905  return false;
3906 }
3907 
3909  DAGCombinerInfo &DCI) const {
3910  // Default implementation: no optimization.
3911  return SDValue();
3912 }
3913 
3914 //===----------------------------------------------------------------------===//
3915 // Inline Assembler Implementation Methods
3916 //===----------------------------------------------------------------------===//
3917 
3920  unsigned S = Constraint.size();
3921 
3922  if (S == 1) {
3923  switch (Constraint[0]) {
3924  default: break;
3925  case 'r':
3926  return C_RegisterClass;
3927  case 'm': // memory
3928  case 'o': // offsetable
3929  case 'V': // not offsetable
3930  return C_Memory;
3931  case 'n': // Simple Integer
3932  case 'E': // Floating Point Constant
3933  case 'F': // Floating Point Constant
3934  return C_Immediate;
3935  case 'i': // Simple Integer or Relocatable Constant
3936  case 's': // Relocatable Constant
3937  case 'p': // Address.
3938  case 'X': // Allow ANY value.
3939  case 'I': // Target registers.
3940  case 'J':
3941  case 'K':
3942  case 'L':
3943  case 'M':
3944  case 'N':
3945  case 'O':
3946  case 'P':
3947  case '<':
3948  case '>':
3949  return C_Other;
3950  }
3951  }
3952 
3953  if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
3954  if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
3955  return C_Memory;
3956  return C_Register;
3957  }
3958  return C_Unknown;
3959 }
3960 
3961 /// Try to replace an X constraint, which matches anything, with another that
3962 /// has more specific requirements based on the type of the corresponding
3963 /// operand.
3964 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
3965  if (ConstraintVT.isInteger())
3966  return "r";
3967  if (ConstraintVT.isFloatingPoint())
3968  return "f"; // works for many targets
3969  return nullptr;
3970 }
3971 
3973  SDValue &Chain, SDValue &Flag, SDLoc DL, const AsmOperandInfo &OpInfo,
3974  SelectionDAG &DAG) const {
3975  return SDValue();
3976 }
3977 
3978 /// Lower the specified operand into the Ops vector.
3979 /// If it is invalid, don't add anything to Ops.
3981  std::string &Constraint,
3982  std::vector<SDValue> &Ops,
3983  SelectionDAG &DAG) const {
3984 
3985  if (Constraint.length() > 1) return;
3986 
3987  char ConstraintLetter = Constraint[0];
3988  switch (ConstraintLetter) {
3989  default: break;
3990  case 'X': // Allows any operand; labels (basic block) use this.
3991  if (Op.getOpcode() == ISD::BasicBlock ||
3993  Ops.push_back(Op);
3994  return;
3995  }
3997  case 'i': // Simple Integer or Relocatable Constant
3998  case 'n': // Simple Integer
3999  case 's': { // Relocatable Constant
4000 
4001  GlobalAddressSDNode *GA;
4002  ConstantSDNode *C;
4003  BlockAddressSDNode *BA;
4004  uint64_t Offset = 0;
4005 
4006  // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
4007  // etc., since getelementpointer is variadic. We can't use
4008  // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
4009  // while in this case the GA may be furthest from the root node which is
4010  // likely an ISD::ADD.
4011  while (1) {
4012  if ((GA = dyn_cast<GlobalAddressSDNode>(Op)) && ConstraintLetter != 'n') {
4013  Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
4014  GA->getValueType(0),
4015  Offset + GA->getOffset()));
4016  return;
4017  } else if ((C = dyn_cast<ConstantSDNode>(Op)) &&
4018  ConstraintLetter != 's') {
4019  // gcc prints these as sign extended. Sign extend value to 64 bits
4020  // now; without this it would get ZExt'd later in
4021  // ScheduleDAGSDNodes::EmitNode, which is very generic.
4022  bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
4024  ISD::NodeType ExtOpc = IsBool ? getExtendForContent(BCont)
4025  : ISD::SIGN_EXTEND;
4026  int64_t ExtVal = ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue()
4027  : C->getSExtValue();
4028  Ops.push_back(DAG.getTargetConstant(Offset + ExtVal,
4029  SDLoc(C), MVT::i64));
4030  return;
4031  } else if ((BA = dyn_cast<BlockAddressSDNode>(Op)) &&
4032  ConstraintLetter != 'n') {
4033  Ops.push_back(DAG.getTargetBlockAddress(
4034  BA->getBlockAddress(), BA->getValueType(0),
4035  Offset + BA->getOffset(), BA->getTargetFlags()));
4036  return;
4037  } else {
4038  const unsigned OpCode = Op.getOpcode();
4039  if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
4040  if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
4041  Op = Op.getOperand(1);
4042  // Subtraction is not commutative.
4043  else if (OpCode == ISD::ADD &&
4044  (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
4045  Op = Op.getOperand(0);
4046  else
4047  return;
4048  Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
4049  continue;
4050  }
4051  }
4052  return;
4053  }
4054  break;
4055  }
4056  }
4057 }
4058 
4059 std::pair<unsigned, const TargetRegisterClass *>
4061  StringRef Constraint,
4062  MVT VT) const {
4063  if (Constraint.empty() || Constraint[0] != '{')
4064  return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
4065  assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
4066 
4067  // Remove the braces from around the name.
4068  StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
4069 
4070  std::pair<unsigned, const TargetRegisterClass *> R =
4071  std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
4072 
4073  // Figure out which register class contains this reg.
4074  for (const TargetRegisterClass *RC : RI->regclasses()) {
4075  // If none of the value types for this register class are valid, we
4076  // can't use it. For example, 64-bit reg classes on 32-bit targets.
4077  if (!isLegalRC(*RI, *RC))
4078  continue;
4079 
4080  for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
4081  I != E; ++I) {
4082  if (RegName.equals_lower(RI->getRegAsmName(*I))) {
4083  std::pair<unsigned, const TargetRegisterClass *> S =
4084  std::make_pair(*I, RC);
4085 
4086  // If this register class has the requested value type, return it,
4087  // otherwise keep searching and return the first class found
4088  // if no other is found which explicitly has the requested type.
4089  if (RI->isTypeLegalForClass(*RC, VT))
4090  return S;
4091  if (!R.second)
4092  R = S;
4093  }
4094  }
4095  }
4096 
4097  return R;
4098 }
4099 
4100 //===----------------------------------------------------------------------===//
4101 // Constraint Selection.
4102 
4103 /// Return true of this is an input operand that is a matching constraint like
4104 /// "4".
4106  assert(!ConstraintCode.empty() && "No known constraint!");
4107  return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
4108 }
4109 
4110 /// If this is an input matching constraint, this method returns the output
4111 /// operand it matches.
4113  assert(!ConstraintCode.empty() && "No known constraint!");
4114  return atoi(ConstraintCode.c_str());
4115 }
4116 
4117 /// Split up the constraint string from the inline assembly value into the
4118 /// specific constraints and their prefixes, and also tie in the associated
4119 /// operand values.
4120 /// If this returns an empty vector, and if the constraint string itself
4121 /// isn't empty, there was an error parsing.
4124  const TargetRegisterInfo *TRI,
4125  ImmutableCallSite CS) const {
4126  /// Information about all of the constraints.
4127  AsmOperandInfoVector ConstraintOperands;
4128  const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4129  unsigned maCount = 0; // Largest number of multiple alternative constraints.
4130 
4131  // Do a prepass over the constraints, canonicalizing them, and building up the
4132  // ConstraintOperands list.
4133  unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4134  unsigned ResNo = 0; // ResNo - The result number of the next output.
4135 
4136  for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
4137  ConstraintOperands.emplace_back(std::move(CI));
4138  AsmOperandInfo &OpInfo = ConstraintOperands.back();
4139 
4140  // Update multiple alternative constraint count.
4141  if (OpInfo.multipleAlternatives.size() > maCount)
4142  maCount = OpInfo.multipleAlternatives.size();
4143 
4144  OpInfo.ConstraintVT = MVT::Other;
4145 
4146  // Compute the value type for each operand.
4147  switch (OpInfo.Type) {
4148  case InlineAsm::isOutput:
4149  // Indirect outputs just consume an argument.
4150  if (OpInfo.isIndirect) {
4151  OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
4152  break;
4153  }
4154 
4155  // The return value of the call is this value. As such, there is no
4156  // corresponding argument.
4157  assert(!CS.getType()->isVoidTy() &&
4158  "Bad inline asm!");
4159  if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
4160  OpInfo.ConstraintVT =
4161  getSimpleValueType(DL, STy->getElementType(ResNo));
4162  } else {
4163  assert(ResNo == 0 && "Asm only has one result!");
4164  OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType());
4165  }
4166  ++ResNo;
4167  break;
4168  case InlineAsm::isInput:
4169  OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
4170  break;
4171  case InlineAsm::isClobber:
4172  // Nothing to do.
4173  break;
4174  }
4175 
4176  if (OpInfo.CallOperandVal) {
4177  llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
4178  if (OpInfo.isIndirect) {
4179  llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
4180  if (!PtrTy)
4181  report_fatal_error("Indirect operand for inline asm not a pointer!");
4182  OpTy = PtrTy->getElementType();
4183  }
4184 
4185  // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
4186  if (StructType *STy = dyn_cast<StructType>(OpTy))
4187  if (STy->getNumElements() == 1)
4188  OpTy = STy->getElementType(0);
4189 
4190  // If OpTy is not a single value, it may be a struct/union that we
4191  // can tile with integers.
4192  if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4193  unsigned BitSize = DL.getTypeSizeInBits(OpTy);
4194  switch (BitSize) {
4195  default: break;
4196  case 1:
4197  case 8:
4198  case 16:
4199  case 32:
4200  case 64:
4201  case 128:
4202  OpInfo.ConstraintVT =
4203  MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
4204  break;
4205  }
4206  } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
4207  unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
4208  OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
4209  } else {
4210  OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
4211  }
4212  }
4213  }
4214 
4215  // If we have multiple alternative constraints, select the best alternative.
4216  if (!ConstraintOperands.empty()) {
4217  if (maCount) {
4218  unsigned bestMAIndex = 0;
4219  int bestWeight = -1;
4220  // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
4221  int weight = -1;
4222  unsigned maIndex;
4223  // Compute the sums of the weights for each alternative, keeping track
4224  // of the best (highest weight) one so far.
4225  for (maIndex = 0; maIndex < maCount; ++maIndex) {
4226  int weightSum = 0;
4227  for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
4228  cIndex != eIndex; ++cIndex) {
4229  AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
4230  if (OpInfo.Type == InlineAsm::isClobber)
4231  continue;
4232 
4233  // If this is an output operand with a matching input operand,
4234  // look up the matching input. If their types mismatch, e.g. one
4235  // is an integer, the other is floating point, or their sizes are
4236  // different, flag it as an maCantMatch.
4237  if (OpInfo.hasMatchingInput()) {
4238  AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4239  if (OpInfo.ConstraintVT != Input.ConstraintVT) {
4240  if ((OpInfo.ConstraintVT.isInteger() !=
4241  Input.ConstraintVT.isInteger()) ||
4242  (OpInfo.ConstraintVT.getSizeInBits() !=
4243  Input.ConstraintVT.getSizeInBits())) {
4244  weightSum = -1; // Can't match.
4245  break;
4246  }
4247  }
4248  }
4249  weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
4250  if (weight == -1) {
4251  weightSum = -1;
4252  break;
4253  }
4254  weightSum += weight;
4255  }
4256  // Update best.
4257  if (weightSum > bestWeight) {
4258  bestWeight = weightSum;
4259  bestMAIndex = maIndex;
4260  }
4261  }
4262 
4263  // Now select chosen alternative in each constraint.
4264  for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
4265  cIndex != eIndex; ++cIndex) {
4266  AsmOperandInfo &cInfo = ConstraintOperands[cIndex];
4267  if (cInfo.Type == InlineAsm::isClobber)
4268  continue;
4269  cInfo.selectAlternative(bestMAIndex);
4270  }
4271  }
4272  }
4273 
4274  // Check and hook up tied operands, choose constraint code to use.
4275  for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
4276  cIndex != eIndex; ++cIndex) {
4277  AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
4278 
4279  // If this is an output operand with a matching input operand, look up the
4280  // matching input. If their types mismatch, e.g. one is an integer, the
4281  // other is floating point, or their sizes are different, flag it as an
4282  // error.
4283  if (OpInfo.hasMatchingInput()) {
4284  AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4285 
4286  if (OpInfo.ConstraintVT != Input.ConstraintVT) {
4287  std::pair<unsigned, const TargetRegisterClass *> MatchRC =
4289  OpInfo.ConstraintVT);
4290  std::pair<unsigned, const TargetRegisterClass *> InputRC =
4292  Input.ConstraintVT);
4293  if ((OpInfo.ConstraintVT.isInteger() !=
4294  Input.ConstraintVT.isInteger()) ||
4295  (MatchRC.second != InputRC.second)) {
4296  report_fatal_error("Unsupported asm: input constraint"
4297  " with a matching output constraint of"
4298  " incompatible type!");
4299  }
4300  }
4301  }
4302  }
4303 
4304  return ConstraintOperands;
4305 }
4306 
4307 /// Return an integer indicating how general CT is.
4309  switch (CT) {
4313  return 0;
4315  return 1;
4317  return 2;
4319  return 3;
4320  }
4321  llvm_unreachable("Invalid constraint type");
4322 }
4323 
4324 /// Examine constraint type and operand type and determine a weight value.
4325 /// This object must already have been set up with the operand type
4326 /// and the current alternative constraint selected.
4329  AsmOperandInfo &info, int maIndex) const {
4331  if (maIndex >= (int)info.multipleAlternatives.size())
4332  rCodes = &info.Codes;
4333  else
4334  rCodes = &info.multipleAlternatives[maIndex].Codes;
4335  ConstraintWeight BestWeight = CW_Invalid;
4336 
4337  // Loop over the options, keeping track of the most general one.
4338  for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
4339  ConstraintWeight weight =
4340  getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
4341  if (weight > BestWeight)
4342  BestWeight = weight;
4343  }
4344 
4345  return BestWeight;
4346 }
4347 
4348 /// Examine constraint type and operand type and determine a weight value.
4349 /// This object must already have been set up with the operand type
4350 /// and the current alternative constraint selected.
4353  AsmOperandInfo &info, const char *constraint) const {
4354  ConstraintWeight weight = CW_Invalid;
4355  Value *CallOperandVal = info.CallOperandVal;
4356  // If we don't have a value, we can't do a match,
4357  // but allow it at the lowest weight.
4358  if (!CallOperandVal)
4359  return CW_Default;
4360  // Look at the constraint type.
4361  switch (*constraint) {
4362  case 'i': // immediate integer.
4363  case 'n': // immediate integer with a known value.
4364  if (isa<ConstantInt>(CallOperandVal))
4365  weight = CW_Constant;
4366  break;
4367  case 's': // non-explicit intregal immediate.
4368  if (isa<GlobalValue>(CallOperandVal))
4369  weight = CW_Constant;
4370  break;
4371  case 'E': // immediate float if host format.
4372  case 'F': // immediate float.
4373  if (isa<ConstantFP>(CallOperandVal))
4374  weight = CW_Constant;
4375  break;
4376  case '<': // memory operand with autodecrement.
4377  case '>': // memory operand with autoincrement.
4378  case 'm': // memory operand.
4379  case 'o': // offsettable memory operand
4380  case 'V': // non-offsettable memory operand
4381  weight = CW_Memory;
4382  break;
4383  case 'r': // general register.
4384  case 'g': // general register, memory operand or immediate integer.
4385  // note: Clang converts "g" to "imr".
4386  if (CallOperandVal->getType()->isIntegerTy())
4387  weight = CW_Register;
4388  break;
4389  case 'X': // any operand.
4390  default:
4391  weight = CW_Default;
4392  break;
4393  }
4394  return weight;
4395 }
4396 
4397 /// If there are multiple different constraints that we could pick for this
4398 /// operand (e.g. "imr") try to pick the 'best' one.
4399 /// This is somewhat tricky: constraints fall into four classes:
4400 /// Other -> immediates and magic values
4401 /// Register -> one specific register
4402 /// RegisterClass -> a group of regs
4403 /// Memory -> memory
4404 /// Ideally, we would pick the most specific constraint possible: if we have
4405 /// something that fits into a register, we would pick it. The problem here
4406 /// is that if we have something that could either be in a register or in
4407 /// memory that use of the register could cause selection of *other*
4408 /// operands to fail: they might only succeed if we pick memory. Because of
4409 /// this the heuristic we use is:
4410 ///
4411 /// 1) If there is an 'other' constraint, and if the operand is valid for
4412 /// that constraint, use it. This makes us take advantage of 'i'
4413 /// constraints when available.
4414 /// 2) Otherwise, pick the most general constraint present. This prefers
4415 /// 'm' over 'r', for example.
4416 ///
4418  const TargetLowering &TLI,
4419  SDValue Op, SelectionDAG *DAG) {
4420  assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
4421  unsigned BestIdx = 0;
4423  int BestGenerality = -1;
4424 
4425  // Loop over the options, keeping track of the most general one.
4426  for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
4428  TLI.getConstraintType(OpInfo.Codes[i]);
4429 
4430  // If this is an 'other' or 'immediate' constraint, see if the operand is
4431  // valid for it. For example, on X86 we might have an 'rI' constraint. If
4432  // the operand is an integer in the range [0..31] we want to use I (saving a
4433  // load of a register), otherwise we must use 'r'.
4434  if ((CType == TargetLowering::C_Other ||
4435  CType == TargetLowering::C_Immediate) && Op.getNode()) {
4436  assert(OpInfo.Codes[i].size() == 1 &&
4437  "Unhandled multi-letter 'other' constraint");
4438  std::vector<SDValue> ResultOps;
4439  TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
4440  ResultOps, *DAG);
4441  if (!ResultOps.empty()) {
4442  BestType = CType;
4443  BestIdx = i;
4444  break;
4445  }
4446  }
4447 
4448  // Things with matching constraints can only be registers, per gcc
4449  // documentation. This mainly affects "g" constraints.
4450  if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
4451  continue;
4452 
4453  // This constraint letter is more general than the previous one, use it.
4454  int Generality = getConstraintGenerality(CType);
4455  if (Generality > BestGenerality) {
4456  BestType = CType;
4457  BestIdx = i;
4458  BestGenerality = Generality;
4459  }
4460  }
4461 
4462  OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
4463  OpInfo.ConstraintType = BestType;
4464 }
4465 
4466 /// Determines the constraint code and constraint type to use for the specific
4467 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
4469  SDValue Op,
4470  SelectionDAG *DAG) const {
4471  assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
4472 
4473  // Single-letter constraints ('r') are very common.
4474  if (OpInfo.Codes.size() == 1) {
4475  OpInfo.ConstraintCode = OpInfo.Codes[0];
4477  } else {
4478  ChooseConstraint(OpInfo, *this, Op, DAG);
4479  }
4480 
4481  // 'X' matches anything.
4482  if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
4483  // Labels and constants are handled elsewhere ('X' is the only thing
4484  // that matches labels). For Functions, the type here is the type of
4485  // the result, which is not what we want to look at; leave them alone.
4486  Value *v = OpInfo.CallOperandVal;
4487  if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
4488  OpInfo.CallOperandVal = v;
4489  return;
4490  }
4491 
4492  if (Op.getNode() && Op.getOpcode() == ISD::TargetBlockAddress)
4493  return;
4494 
4495  // Otherwise, try to resolve it to something we know about by looking at
4496  // the actual operand type.
4497  if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
4498  OpInfo.ConstraintCode = Repl;
4500  }
4501  }
4502 }
4503 
4504 /// Given an exact SDIV by a constant, create a multiplication
4505 /// with the multiplicative inverse of the constant.
4507  const SDLoc &dl, SelectionDAG &DAG,
4508  SmallVectorImpl<SDNode *> &Created) {
4509  SDValue Op0 = N->getOperand(0);
4510  SDValue Op1 = N->getOperand(1);
4511  EVT VT = N->getValueType(0);
4512  EVT SVT = VT.getScalarType();
4513  EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
4514  EVT ShSVT = ShVT.getScalarType();
4515 
4516  bool UseSRA = false;
4517  SmallVector<SDValue, 16> Shifts, Factors;
4518 
4519  auto BuildSDIVPattern = [&](ConstantSDNode *C) {
4520  if (C->isNullValue())
4521  return false;
4522  APInt Divisor = C->getAPIntValue();
4523  unsigned Shift = Divisor.countTrailingZeros();
4524  if (Shift) {
4525  Divisor.ashrInPlace(Shift);
4526  UseSRA = true;
4527  }
4528  // Calculate the multiplicative inverse, using Newton's method.
4529  APInt t;
4530  APInt Factor = Divisor;
4531  while ((t = Divisor * Factor) != 1)
4532  Factor *= APInt(Divisor.getBitWidth(), 2) - t;
4533  Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
4534  Factors.push_back(DAG.getConstant(Factor, dl, SVT));
4535  return true;
4536  };
4537 
4538  // Collect all magic values from the build vector.
4539  if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
4540  return SDValue();
4541 
4542  SDValue Shift, Factor;
4543  if (VT.isVector()) {
4544  Shift = DAG.getBuildVector(ShVT, dl, Shifts);
4545  Factor = DAG.getBuildVector(VT, dl, Factors);
4546  } else {
4547  Shift = Shifts[0];
4548  Factor = Factors[0];
4549  }
4550 
4551  SDValue Res = Op0;
4552 
4553  // Shift the value upfront if it is even, so the LSB is one.
4554  if (UseSRA) {
4555  // TODO: For UDIV use SRL instead of SRA.
4556  SDNodeFlags Flags;
4557  Flags.setExact(true);
4558  Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags);
4559  Created.push_back(Res.getNode());
4560  }
4561 
4562  return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
4563 }
4564 
4566  SelectionDAG &DAG,
4567  SmallVectorImpl<SDNode *> &Created) const {
4569  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4570  if (TLI.isIntDivCheap(N->getValueType(0), Attr))
4571  return SDValue(N, 0); // Lower SDIV as SDIV
4572  return SDValue();
4573 }
4574 
4575 /// Given an ISD::SDIV node expressing a divide by constant,
4576 /// return a DAG expression to select that will generate the same value by
4577 /// multiplying by a magic number.
4578 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
4580  bool IsAfterLegalization,
4581  SmallVectorImpl<SDNode *> &Created) const {
4582  SDLoc dl(N);
4583  EVT VT = N->getValueType(0);
4584  EVT SVT = VT.getScalarType();
4585  EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
4586  EVT ShSVT = ShVT.getScalarType();
4587  unsigned EltBits = VT.getScalarSizeInBits();
4588 
4589  // Check to see if we can do this.
4590  // FIXME: We should be more aggressive here.
4591  if (!isTypeLegal(VT))
4592  return SDValue();
4593 
4594  // If the sdiv has an 'exact' bit we can use a simpler lowering.
4595  if (N->getFlags().hasExact())
4596  return BuildExactSDIV(*this, N, dl, DAG, Created);
4597 
4598  SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
4599 
4600  auto BuildSDIVPattern = [&](ConstantSDNode *C) {
4601  if (C->isNullValue())
4602  return false;
4603 
4604  const APInt &Divisor = C->getAPIntValue();
4605  APInt::ms magics = Divisor.magic();
4606  int NumeratorFactor = 0;
4607  int ShiftMask = -1;
4608 
4609  if (Divisor.isOneValue() || Divisor.isAllOnesValue()) {
4610  // If d is +1/-1, we just multiply the numerator by +1/-1.
4611  NumeratorFactor = Divisor.getSExtValue();
4612  magics.m = 0;
4613  magics.s = 0;
4614  ShiftMask = 0;
4615  } else if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
4616  // If d > 0 and m < 0, add the numerator.
4617  NumeratorFactor = 1;
4618  } else if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
4619  // If d < 0 and m > 0, subtract the numerator.
4620  NumeratorFactor = -1;
4621  }
4622 
4623  MagicFactors.push_back(DAG.getConstant(magics.m, dl, SVT));
4624  Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT));
4625  Shifts.push_back(DAG.getConstant(magics.s, dl, ShSVT));
4626  ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT));
4627  return true;
4628  };
4629 
4630  SDValue N0 = N->getOperand(0);
4631  SDValue N1 = N->getOperand(1);
4632 
4633  // Collect the shifts / magic values from each element.
4634  if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern))
4635  return SDValue();
4636 
4637  SDValue MagicFactor, Factor, Shift, ShiftMask;
4638  if (VT.isVector()) {
4639  MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
4640  Factor = DAG.getBuildVector(VT, dl, Factors);
4641  Shift = DAG.getBuildVector(ShVT, dl, Shifts);
4642  ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
4643  } else {
4644  MagicFactor = MagicFactors[0];
4645  Factor = Factors[0];
4646  Shift = Shifts[0];
4647  ShiftMask = ShiftMasks[0];
4648  }
4649 
4650  // Multiply the numerator (operand 0) by the magic value.
4651  // FIXME: We should support doing a MUL in a wider type.
4652  SDValue Q;
4653  if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT)
4655  Q = DAG.getNode(ISD::MULHS, dl, VT, N0, MagicFactor);
4656  else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT)
4658  SDValue LoHi =
4659  DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), N0, MagicFactor);
4660  Q = SDValue(LoHi.getNode(), 1);
4661  } else
4662  return SDValue(); // No mulhs or equivalent.
4663  Created.push_back(Q.getNode());
4664 
4665  // (Optionally) Add/subtract the numerator using Factor.
4666  Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
4667  Created.push_back(Factor.getNode());
4668  Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
4669  Created.push_back(Q.getNode());
4670 
4671  // Shift right algebraic by shift value.
4672  Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
4673  Created.push_back(Q.getNode());
4674 
4675  // Extract the sign bit, mask it and add it to the quotient.
4676  SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
4677  SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
4678  Created.push_back(T.getNode());
4679  T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
4680  Created.push_back(T.getNode());
4681  return DAG.getNode(ISD::ADD, dl, VT, Q, T);
4682 }
4683 
4684 /// Given an ISD::UDIV node expressing a divide by constant,
4685 /// return a DAG expression to select that will generate the same value by
4686 /// multiplying by a magic number.
4687 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
4689  bool IsAfterLegalization,
4690  SmallVectorImpl<SDNode *> &Created) const {
4691  SDLoc dl(N);
4692  EVT VT = N->getValueType(0);
4693  EVT SVT = VT.getScalarType();
4694  EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
4695  EVT ShSVT = ShVT.getScalarType();
4696  unsigned EltBits = VT.getScalarSizeInBits();
4697 
4698  // Check to see if we can do this.
4699  // FIXME: We should be more aggressive here.
4700  if (!isTypeLegal(VT))
4701  return SDValue();
4702 
4703  bool UseNPQ = false;
4704  SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
4705 
4706  auto BuildUDIVPattern = [&](ConstantSDNode *C) {
4707  if (C->isNullValue())
4708  return false;
4709  // FIXME: We should use a narrower constant when the upper
4710  // bits are known to be zero.
4711  APInt Divisor = C->getAPIntValue();
4712  APInt::mu magics = Divisor.magicu();
4713  unsigned PreShift = 0, PostShift = 0;
4714 
4715  // If the divisor is even, we can avoid using the expensive fixup by
4716  // shifting the divided value upfront.
4717  if (magics.a != 0 && !Divisor[0]) {
4718  PreShift = Divisor.countTrailingZeros();
4719  // Get magic number for the shifted divisor.
4720  magics = Divisor.lshr(PreShift).magicu(PreShift);
4721  assert(magics.a == 0 && "Should use cheap fixup now");
4722  }
4723 
4724  APInt Magic = magics.m;
4725 
4726  unsigned SelNPQ;
4727  if (magics.a == 0 || Divisor.isOneValue()) {
4728  assert(magics.s < Divisor.getBitWidth() &&
4729  "We shouldn't generate an undefined shift!");
4730  PostShift = magics.s;
4731  SelNPQ = false;
4732  } else {
4733  PostShift = magics.s - 1;
4734  SelNPQ = true;
4735  }
4736 
4737  PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT));
4738  MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT));
4739  NPQFactors.push_back(
4740  DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1)
4741  : APInt::getNullValue(EltBits),
4742  dl, SVT));
4743  PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT));
4744  UseNPQ |= SelNPQ;
4745  return true;
4746  };
4747 
4748  SDValue N0 = N->getOperand(0);
4749  SDValue N1 = N->getOperand(1);
4750 
4751  // Collect the shifts/magic values from each element.
4752  if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern))
4753  return SDValue();
4754 
4755  SDValue PreShift, PostShift, MagicFactor, NPQFactor;
4756  if (VT.isVector()) {
4757  PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
4758  MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
4759  NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
4760  PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
4761  } else {
4762  PreShift = PreShifts[0];
4763  MagicFactor = MagicFactors[0];
4764  PostShift = PostShifts[0];
4765  }
4766 
4767  SDValue Q = N0;
4768  Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
4769  Created.push_back(Q.getNode());
4770 
4771  // FIXME: We should support doing a MUL in a wider type.
4772  auto GetMULHU = [&](SDValue X, SDValue Y) {
4773  if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT)
4775  return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
4776  if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT)
4778  SDValue LoHi =
4779  DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
4780  return SDValue(LoHi.getNode(), 1);
4781  }
4782  return SDValue(); // No mulhu or equivalent
4783  };
4784 
4785  // Multiply the numerator (operand 0) by the magic value.
4786  Q = GetMULHU(Q, MagicFactor);
4787  if (!Q)
4788  return SDValue();
4789 
4790  Created.push_back(Q.getNode());
4791 
4792  if (UseNPQ) {
4793  SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
4794  Created.push_back(NPQ.getNode());
4795 
4796  // For vectors we might have a mix of non-NPQ/NPQ paths, so use
4797  // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
4798  if (VT.isVector())
4799  NPQ = GetMULHU(NPQ, NPQFactor);
4800  else
4801  NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
4802 
4803  Created.push_back(NPQ.getNode());
4804 
4805  Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
4806  Created.push_back(Q.getNode());
4807  }
4808 
4809  Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
4810  Created.push_back(Q.getNode());
4811 
4812  SDValue One = DAG.getConstant(1, dl, VT);
4813  SDValue IsOne = DAG.getSetCC(dl, VT, N1, One, ISD::SETEQ);
4814  return DAG.getSelect(dl, VT, IsOne, N0, Q);
4815 }
4816 
4817 /// If all values in Values that *don't* match the predicate are same 'splat'
4818 /// value, then replace all values with that splat value.
4819 /// Else, if AlternativeReplacement was provided, then replace all values that
4820 /// do match predicate with AlternativeReplacement value.
4821 static void
4824  SDValue AlternativeReplacement = SDValue()) {
4825  SDValue Replacement;
4826  // Is there a value for which the Predicate does *NOT* match? What is it?
4827  auto SplatValue = llvm::find_if_not(Values, Predicate);
4828  if (SplatValue != Values.end()) {
4829  // Does Values consist only of SplatValue's and values matching Predicate?
4830  if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
4831  return Value == *SplatValue || Predicate(Value);
4832  })) // Then we shall replace values matching predicate with SplatValue.
4833  Replacement = *SplatValue;
4834  }
4835  if (!Replacement) {
4836  // Oops, we did not find the "baseline" splat value.
4837  if (!AlternativeReplacement)
4838  return; // Nothing to do.
4839  // Let's replace with provided value then.
4840  Replacement = AlternativeReplacement;
4841  }
4842  std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
4843 }
4844 
4845 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
4846 /// where the divisor is constant and the comparison target is zero,
4847 /// return a DAG expression that will generate the same comparison result
4848 /// using only multiplications, additions and shifts/rotations.
4849 /// Ref: "Hacker's Delight" 10-17.
4850 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
4851  SDValue CompTargetNode,
4852  ISD::CondCode Cond,
4853  DAGCombinerInfo &DCI,
4854  const SDLoc &DL) const {
4856  if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
4857  DCI, DL, Built)) {
4858  for (SDNode *N : Built)
4859  DCI.AddToWorklist(N);
4860  return Folded;
4861  }
4862 
4863  return SDValue();
4864 }
4865 
4866 SDValue
4867 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
4868  SDValue CompTargetNode, ISD::CondCode Cond,
4869  DAGCombinerInfo &DCI, const SDLoc &DL,
4870  SmallVectorImpl<SDNode *> &Created) const {
4871  // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q)
4872  // - D must be constant, with D = D0 * 2^K where D0 is odd
4873  // - P is the multiplicative inverse of D0 modulo 2^W
4874  // - Q = floor(((2^W) - 1) / D)
4875  // where W is the width of the common type of N and D.
4876  assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4877  "Only applicable for (in)equality comparisons.");
4878 
4879  SelectionDAG &DAG = DCI.DAG;
4880 
4881  EVT VT = REMNode.getValueType();
4882  EVT SVT = VT.getScalarType();
4883  EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
4884  EVT ShSVT = ShVT.getScalarType();
4885 
4886  // If MUL is unavailable, we cannot proceed in any case.
4888  return SDValue();
4889 
4890  // TODO: Could support comparing with non-zero too.
4891  ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
4892  if (!CompTarget || !CompTarget->isNullValue())
4893  return SDValue();
4894 
4895  bool HadOneDivisor = false;
4896  bool AllDivisorsAreOnes = true;
4897  bool HadEvenDivisor = false;
4898  bool AllDivisorsArePowerOfTwo = true;
4899  SmallVector<SDValue, 16> PAmts, KAmts, QAmts;
4900 
4901  auto BuildUREMPattern = [&](ConstantSDNode *C) {
4902  // Division by 0 is UB. Leave it to be constant-folded elsewhere.
4903  if (C->isNullValue())
4904  return false;
4905 
4906  const APInt &D = C->getAPIntValue();
4907  // If all divisors are ones, we will prefer to avoid the fold.
4908  HadOneDivisor |= D.isOneValue();
4909  AllDivisorsAreOnes &= D.isOneValue();
4910 
4911  // Decompose D into D0 * 2^K
4912  unsigned K = D.countTrailingZeros();
4913  assert((!D.isOneValue() || (K == 0)) && "For divisor '1' we won't rotate.");
4914  APInt D0 = D.lshr(K);
4915 
4916  // D is even if it has trailing zeros.
4917  HadEvenDivisor |= (K != 0);
4918  // D is a power-of-two if D0 is one.
4919  // If all divisors are power-of-two, we will prefer to avoid the fold.
4920  AllDivisorsArePowerOfTwo &= D0.isOneValue();
4921 
4922  // P = inv(D0, 2^W)
4923  // 2^W requires W + 1 bits, so we have to extend and then truncate.
4924  unsigned W = D.getBitWidth();
4925  APInt P = D0.zext(W + 1)
4926  .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
4927  .trunc(W);
4928  assert(!P.isNullValue() && "No multiplicative inverse!"); // unreachable
4929  assert((D0 * P).isOneValue() && "Multiplicative inverse sanity check.");
4930 
4931  // Q = floor((2^W - 1) / D)
4932  APInt Q = APInt::getAllOnesValue(W).udiv(D);
4933 
4934  assert(APInt::getAllOnesValue(ShSVT.getSizeInBits()).ugt(K) &&
4935  "We are expecting that K is always less than all-ones for ShSVT");
4936 
4937  // If the divisor is 1 the result can be constant-folded.
4938  if (D.isOneValue()) {
4939  // Set P and K amount to a bogus values so we can try to splat them.
4940  P = 0;
4941  K = -1;
4942  assert(Q.isAllOnesValue() &&
4943  "Expecting all-ones comparison for one divisor");
4944  }
4945 
4946  PAmts.push_back(DAG.getConstant(P, DL, SVT));
4947  KAmts.push_back(
4948  DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
4949  QAmts.push_back(DAG.getConstant(Q, DL, SVT));
4950  return true;
4951  };
4952 
4953  SDValue N = REMNode.getOperand(0);
4954  SDValue D = REMNode.getOperand(1);
4955 
4956  // Collect the values from each element.
4957  if (!ISD::matchUnaryPredicate(D, BuildUREMPattern))
4958  return SDValue();
4959 
4960  // If this is a urem by a one, avoid the fold since it can be constant-folded.
4961  if (AllDivisorsAreOnes)
4962  return SDValue();
4963 
4964  // If this is a urem by a powers-of-two, avoid the fold since it can be
4965  // best implemented as a bit test.
4966  if (AllDivisorsArePowerOfTwo)
4967  return SDValue();
4968 
4969  SDValue PVal, KVal, QVal;
4970  if (VT.isVector()) {
4971  if (HadOneDivisor) {
4972  // Try to turn PAmts into a splat, since we don't care about the values
4973  // that are currently '0'. If we can't, just keep '0'`s.
4975  // Try to turn KAmts into a splat, since we don't care about the values
4976  // that are currently '-1'. If we can't, change them to '0'`s.
4978  DAG.getConstant(0, DL, ShSVT));
4979  }
4980 
4981  PVal = DAG.getBuildVector(VT, DL, PAmts);
4982  KVal = DAG.getBuildVector(ShVT, DL, KAmts);
4983  QVal = DAG.getBuildVector(VT, DL, QAmts);
4984  } else {
4985  PVal = PAmts[0];
4986  KVal = KAmts[0];
4987  QVal = QAmts[0];
4988  }
4989 
4990