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