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 
13 #include "llvm/CodeGen/TargetLowering.h"
14 #include "llvm/ADT/BitVector.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/CodeGen/CallingConvLower.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineJumpTableInfo.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/CodeGen/TargetRegisterInfo.h"
23 #include "llvm/CodeGen/TargetSubtargetInfo.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"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/KnownBits.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Target/TargetLoweringObjectFile.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include <cctype>
36 using namespace llvm;
37 
38 /// NOTE: The TargetMachine owns TLOF.
39 TargetLowering::TargetLowering(const TargetMachine &tm)
40   : TargetLoweringBase(tm) {}
41 
42 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
43   return nullptr;
44 }
45 
46 bool TargetLowering::isPositionIndependent() const {
47   return getTargetMachine().isPositionIndependent();
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.
52 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
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 
75 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI,
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.
102 void TargetLoweringBase::ArgListEntry::setAttributes(const CallBase *Call,
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 }
116 
117 /// Generate a libcall taking the given operands as arguments and returning a
118 /// result of type RetVT.
119 std::pair<SDValue, SDValue>
120 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
121                             ArrayRef<SDValue> Ops, bool isSigned,
122                             const SDLoc &dl, bool doesNotReturn,
123                             bool isReturnValueUsed,
124                             bool isPostTypeLegalization) const {
125   TargetLowering::ArgListTy Args;
126   Args.reserve(Ops.size());
127 
128   TargetLowering::ArgListEntry Entry;
129   for (SDValue Op : Ops) {
130     Entry.Node = Op;
131     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
132     Entry.IsSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
133     Entry.IsZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
134     Args.push_back(Entry);
135   }
136 
137   if (LC == RTLIB::UNKNOWN_LIBCALL)
138     report_fatal_error("Unsupported library call operation!");
139   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
140                                          getPointerTy(DAG.getDataLayout()));
141 
142   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
143   TargetLowering::CallLoweringInfo CLI(DAG);
144   bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned);
145   CLI.setDebugLoc(dl)
146       .setChain(DAG.getEntryNode())
147       .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
148       .setNoReturn(doesNotReturn)
149       .setDiscardResult(!isReturnValueUsed)
150       .setIsPostTypeLegalization(isPostTypeLegalization)
151       .setSExtResult(signExtend)
152       .setZExtResult(!signExtend);
153   return LowerCallTo(CLI);
154 }
155 
156 /// Soften the operands of a comparison. This code is shared among BR_CC,
157 /// SELECT_CC, and SETCC handlers.
158 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
159                                          SDValue &NewLHS, SDValue &NewRHS,
160                                          ISD::CondCode &CCCode,
161                                          const SDLoc &dl) const {
162   assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
163          && "Unsupported setcc type!");
164 
165   // Expand into one or more soft-fp libcall(s).
166   RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
167   bool ShouldInvertCC = false;
168   switch (CCCode) {
169   case ISD::SETEQ:
170   case ISD::SETOEQ:
171     LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
172           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
173           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
174     break;
175   case ISD::SETNE:
176   case ISD::SETUNE:
177     LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
178           (VT == MVT::f64) ? RTLIB::UNE_F64 :
179           (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
180     break;
181   case ISD::SETGE:
182   case ISD::SETOGE:
183     LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
184           (VT == MVT::f64) ? RTLIB::OGE_F64 :
185           (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
186     break;
187   case ISD::SETLT:
188   case ISD::SETOLT:
189     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
190           (VT == MVT::f64) ? RTLIB::OLT_F64 :
191           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
192     break;
193   case ISD::SETLE:
194   case ISD::SETOLE:
195     LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
196           (VT == MVT::f64) ? RTLIB::OLE_F64 :
197           (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
198     break;
199   case ISD::SETGT:
200   case ISD::SETOGT:
201     LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
202           (VT == MVT::f64) ? RTLIB::OGT_F64 :
203           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
204     break;
205   case ISD::SETUO:
206     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
207           (VT == MVT::f64) ? RTLIB::UO_F64 :
208           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
209     break;
210   case ISD::SETO:
211     LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
212           (VT == MVT::f64) ? RTLIB::O_F64 :
213           (VT == MVT::f128) ? RTLIB::O_F128 : RTLIB::O_PPCF128;
214     break;
215   case ISD::SETONE:
216     // SETONE = SETOLT | SETOGT
217     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
218           (VT == MVT::f64) ? RTLIB::OLT_F64 :
219           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
220     LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
221           (VT == MVT::f64) ? RTLIB::OGT_F64 :
222           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
223     break;
224   case ISD::SETUEQ:
225     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
226           (VT == MVT::f64) ? RTLIB::UO_F64 :
227           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
228     LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
229           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
230           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
231     break;
232   default:
233     // Invert CC for unordered comparisons
234     ShouldInvertCC = true;
235     switch (CCCode) {
236     case ISD::SETULT:
237       LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
238             (VT == MVT::f64) ? RTLIB::OGE_F64 :
239             (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
240       break;
241     case ISD::SETULE:
242       LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
243             (VT == MVT::f64) ? RTLIB::OGT_F64 :
244             (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
245       break;
246     case ISD::SETUGT:
247       LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
248             (VT == MVT::f64) ? RTLIB::OLE_F64 :
249             (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
250       break;
251     case ISD::SETUGE:
252       LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
253             (VT == MVT::f64) ? RTLIB::OLT_F64 :
254             (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
255       break;
256     default: llvm_unreachable("Do not know how to soften this setcc!");
257     }
258   }
259 
260   // Use the target specific return value for comparions lib calls.
261   EVT RetVT = getCmpLibcallReturnType();
262   SDValue Ops[2] = {NewLHS, NewRHS};
263   NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, false /*sign irrelevant*/,
264                        dl).first;
265   NewRHS = DAG.getConstant(0, dl, RetVT);
266 
267   CCCode = getCmpLibcallCC(LC1);
268   if (ShouldInvertCC)
269     CCCode = getSetCCInverse(CCCode, /*isInteger=*/true);
270 
271   if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
272     SDValue Tmp = DAG.getNode(
273         ISD::SETCC, dl,
274         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
275         NewLHS, NewRHS, DAG.getCondCode(CCCode));
276     NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, false/*sign irrelevant*/,
277                          dl).first;
278     NewLHS = DAG.getNode(
279         ISD::SETCC, dl,
280         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
281         NewLHS, NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
282     NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
283     NewRHS = SDValue();
284   }
285 }
286 
287 /// Return the entry encoding for a jump table in the current function. The
288 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
289 unsigned TargetLowering::getJumpTableEncoding() const {
290   // In non-pic modes, just use the address of a block.
291   if (!isPositionIndependent())
292     return MachineJumpTableInfo::EK_BlockAddress;
293 
294   // In PIC mode, if the target supports a GPRel32 directive, use it.
295   if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
296     return MachineJumpTableInfo::EK_GPRel32BlockAddress;
297 
298   // Otherwise, use a label difference.
299   return MachineJumpTableInfo::EK_LabelDifference32;
300 }
301 
302 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
303                                                  SelectionDAG &DAG) const {
304   // If our PIC model is GP relative, use the global offset table as the base.
305   unsigned JTEncoding = getJumpTableEncoding();
306 
307   if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
308       (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
309     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
310 
311   return Table;
312 }
313 
314 /// This returns the relocation base for the given PIC jumptable, the same as
315 /// getPICJumpTableRelocBase, but as an MCExpr.
316 const MCExpr *
317 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
318                                              unsigned JTI,MCContext &Ctx) const{
319   // The normal PIC reloc base is the label at the start of the jump table.
320   return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
321 }
322 
323 bool
324 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
325   const TargetMachine &TM = getTargetMachine();
326   const GlobalValue *GV = GA->getGlobal();
327 
328   // If the address is not even local to this DSO we will have to load it from
329   // a got and then add the offset.
330   if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
331     return false;
332 
333   // If the code is position independent we will have to add a base register.
334   if (isPositionIndependent())
335     return false;
336 
337   // Otherwise we can do it.
338   return true;
339 }
340 
341 //===----------------------------------------------------------------------===//
342 //  Optimization Methods
343 //===----------------------------------------------------------------------===//
344 
345 /// If the specified instruction has a constant integer operand and there are
346 /// bits set in that constant that are not demanded, then clear those bits and
347 /// return true.
348 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
349                                             TargetLoweringOpt &TLO) const {
350   SelectionDAG &DAG = TLO.DAG;
351   SDLoc DL(Op);
352   unsigned Opcode = Op.getOpcode();
353 
354   // Do target-specific constant optimization.
355   if (targetShrinkDemandedConstant(Op, Demanded, TLO))
356     return TLO.New.getNode();
357 
358   // FIXME: ISD::SELECT, ISD::SELECT_CC
359   switch (Opcode) {
360   default:
361     break;
362   case ISD::XOR:
363   case ISD::AND:
364   case ISD::OR: {
365     auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
366     if (!Op1C)
367       return false;
368 
369     // If this is a 'not' op, don't touch it because that's a canonical form.
370     const APInt &C = Op1C->getAPIntValue();
371     if (Opcode == ISD::XOR && Demanded.isSubsetOf(C))
372       return false;
373 
374     if (!C.isSubsetOf(Demanded)) {
375       EVT VT = Op.getValueType();
376       SDValue NewC = DAG.getConstant(Demanded & C, DL, VT);
377       SDValue NewOp = DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC);
378       return TLO.CombineTo(Op, NewOp);
379     }
380 
381     break;
382   }
383   }
384 
385   return false;
386 }
387 
388 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
389 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
390 /// generalized for targets with other types of implicit widening casts.
391 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth,
392                                       const APInt &Demanded,
393                                       TargetLoweringOpt &TLO) const {
394   assert(Op.getNumOperands() == 2 &&
395          "ShrinkDemandedOp only supports binary operators!");
396   assert(Op.getNode()->getNumValues() == 1 &&
397          "ShrinkDemandedOp only supports nodes with one result!");
398 
399   SelectionDAG &DAG = TLO.DAG;
400   SDLoc dl(Op);
401 
402   // Early return, as this function cannot handle vector types.
403   if (Op.getValueType().isVector())
404     return false;
405 
406   // Don't do this if the node has another user, which may require the
407   // full value.
408   if (!Op.getNode()->hasOneUse())
409     return false;
410 
411   // Search for the smallest integer type with free casts to and from
412   // Op's type. For expedience, just check power-of-2 integer types.
413   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
414   unsigned DemandedSize = Demanded.getActiveBits();
415   unsigned SmallVTBits = DemandedSize;
416   if (!isPowerOf2_32(SmallVTBits))
417     SmallVTBits = NextPowerOf2(SmallVTBits);
418   for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
419     EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
420     if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
421         TLI.isZExtFree(SmallVT, Op.getValueType())) {
422       // We found a type with free casts.
423       SDValue X = DAG.getNode(
424           Op.getOpcode(), dl, SmallVT,
425           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
426           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)));
427       assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?");
428       SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), X);
429       return TLO.CombineTo(Op, Z);
430     }
431   }
432   return false;
433 }
434 
435 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
436                                           DAGCombinerInfo &DCI) const {
437   SelectionDAG &DAG = DCI.DAG;
438   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
439                         !DCI.isBeforeLegalizeOps());
440   KnownBits Known;
441 
442   bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO);
443   if (Simplified) {
444     DCI.AddToWorklist(Op.getNode());
445     DCI.CommitTargetLoweringOpt(TLO);
446   }
447   return Simplified;
448 }
449 
450 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
451                                           KnownBits &Known,
452                                           TargetLoweringOpt &TLO,
453                                           unsigned Depth,
454                                           bool AssumeSingleUse) const {
455   EVT VT = Op.getValueType();
456   APInt DemandedElts = VT.isVector()
457                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
458                            : APInt(1, 1);
459   return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth,
460                               AssumeSingleUse);
461 }
462 
463 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the
464 /// result of Op are ever used downstream. If we can use this information to
465 /// simplify Op, create a new simplified DAG node and return true, returning the
466 /// original and new nodes in Old and New. Otherwise, analyze the expression and
467 /// return a mask of Known bits for the expression (used to simplify the
468 /// caller).  The Known bits may only be accurate for those bits in the
469 /// OriginalDemandedBits and OriginalDemandedElts.
470 bool TargetLowering::SimplifyDemandedBits(
471     SDValue Op, const APInt &OriginalDemandedBits,
472     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
473     unsigned Depth, bool AssumeSingleUse) const {
474   unsigned BitWidth = OriginalDemandedBits.getBitWidth();
475   assert(Op.getScalarValueSizeInBits() == BitWidth &&
476          "Mask size mismatches value type size!");
477 
478   unsigned NumElts = OriginalDemandedElts.getBitWidth();
479   assert((!Op.getValueType().isVector() ||
480           NumElts == Op.getValueType().getVectorNumElements()) &&
481          "Unexpected vector size");
482 
483   APInt DemandedBits = OriginalDemandedBits;
484   APInt DemandedElts = OriginalDemandedElts;
485   SDLoc dl(Op);
486   auto &DL = TLO.DAG.getDataLayout();
487 
488   // Don't know anything.
489   Known = KnownBits(BitWidth);
490 
491   if (Op.getOpcode() == ISD::Constant) {
492     // We know all of the bits for a constant!
493     Known.One = cast<ConstantSDNode>(Op)->getAPIntValue();
494     Known.Zero = ~Known.One;
495     return false;
496   }
497 
498   // Other users may use these bits.
499   EVT VT = Op.getValueType();
500   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) {
501     if (Depth != 0) {
502       // If not at the root, Just compute the Known bits to
503       // simplify things downstream.
504       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
505       return false;
506     }
507     // If this is the root being simplified, allow it to have multiple uses,
508     // just set the DemandedBits/Elts to all bits.
509     DemandedBits = APInt::getAllOnesValue(BitWidth);
510     DemandedElts = APInt::getAllOnesValue(NumElts);
511   } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) {
512     // Not demanding any bits/elts from Op.
513     if (!Op.isUndef())
514       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
515     return false;
516   } else if (Depth == 6) { // Limit search depth.
517     return false;
518   }
519 
520   KnownBits Known2, KnownOut;
521   switch (Op.getOpcode()) {
522   case ISD::SCALAR_TO_VECTOR: {
523     if (!DemandedElts[0])
524       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
525 
526     KnownBits SrcKnown;
527     SDValue Src = Op.getOperand(0);
528     unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
529     APInt SrcDemandedBits = DemandedBits.zextOrSelf(SrcBitWidth);
530     if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1))
531       return true;
532     Known = SrcKnown.zextOrTrunc(BitWidth, false);
533     break;
534   }
535   case ISD::BUILD_VECTOR:
536     // Collect the known bits that are shared by every constant vector element.
537     Known.Zero.setAllBits(); Known.One.setAllBits();
538     for (SDValue SrcOp : Op->ops()) {
539       if (!isa<ConstantSDNode>(SrcOp)) {
540         // We can only handle all constant values - bail out with no known bits.
541         Known = KnownBits(BitWidth);
542         return false;
543       }
544       Known2.One = cast<ConstantSDNode>(SrcOp)->getAPIntValue();
545       Known2.Zero = ~Known2.One;
546 
547       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
548       if (Known2.One.getBitWidth() != BitWidth) {
549         assert(Known2.getBitWidth() > BitWidth &&
550                "Expected BUILD_VECTOR implicit truncation");
551         Known2 = Known2.trunc(BitWidth);
552       }
553 
554       // Known bits are the values that are shared by every element.
555       // TODO: support per-element known bits.
556       Known.One &= Known2.One;
557       Known.Zero &= Known2.Zero;
558     }
559     return false; // Don't fall through, will infinitely loop.
560   case ISD::INSERT_VECTOR_ELT: {
561     SDValue Vec = Op.getOperand(0);
562     SDValue Scl = Op.getOperand(1);
563     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
564     EVT VecVT = Vec.getValueType();
565 
566     // If index isn't constant, assume we need all vector elements AND the
567     // inserted element.
568     APInt DemandedVecElts(OriginalDemandedElts);
569     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
570       unsigned Idx = CIdx->getZExtValue();
571       DemandedVecElts.clearBit(Idx);
572 
573       // Inserted element is not required.
574       if (!OriginalDemandedElts[Idx])
575         return TLO.CombineTo(Op, Vec);
576     }
577 
578     KnownBits KnownScl;
579     unsigned NumSclBits = Scl.getScalarValueSizeInBits();
580     APInt DemandedSclBits = OriginalDemandedBits.zextOrTrunc(NumSclBits);
581     if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
582       return true;
583 
584     Known = KnownScl.zextOrTrunc(BitWidth, false);
585 
586     KnownBits KnownVec;
587     if (SimplifyDemandedBits(Vec, OriginalDemandedBits, DemandedVecElts,
588                              KnownVec, TLO, Depth + 1))
589       return true;
590 
591     if (!!DemandedVecElts) {
592       Known.One &= KnownVec.One;
593       Known.Zero &= KnownVec.Zero;
594     }
595 
596     return false;
597   }
598   case ISD::CONCAT_VECTORS: {
599     Known.Zero.setAllBits();
600     Known.One.setAllBits();
601     EVT SubVT = Op.getOperand(0).getValueType();
602     unsigned NumSubVecs = Op.getNumOperands();
603     unsigned NumSubElts = SubVT.getVectorNumElements();
604     for (unsigned i = 0; i != NumSubVecs; ++i) {
605       APInt DemandedSubElts =
606           DemandedElts.extractBits(NumSubElts, i * NumSubElts);
607       if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts,
608                                Known2, TLO, Depth + 1))
609         return true;
610       // Known bits are shared by every demanded subvector element.
611       if (!!DemandedSubElts) {
612         Known.One &= Known2.One;
613         Known.Zero &= Known2.Zero;
614       }
615     }
616     break;
617   }
618   case ISD::VECTOR_SHUFFLE: {
619     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
620 
621     // Collect demanded elements from shuffle operands..
622     APInt DemandedLHS(NumElts, 0);
623     APInt DemandedRHS(NumElts, 0);
624     for (unsigned i = 0; i != NumElts; ++i) {
625       if (!DemandedElts[i])
626         continue;
627       int M = ShuffleMask[i];
628       if (M < 0) {
629         // For UNDEF elements, we don't know anything about the common state of
630         // the shuffle result.
631         DemandedLHS.clearAllBits();
632         DemandedRHS.clearAllBits();
633         break;
634       }
635       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
636       if (M < (int)NumElts)
637         DemandedLHS.setBit(M);
638       else
639         DemandedRHS.setBit(M - NumElts);
640     }
641 
642     if (!!DemandedLHS || !!DemandedRHS) {
643       Known.Zero.setAllBits();
644       Known.One.setAllBits();
645       if (!!DemandedLHS) {
646         if (SimplifyDemandedBits(Op.getOperand(0), DemandedBits, DemandedLHS,
647                                  Known2, TLO, Depth + 1))
648           return true;
649         Known.One &= Known2.One;
650         Known.Zero &= Known2.Zero;
651       }
652       if (!!DemandedRHS) {
653         if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedRHS,
654                                  Known2, TLO, Depth + 1))
655           return true;
656         Known.One &= Known2.One;
657         Known.Zero &= Known2.Zero;
658       }
659     }
660     break;
661   }
662   case ISD::AND: {
663     SDValue Op0 = Op.getOperand(0);
664     SDValue Op1 = Op.getOperand(1);
665 
666     // If the RHS is a constant, check to see if the LHS would be zero without
667     // using the bits from the RHS.  Below, we use knowledge about the RHS to
668     // simplify the LHS, here we're using information from the LHS to simplify
669     // the RHS.
670     if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) {
671       // Do not increment Depth here; that can cause an infinite loop.
672       KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth);
673       // If the LHS already has zeros where RHSC does, this 'and' is dead.
674       if ((LHSKnown.Zero & DemandedBits) ==
675           (~RHSC->getAPIntValue() & DemandedBits))
676         return TLO.CombineTo(Op, Op0);
677 
678       // If any of the set bits in the RHS are known zero on the LHS, shrink
679       // the constant.
680       if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits, TLO))
681         return true;
682 
683       // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
684       // constant, but if this 'and' is only clearing bits that were just set by
685       // the xor, then this 'and' can be eliminated by shrinking the mask of
686       // the xor. For example, for a 32-bit X:
687       // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
688       if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
689           LHSKnown.One == ~RHSC->getAPIntValue()) {
690         SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1);
691         return TLO.CombineTo(Op, Xor);
692       }
693     }
694 
695     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
696                              Depth + 1))
697       return true;
698     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
699     if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts,
700                              Known2, TLO, Depth + 1))
701       return true;
702     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
703 
704     // If all of the demanded bits are known one on one side, return the other.
705     // These bits cannot contribute to the result of the 'and'.
706     if (DemandedBits.isSubsetOf(Known2.Zero | Known.One))
707       return TLO.CombineTo(Op, Op0);
708     if (DemandedBits.isSubsetOf(Known.Zero | Known2.One))
709       return TLO.CombineTo(Op, Op1);
710     // If all of the demanded bits in the inputs are known zeros, return zero.
711     if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
712       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
713     // If the RHS is a constant, see if we can simplify it.
714     if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, TLO))
715       return true;
716     // If the operation can be done in a smaller type, do so.
717     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
718       return true;
719 
720     // Output known-1 bits are only known if set in both the LHS & RHS.
721     Known.One &= Known2.One;
722     // Output known-0 are known to be clear if zero in either the LHS | RHS.
723     Known.Zero |= Known2.Zero;
724     break;
725   }
726   case ISD::OR: {
727     SDValue Op0 = Op.getOperand(0);
728     SDValue Op1 = Op.getOperand(1);
729 
730     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
731                              Depth + 1))
732       return true;
733     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
734     if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts,
735                              Known2, TLO, Depth + 1))
736       return true;
737     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
738 
739     // If all of the demanded bits are known zero on one side, return the other.
740     // These bits cannot contribute to the result of the 'or'.
741     if (DemandedBits.isSubsetOf(Known2.One | Known.Zero))
742       return TLO.CombineTo(Op, Op0);
743     if (DemandedBits.isSubsetOf(Known.One | Known2.Zero))
744       return TLO.CombineTo(Op, Op1);
745     // If the RHS is a constant, see if we can simplify it.
746     if (ShrinkDemandedConstant(Op, DemandedBits, TLO))
747       return true;
748     // If the operation can be done in a smaller type, do so.
749     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
750       return true;
751 
752     // Output known-0 bits are only known if clear in both the LHS & RHS.
753     Known.Zero &= Known2.Zero;
754     // Output known-1 are known to be set if set in either the LHS | RHS.
755     Known.One |= Known2.One;
756     break;
757   }
758   case ISD::XOR: {
759     SDValue Op0 = Op.getOperand(0);
760     SDValue Op1 = Op.getOperand(1);
761 
762     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
763                              Depth + 1))
764       return true;
765     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
766     if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO,
767                              Depth + 1))
768       return true;
769     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
770 
771     // If all of the demanded bits are known zero on one side, return the other.
772     // These bits cannot contribute to the result of the 'xor'.
773     if (DemandedBits.isSubsetOf(Known.Zero))
774       return TLO.CombineTo(Op, Op0);
775     if (DemandedBits.isSubsetOf(Known2.Zero))
776       return TLO.CombineTo(Op, Op1);
777     // If the operation can be done in a smaller type, do so.
778     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
779       return true;
780 
781     // If all of the unknown bits are known to be zero on one side or the other
782     // (but not both) turn this into an *inclusive* or.
783     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
784     if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
785       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1));
786 
787     // Output known-0 bits are known if clear or set in both the LHS & RHS.
788     KnownOut.Zero = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
789     // Output known-1 are known to be set if set in only one of the LHS, RHS.
790     KnownOut.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
791 
792     if (ConstantSDNode *C = isConstOrConstSplat(Op1)) {
793       // If one side is a constant, and all of the known set bits on the other
794       // side are also set in the constant, turn this into an AND, as we know
795       // the bits will be cleared.
796       //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
797       // NB: it is okay if more bits are known than are requested
798       if (C->getAPIntValue() == Known2.One) {
799         SDValue ANDC =
800             TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT);
801         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC));
802       }
803 
804       // If the RHS is a constant, see if we can change it. Don't alter a -1
805       // constant because that's a 'not' op, and that is better for combining
806       // and codegen.
807       if (!C->isAllOnesValue()) {
808         if (DemandedBits.isSubsetOf(C->getAPIntValue())) {
809           // We're flipping all demanded bits. Flip the undemanded bits too.
810           SDValue New = TLO.DAG.getNOT(dl, Op0, VT);
811           return TLO.CombineTo(Op, New);
812         }
813         // If we can't turn this into a 'not', try to shrink the constant.
814         if (ShrinkDemandedConstant(Op, DemandedBits, TLO))
815           return true;
816       }
817     }
818 
819     Known = std::move(KnownOut);
820     break;
821   }
822   case ISD::SELECT:
823     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO,
824                              Depth + 1))
825       return true;
826     if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO,
827                              Depth + 1))
828       return true;
829     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
830     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
831 
832     // If the operands are constants, see if we can simplify them.
833     if (ShrinkDemandedConstant(Op, DemandedBits, TLO))
834       return true;
835 
836     // Only known if known in both the LHS and RHS.
837     Known.One &= Known2.One;
838     Known.Zero &= Known2.Zero;
839     break;
840   case ISD::SELECT_CC:
841     if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO,
842                              Depth + 1))
843       return true;
844     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO,
845                              Depth + 1))
846       return true;
847     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
848     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
849 
850     // If the operands are constants, see if we can simplify them.
851     if (ShrinkDemandedConstant(Op, DemandedBits, TLO))
852       return true;
853 
854     // Only known if known in both the LHS and RHS.
855     Known.One &= Known2.One;
856     Known.Zero &= Known2.Zero;
857     break;
858   case ISD::SETCC: {
859     SDValue Op0 = Op.getOperand(0);
860     SDValue Op1 = Op.getOperand(1);
861     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
862     // If (1) we only need the sign-bit, (2) the setcc operands are the same
863     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
864     // -1, we may be able to bypass the setcc.
865     if (DemandedBits.isSignMask() &&
866         Op0.getScalarValueSizeInBits() == BitWidth &&
867         getBooleanContents(VT) ==
868             BooleanContent::ZeroOrNegativeOneBooleanContent) {
869       // If we're testing X < 0, then this compare isn't needed - just use X!
870       // FIXME: We're limiting to integer types here, but this should also work
871       // if we don't care about FP signed-zero. The use of SETLT with FP means
872       // that we don't care about NaNs.
873       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
874           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
875         return TLO.CombineTo(Op, Op0);
876 
877       // TODO: Should we check for other forms of sign-bit comparisons?
878       // Examples: X <= -1, X >= 0
879     }
880     if (getBooleanContents(Op0.getValueType()) ==
881             TargetLowering::ZeroOrOneBooleanContent &&
882         BitWidth > 1)
883       Known.Zero.setBitsFrom(1);
884     break;
885   }
886   case ISD::SHL: {
887     SDValue Op0 = Op.getOperand(0);
888     SDValue Op1 = Op.getOperand(1);
889 
890     if (ConstantSDNode *SA = isConstOrConstSplat(Op1)) {
891       // If the shift count is an invalid immediate, don't do anything.
892       if (SA->getAPIntValue().uge(BitWidth))
893         break;
894 
895       unsigned ShAmt = SA->getZExtValue();
896 
897       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
898       // single shift.  We can do this if the bottom bits (which are shifted
899       // out) are never demanded.
900       if (Op0.getOpcode() == ISD::SRL) {
901         if (ShAmt &&
902             (DemandedBits & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
903           if (ConstantSDNode *SA2 = isConstOrConstSplat(Op0.getOperand(1))) {
904             if (SA2->getAPIntValue().ult(BitWidth)) {
905               unsigned C1 = SA2->getZExtValue();
906               unsigned Opc = ISD::SHL;
907               int Diff = ShAmt - C1;
908               if (Diff < 0) {
909                 Diff = -Diff;
910                 Opc = ISD::SRL;
911               }
912 
913               SDValue NewSA = TLO.DAG.getConstant(Diff, dl, Op1.getValueType());
914               return TLO.CombineTo(
915                   Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
916             }
917           }
918         }
919       }
920 
921       if (SimplifyDemandedBits(Op0, DemandedBits.lshr(ShAmt), DemandedElts,
922                                Known, TLO, Depth + 1))
923         return true;
924 
925       // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
926       // are not demanded. This will likely allow the anyext to be folded away.
927       if (Op0.getOpcode() == ISD::ANY_EXTEND) {
928         SDValue InnerOp = Op0.getOperand(0);
929         EVT InnerVT = InnerOp.getValueType();
930         unsigned InnerBits = InnerVT.getScalarSizeInBits();
931         if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits &&
932             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
933           EVT ShTy = getShiftAmountTy(InnerVT, DL);
934           if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
935             ShTy = InnerVT;
936           SDValue NarrowShl =
937               TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
938                               TLO.DAG.getConstant(ShAmt, dl, ShTy));
939           return TLO.CombineTo(
940               Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
941         }
942         // Repeat the SHL optimization above in cases where an extension
943         // intervenes: (shl (anyext (shr x, c1)), c2) to
944         // (shl (anyext x), c2-c1).  This requires that the bottom c1 bits
945         // aren't demanded (as above) and that the shifted upper c1 bits of
946         // x aren't demanded.
947         if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL &&
948             InnerOp.hasOneUse()) {
949           if (ConstantSDNode *SA2 =
950                   isConstOrConstSplat(InnerOp.getOperand(1))) {
951             unsigned InnerShAmt = SA2->getLimitedValue(InnerBits);
952             if (InnerShAmt < ShAmt && InnerShAmt < InnerBits &&
953                 DemandedBits.getActiveBits() <=
954                     (InnerBits - InnerShAmt + ShAmt) &&
955                 DemandedBits.countTrailingZeros() >= ShAmt) {
956               SDValue NewSA = TLO.DAG.getConstant(ShAmt - InnerShAmt, dl,
957                                                   Op1.getValueType());
958               SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
959                                                InnerOp.getOperand(0));
960               return TLO.CombineTo(
961                   Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA));
962             }
963           }
964         }
965       }
966 
967       Known.Zero <<= ShAmt;
968       Known.One <<= ShAmt;
969       // low bits known zero.
970       Known.Zero.setLowBits(ShAmt);
971     }
972     break;
973   }
974   case ISD::SRL: {
975     SDValue Op0 = Op.getOperand(0);
976     SDValue Op1 = Op.getOperand(1);
977 
978     if (ConstantSDNode *SA = isConstOrConstSplat(Op1)) {
979       // If the shift count is an invalid immediate, don't do anything.
980       if (SA->getAPIntValue().uge(BitWidth))
981         break;
982 
983       unsigned ShAmt = SA->getZExtValue();
984       APInt InDemandedMask = (DemandedBits << ShAmt);
985 
986       // If the shift is exact, then it does demand the low bits (and knows that
987       // they are zero).
988       if (Op->getFlags().hasExact())
989         InDemandedMask.setLowBits(ShAmt);
990 
991       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
992       // single shift.  We can do this if the top bits (which are shifted out)
993       // are never demanded.
994       if (Op0.getOpcode() == ISD::SHL) {
995         if (ConstantSDNode *SA2 = isConstOrConstSplat(Op0.getOperand(1))) {
996           if (ShAmt &&
997               (DemandedBits & APInt::getHighBitsSet(BitWidth, ShAmt)) == 0) {
998             if (SA2->getAPIntValue().ult(BitWidth)) {
999               unsigned C1 = SA2->getZExtValue();
1000               unsigned Opc = ISD::SRL;
1001               int Diff = ShAmt - C1;
1002               if (Diff < 0) {
1003                 Diff = -Diff;
1004                 Opc = ISD::SHL;
1005               }
1006 
1007               SDValue NewSA = TLO.DAG.getConstant(Diff, dl, Op1.getValueType());
1008               return TLO.CombineTo(
1009                   Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1010             }
1011           }
1012         }
1013       }
1014 
1015       // Compute the new bits that are at the top now.
1016       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1017                                Depth + 1))
1018         return true;
1019       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1020       Known.Zero.lshrInPlace(ShAmt);
1021       Known.One.lshrInPlace(ShAmt);
1022 
1023       Known.Zero.setHighBits(ShAmt); // High bits known zero.
1024     }
1025     break;
1026   }
1027   case ISD::SRA: {
1028     SDValue Op0 = Op.getOperand(0);
1029     SDValue Op1 = Op.getOperand(1);
1030 
1031     // If this is an arithmetic shift right and only the low-bit is set, we can
1032     // always convert this into a logical shr, even if the shift amount is
1033     // variable.  The low bit of the shift cannot be an input sign bit unless
1034     // the shift amount is >= the size of the datatype, which is undefined.
1035     if (DemandedBits.isOneValue())
1036       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
1037 
1038     if (ConstantSDNode *SA = isConstOrConstSplat(Op1)) {
1039       // If the shift count is an invalid immediate, don't do anything.
1040       if (SA->getAPIntValue().uge(BitWidth))
1041         break;
1042 
1043       unsigned ShAmt = SA->getZExtValue();
1044       APInt InDemandedMask = (DemandedBits << ShAmt);
1045 
1046       // If the shift is exact, then it does demand the low bits (and knows that
1047       // they are zero).
1048       if (Op->getFlags().hasExact())
1049         InDemandedMask.setLowBits(ShAmt);
1050 
1051       // If any of the demanded bits are produced by the sign extension, we also
1052       // demand the input sign bit.
1053       if (DemandedBits.countLeadingZeros() < ShAmt)
1054         InDemandedMask.setSignBit();
1055 
1056       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1057                                Depth + 1))
1058         return true;
1059       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1060       Known.Zero.lshrInPlace(ShAmt);
1061       Known.One.lshrInPlace(ShAmt);
1062 
1063       // If the input sign bit is known to be zero, or if none of the top bits
1064       // are demanded, turn this into an unsigned shift right.
1065       if (Known.Zero[BitWidth - ShAmt - 1] ||
1066           DemandedBits.countLeadingZeros() >= ShAmt) {
1067         SDNodeFlags Flags;
1068         Flags.setExact(Op->getFlags().hasExact());
1069         return TLO.CombineTo(
1070             Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags));
1071       }
1072 
1073       int Log2 = DemandedBits.exactLogBase2();
1074       if (Log2 >= 0) {
1075         // The bit must come from the sign.
1076         SDValue NewSA =
1077             TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, Op1.getValueType());
1078         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA));
1079       }
1080 
1081       if (Known.One[BitWidth - ShAmt - 1])
1082         // New bits are known one.
1083         Known.One.setHighBits(ShAmt);
1084     }
1085     break;
1086   }
1087   case ISD::FSHL:
1088   case ISD::FSHR: {
1089     SDValue Op0 = Op.getOperand(0);
1090     SDValue Op1 = Op.getOperand(1);
1091     SDValue Op2 = Op.getOperand(2);
1092     bool IsFSHL = (Op.getOpcode() == ISD::FSHL);
1093 
1094     if (ConstantSDNode *SA = isConstOrConstSplat(Op2)) {
1095       unsigned Amt = SA->getAPIntValue().urem(BitWidth);
1096 
1097       // For fshl, 0-shift returns the 1st arg.
1098       // For fshr, 0-shift returns the 2nd arg.
1099       if (Amt == 0) {
1100         if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts,
1101                                  Known, TLO, Depth + 1))
1102           return true;
1103         break;
1104       }
1105 
1106       // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
1107       // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
1108       APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt));
1109       APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt);
1110       if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
1111                                Depth + 1))
1112         return true;
1113       if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO,
1114                                Depth + 1))
1115         return true;
1116 
1117       Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt));
1118       Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt));
1119       Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
1120       Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
1121       Known.One |= Known2.One;
1122       Known.Zero |= Known2.Zero;
1123     }
1124     break;
1125   }
1126   case ISD::SIGN_EXTEND_INREG: {
1127     SDValue Op0 = Op.getOperand(0);
1128     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1129     unsigned ExVTBits = ExVT.getScalarSizeInBits();
1130 
1131     // If we only care about the highest bit, don't bother shifting right.
1132     if (DemandedBits.isSignMask()) {
1133       bool AlreadySignExtended =
1134           TLO.DAG.ComputeNumSignBits(Op0) >= BitWidth - ExVTBits + 1;
1135       // However if the input is already sign extended we expect the sign
1136       // extension to be dropped altogether later and do not simplify.
1137       if (!AlreadySignExtended) {
1138         // Compute the correct shift amount type, which must be getShiftAmountTy
1139         // for scalar types after legalization.
1140         EVT ShiftAmtTy = VT;
1141         if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
1142           ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL);
1143 
1144         SDValue ShiftAmt =
1145             TLO.DAG.getConstant(BitWidth - ExVTBits, dl, ShiftAmtTy);
1146         return TLO.CombineTo(Op,
1147                              TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt));
1148       }
1149     }
1150 
1151     // If none of the extended bits are demanded, eliminate the sextinreg.
1152     if (DemandedBits.getActiveBits() <= ExVTBits)
1153       return TLO.CombineTo(Op, Op0);
1154 
1155     APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits);
1156 
1157     // Since the sign extended bits are demanded, we know that the sign
1158     // bit is demanded.
1159     InputDemandedBits.setBit(ExVTBits - 1);
1160 
1161     if (SimplifyDemandedBits(Op0, InputDemandedBits, Known, TLO, Depth + 1))
1162       return true;
1163     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1164 
1165     // If the sign bit of the input is known set or clear, then we know the
1166     // top bits of the result.
1167 
1168     // If the input sign bit is known zero, convert this into a zero extension.
1169     if (Known.Zero[ExVTBits - 1])
1170       return TLO.CombineTo(
1171           Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT.getScalarType()));
1172 
1173     APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
1174     if (Known.One[ExVTBits - 1]) { // Input sign bit known set
1175       Known.One.setBitsFrom(ExVTBits);
1176       Known.Zero &= Mask;
1177     } else { // Input sign bit unknown
1178       Known.Zero &= Mask;
1179       Known.One &= Mask;
1180     }
1181     break;
1182   }
1183   case ISD::BUILD_PAIR: {
1184     EVT HalfVT = Op.getOperand(0).getValueType();
1185     unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
1186 
1187     APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
1188     APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
1189 
1190     KnownBits KnownLo, KnownHi;
1191 
1192     if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
1193       return true;
1194 
1195     if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
1196       return true;
1197 
1198     Known.Zero = KnownLo.Zero.zext(BitWidth) |
1199                  KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth);
1200 
1201     Known.One = KnownLo.One.zext(BitWidth) |
1202                 KnownHi.One.zext(BitWidth).shl(HalfBitWidth);
1203     break;
1204   }
1205   case ISD::ZERO_EXTEND: {
1206     SDValue Src = Op.getOperand(0);
1207     unsigned InBits = Src.getScalarValueSizeInBits();
1208 
1209     // If none of the top bits are demanded, convert this into an any_extend.
1210     if (DemandedBits.getActiveBits() <= InBits)
1211       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, Src));
1212 
1213     APInt InDemandedBits = DemandedBits.trunc(InBits);
1214     if (SimplifyDemandedBits(Src, InDemandedBits, Known, TLO, Depth + 1))
1215       return true;
1216     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1217     assert(Known.getBitWidth() == InBits && "Src width has changed?");
1218     Known = Known.zext(BitWidth, true /* ExtendedBitsAreKnownZero */);
1219     break;
1220   }
1221   case ISD::SIGN_EXTEND: {
1222     SDValue Src = Op.getOperand(0);
1223     unsigned InBits = Src.getScalarValueSizeInBits();
1224 
1225     // If none of the top bits are demanded, convert this into an any_extend.
1226     if (DemandedBits.getActiveBits() <= InBits)
1227       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, Src));
1228 
1229     // Since some of the sign extended bits are demanded, we know that the sign
1230     // bit is demanded.
1231     APInt InDemandedBits = DemandedBits.trunc(InBits);
1232     InDemandedBits.setBit(InBits - 1);
1233 
1234     if (SimplifyDemandedBits(Src, InDemandedBits, Known, TLO, Depth + 1))
1235       return true;
1236     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1237     // If the sign bit is known one, the top bits match.
1238     Known = Known.sext(BitWidth);
1239 
1240     // If the sign bit is known zero, convert this to a zero extend.
1241     if (Known.isNonNegative())
1242       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Src));
1243     break;
1244   }
1245   case ISD::SIGN_EXTEND_VECTOR_INREG: {
1246     // TODO - merge this with SIGN_EXTEND above?
1247     SDValue Src = Op.getOperand(0);
1248     unsigned InBits = Src.getScalarValueSizeInBits();
1249 
1250     APInt InDemandedBits = DemandedBits.trunc(InBits);
1251 
1252     // If some of the sign extended bits are demanded, we know that the sign
1253     // bit is demanded.
1254     if (InBits < DemandedBits.getActiveBits())
1255       InDemandedBits.setBit(InBits - 1);
1256 
1257     if (SimplifyDemandedBits(Src, InDemandedBits, Known, TLO, Depth + 1))
1258       return true;
1259     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1260     // If the sign bit is known one, the top bits match.
1261     Known = Known.sext(BitWidth);
1262     break;
1263   }
1264   case ISD::ANY_EXTEND: {
1265     SDValue Src = Op.getOperand(0);
1266     unsigned InBits = Src.getScalarValueSizeInBits();
1267     APInt InDemandedBits = DemandedBits.trunc(InBits);
1268     if (SimplifyDemandedBits(Src, InDemandedBits, Known, TLO, Depth + 1))
1269       return true;
1270     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1271     Known = Known.zext(BitWidth, false /* => any extend */);
1272     break;
1273   }
1274   case ISD::TRUNCATE: {
1275     SDValue Src = Op.getOperand(0);
1276 
1277     // Simplify the input, using demanded bit information, and compute the known
1278     // zero/one bits live out.
1279     unsigned OperandBitWidth = Src.getScalarValueSizeInBits();
1280     APInt TruncMask = DemandedBits.zext(OperandBitWidth);
1281     if (SimplifyDemandedBits(Src, TruncMask, Known, TLO, Depth + 1))
1282       return true;
1283     Known = Known.trunc(BitWidth);
1284 
1285     // If the input is only used by this truncate, see if we can shrink it based
1286     // on the known demanded bits.
1287     if (Src.getNode()->hasOneUse()) {
1288       switch (Src.getOpcode()) {
1289       default:
1290         break;
1291       case ISD::SRL:
1292         // Shrink SRL by a constant if none of the high bits shifted in are
1293         // demanded.
1294         if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
1295           // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1296           // undesirable.
1297           break;
1298 
1299         auto *ShAmt = dyn_cast<ConstantSDNode>(Src.getOperand(1));
1300         if (!ShAmt || ShAmt->getAPIntValue().uge(BitWidth))
1301           break;
1302 
1303         SDValue Shift = Src.getOperand(1);
1304         uint64_t ShVal = ShAmt->getZExtValue();
1305 
1306         if (TLO.LegalTypes())
1307           Shift = TLO.DAG.getConstant(ShVal, dl, getShiftAmountTy(VT, DL));
1308 
1309         APInt HighBits =
1310             APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth);
1311         HighBits.lshrInPlace(ShVal);
1312         HighBits = HighBits.trunc(BitWidth);
1313 
1314         if (!(HighBits & DemandedBits)) {
1315           // None of the shifted in bits are needed.  Add a truncate of the
1316           // shift input, then shift it.
1317           SDValue NewTrunc =
1318               TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0));
1319           return TLO.CombineTo(
1320               Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, Shift));
1321         }
1322         break;
1323       }
1324     }
1325 
1326     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1327     break;
1328   }
1329   case ISD::AssertZext: {
1330     // AssertZext demands all of the high bits, plus any of the low bits
1331     // demanded by its users.
1332     EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1333     APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits());
1334     if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known,
1335                              TLO, Depth + 1))
1336       return true;
1337     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1338 
1339     Known.Zero |= ~InMask;
1340     break;
1341   }
1342   case ISD::EXTRACT_VECTOR_ELT: {
1343     SDValue Src = Op.getOperand(0);
1344     SDValue Idx = Op.getOperand(1);
1345     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1346     unsigned EltBitWidth = Src.getScalarValueSizeInBits();
1347 
1348     // Demand the bits from every vector element without a constant index.
1349     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
1350     if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx))
1351       if (CIdx->getAPIntValue().ult(NumSrcElts))
1352         DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue());
1353 
1354     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
1355     // anything about the extended bits.
1356     APInt DemandedSrcBits = DemandedBits;
1357     if (BitWidth > EltBitWidth)
1358       DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth);
1359 
1360     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO,
1361                              Depth + 1))
1362       return true;
1363 
1364     Known = Known2;
1365     if (BitWidth > EltBitWidth)
1366       Known = Known.zext(BitWidth, false /* => any extend */);
1367     break;
1368   }
1369   case ISD::BITCAST: {
1370     SDValue Src = Op.getOperand(0);
1371     EVT SrcVT = Src.getValueType();
1372     unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
1373 
1374     // If this is an FP->Int bitcast and if the sign bit is the only
1375     // thing demanded, turn this into a FGETSIGN.
1376     if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() &&
1377         DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) &&
1378         SrcVT.isFloatingPoint()) {
1379       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT);
1380       bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
1381       if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 &&
1382           SrcVT != MVT::f128) {
1383         // Cannot eliminate/lower SHL for f128 yet.
1384         EVT Ty = OpVTLegal ? VT : MVT::i32;
1385         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1386         // place.  We expect the SHL to be eliminated by other optimizations.
1387         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src);
1388         unsigned OpVTSizeInBits = Op.getValueSizeInBits();
1389         if (!OpVTLegal && OpVTSizeInBits > 32)
1390           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign);
1391         unsigned ShVal = Op.getValueSizeInBits() - 1;
1392         SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT);
1393         return TLO.CombineTo(Op,
1394                              TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
1395       }
1396     }
1397     // If bitcast from a vector, see if we can use SimplifyDemandedVectorElts by
1398     // demanding the element if any bits from it are demanded.
1399     // TODO - bigendian once we have test coverage.
1400     // TODO - bool vectors once SimplifyDemandedVectorElts has SETCC support.
1401     if (SrcVT.isVector() && NumSrcEltBits > 1 &&
1402         (BitWidth % NumSrcEltBits) == 0 &&
1403         TLO.DAG.getDataLayout().isLittleEndian()) {
1404       unsigned Scale = BitWidth / NumSrcEltBits;
1405       auto GetDemandedSubMask = [&](APInt &DemandedSubElts) -> bool {
1406         DemandedSubElts = APInt::getNullValue(Scale);
1407         for (unsigned i = 0; i != Scale; ++i) {
1408           unsigned Offset = i * NumSrcEltBits;
1409           APInt Sub = DemandedBits.extractBits(NumSrcEltBits, Offset);
1410           if (!Sub.isNullValue())
1411             DemandedSubElts.setBit(i);
1412         }
1413         return true;
1414       };
1415 
1416       APInt DemandedSubElts;
1417       if (GetDemandedSubMask(DemandedSubElts)) {
1418         unsigned NumSrcElts = SrcVT.getVectorNumElements();
1419         APInt DemandedElts = APInt::getSplat(NumSrcElts, DemandedSubElts);
1420 
1421         APInt KnownUndef, KnownZero;
1422         if (SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, KnownZero,
1423                                        TLO, Depth + 1))
1424           return true;
1425       }
1426     }
1427     // If this is a bitcast, let computeKnownBits handle it.  Only do this on a
1428     // recursive call where Known may be useful to the caller.
1429     if (Depth > 0) {
1430       Known = TLO.DAG.computeKnownBits(Op, Depth);
1431       return false;
1432     }
1433     break;
1434   }
1435   case ISD::ADD:
1436   case ISD::MUL:
1437   case ISD::SUB: {
1438     // Add, Sub, and Mul don't demand any bits in positions beyond that
1439     // of the highest bit demanded of them.
1440     SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
1441     unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros();
1442     APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
1443     if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO,
1444                              Depth + 1) ||
1445         SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO,
1446                              Depth + 1) ||
1447         // See if the operation should be performed at a smaller bit width.
1448         ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) {
1449       SDNodeFlags Flags = Op.getNode()->getFlags();
1450       if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) {
1451         // Disable the nsw and nuw flags. We can no longer guarantee that we
1452         // won't wrap after simplification.
1453         Flags.setNoSignedWrap(false);
1454         Flags.setNoUnsignedWrap(false);
1455         SDValue NewOp =
1456             TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags);
1457         return TLO.CombineTo(Op, NewOp);
1458       }
1459       return true;
1460     }
1461 
1462     // If we have a constant operand, we may be able to turn it into -1 if we
1463     // do not demand the high bits. This can make the constant smaller to
1464     // encode, allow more general folding, or match specialized instruction
1465     // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
1466     // is probably not useful (and could be detrimental).
1467     ConstantSDNode *C = isConstOrConstSplat(Op1);
1468     APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ);
1469     if (C && !C->isAllOnesValue() && !C->isOne() &&
1470         (C->getAPIntValue() | HighMask).isAllOnesValue()) {
1471       SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
1472       // We can't guarantee that the new math op doesn't wrap, so explicitly
1473       // clear those flags to prevent folding with a potential existing node
1474       // that has those flags set.
1475       SDNodeFlags Flags;
1476       Flags.setNoSignedWrap(false);
1477       Flags.setNoUnsignedWrap(false);
1478       SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags);
1479       return TLO.CombineTo(Op, NewOp);
1480     }
1481 
1482     LLVM_FALLTHROUGH;
1483   }
1484   default:
1485     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1486       if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts,
1487                                             Known, TLO, Depth))
1488         return true;
1489       break;
1490     }
1491 
1492     // Just use computeKnownBits to compute output bits.
1493     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1494     break;
1495   }
1496 
1497   // If we know the value of all of the demanded bits, return this as a
1498   // constant.
1499   if (DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
1500     // Avoid folding to a constant if any OpaqueConstant is involved.
1501     const SDNode *N = Op.getNode();
1502     for (SDNodeIterator I = SDNodeIterator::begin(N),
1503                         E = SDNodeIterator::end(N);
1504          I != E; ++I) {
1505       SDNode *Op = *I;
1506       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
1507         if (C->isOpaque())
1508           return false;
1509     }
1510     // TODO: Handle float bits as well.
1511     if (VT.isInteger())
1512       return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
1513   }
1514 
1515   return false;
1516 }
1517 
1518 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op,
1519                                                 const APInt &DemandedElts,
1520                                                 APInt &KnownUndef,
1521                                                 APInt &KnownZero,
1522                                                 DAGCombinerInfo &DCI) const {
1523   SelectionDAG &DAG = DCI.DAG;
1524   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1525                         !DCI.isBeforeLegalizeOps());
1526 
1527   bool Simplified =
1528       SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
1529   if (Simplified) {
1530     DCI.AddToWorklist(Op.getNode());
1531     DCI.CommitTargetLoweringOpt(TLO);
1532   }
1533   return Simplified;
1534 }
1535 
1536 /// Given a vector binary operation and known undefined elements for each input
1537 /// operand, compute whether each element of the output is undefined.
1538 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG,
1539                                          const APInt &UndefOp0,
1540                                          const APInt &UndefOp1) {
1541   EVT VT = BO.getValueType();
1542   assert(ISD::isBinaryOp(BO.getNode()) && VT.isVector() && "Vector binop only");
1543 
1544   EVT EltVT = VT.getVectorElementType();
1545   unsigned NumElts = VT.getVectorNumElements();
1546   assert(UndefOp0.getBitWidth() == NumElts &&
1547          UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
1548 
1549   auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
1550                                    const APInt &UndefVals) {
1551     if (UndefVals[Index])
1552       return DAG.getUNDEF(EltVT);
1553 
1554     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1555       // Try hard to make sure that the getNode() call is not creating temporary
1556       // nodes. Ignore opaque integers because they do not constant fold.
1557       SDValue Elt = BV->getOperand(Index);
1558       auto *C = dyn_cast<ConstantSDNode>(Elt);
1559       if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
1560         return Elt;
1561     }
1562 
1563     return SDValue();
1564   };
1565 
1566   APInt KnownUndef = APInt::getNullValue(NumElts);
1567   for (unsigned i = 0; i != NumElts; ++i) {
1568     // If both inputs for this element are either constant or undef and match
1569     // the element type, compute the constant/undef result for this element of
1570     // the vector.
1571     // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
1572     // not handle FP constants. The code within getNode() should be refactored
1573     // to avoid the danger of creating a bogus temporary node here.
1574     SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
1575     SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
1576     if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
1577       if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
1578         KnownUndef.setBit(i);
1579   }
1580   return KnownUndef;
1581 }
1582 
1583 bool TargetLowering::SimplifyDemandedVectorElts(
1584     SDValue Op, const APInt &DemandedEltMask, APInt &KnownUndef,
1585     APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
1586     bool AssumeSingleUse) const {
1587   EVT VT = Op.getValueType();
1588   APInt DemandedElts = DemandedEltMask;
1589   unsigned NumElts = DemandedElts.getBitWidth();
1590   assert(VT.isVector() && "Expected vector op");
1591   assert(VT.getVectorNumElements() == NumElts &&
1592          "Mask size mismatches value type element count!");
1593 
1594   KnownUndef = KnownZero = APInt::getNullValue(NumElts);
1595 
1596   // Undef operand.
1597   if (Op.isUndef()) {
1598     KnownUndef.setAllBits();
1599     return false;
1600   }
1601 
1602   // If Op has other users, assume that all elements are needed.
1603   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse)
1604     DemandedElts.setAllBits();
1605 
1606   // Not demanding any elements from Op.
1607   if (DemandedElts == 0) {
1608     KnownUndef.setAllBits();
1609     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1610   }
1611 
1612   // Limit search depth.
1613   if (Depth >= 6)
1614     return false;
1615 
1616   SDLoc DL(Op);
1617   unsigned EltSizeInBits = VT.getScalarSizeInBits();
1618 
1619   switch (Op.getOpcode()) {
1620   case ISD::SCALAR_TO_VECTOR: {
1621     if (!DemandedElts[0]) {
1622       KnownUndef.setAllBits();
1623       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1624     }
1625     KnownUndef.setHighBits(NumElts - 1);
1626     break;
1627   }
1628   case ISD::BITCAST: {
1629     SDValue Src = Op.getOperand(0);
1630     EVT SrcVT = Src.getValueType();
1631 
1632     // We only handle vectors here.
1633     // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits?
1634     if (!SrcVT.isVector())
1635       break;
1636 
1637     // Fast handling of 'identity' bitcasts.
1638     unsigned NumSrcElts = SrcVT.getVectorNumElements();
1639     if (NumSrcElts == NumElts)
1640       return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
1641                                         KnownZero, TLO, Depth + 1);
1642 
1643     APInt SrcZero, SrcUndef;
1644     APInt SrcDemandedElts = APInt::getNullValue(NumSrcElts);
1645 
1646     // Bitcast from 'large element' src vector to 'small element' vector, we
1647     // must demand a source element if any DemandedElt maps to it.
1648     if ((NumElts % NumSrcElts) == 0) {
1649       unsigned Scale = NumElts / NumSrcElts;
1650       for (unsigned i = 0; i != NumElts; ++i)
1651         if (DemandedElts[i])
1652           SrcDemandedElts.setBit(i / Scale);
1653 
1654       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
1655                                      TLO, Depth + 1))
1656         return true;
1657 
1658       // Try calling SimplifyDemandedBits, converting demanded elts to the bits
1659       // of the large element.
1660       // TODO - bigendian once we have test coverage.
1661       if (TLO.DAG.getDataLayout().isLittleEndian()) {
1662         unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
1663         APInt SrcDemandedBits = APInt::getNullValue(SrcEltSizeInBits);
1664         for (unsigned i = 0; i != NumElts; ++i)
1665           if (DemandedElts[i]) {
1666             unsigned Ofs = (i % Scale) * EltSizeInBits;
1667             SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
1668           }
1669 
1670         KnownBits Known;
1671         if (SimplifyDemandedBits(Src, SrcDemandedBits, Known, TLO, Depth + 1))
1672           return true;
1673       }
1674 
1675       // If the src element is zero/undef then all the output elements will be -
1676       // only demanded elements are guaranteed to be correct.
1677       for (unsigned i = 0; i != NumSrcElts; ++i) {
1678         if (SrcDemandedElts[i]) {
1679           if (SrcZero[i])
1680             KnownZero.setBits(i * Scale, (i + 1) * Scale);
1681           if (SrcUndef[i])
1682             KnownUndef.setBits(i * Scale, (i + 1) * Scale);
1683         }
1684       }
1685     }
1686 
1687     // Bitcast from 'small element' src vector to 'large element' vector, we
1688     // demand all smaller source elements covered by the larger demanded element
1689     // of this vector.
1690     if ((NumSrcElts % NumElts) == 0) {
1691       unsigned Scale = NumSrcElts / NumElts;
1692       for (unsigned i = 0; i != NumElts; ++i)
1693         if (DemandedElts[i])
1694           SrcDemandedElts.setBits(i * Scale, (i + 1) * Scale);
1695 
1696       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
1697                                      TLO, Depth + 1))
1698         return true;
1699 
1700       // If all the src elements covering an output element are zero/undef, then
1701       // the output element will be as well, assuming it was demanded.
1702       for (unsigned i = 0; i != NumElts; ++i) {
1703         if (DemandedElts[i]) {
1704           if (SrcZero.extractBits(Scale, i * Scale).isAllOnesValue())
1705             KnownZero.setBit(i);
1706           if (SrcUndef.extractBits(Scale, i * Scale).isAllOnesValue())
1707             KnownUndef.setBit(i);
1708         }
1709       }
1710     }
1711     break;
1712   }
1713   case ISD::BUILD_VECTOR: {
1714     // Check all elements and simplify any unused elements with UNDEF.
1715     if (!DemandedElts.isAllOnesValue()) {
1716       // Don't simplify BROADCASTS.
1717       if (llvm::any_of(Op->op_values(),
1718                        [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
1719         SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end());
1720         bool Updated = false;
1721         for (unsigned i = 0; i != NumElts; ++i) {
1722           if (!DemandedElts[i] && !Ops[i].isUndef()) {
1723             Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
1724             KnownUndef.setBit(i);
1725             Updated = true;
1726           }
1727         }
1728         if (Updated)
1729           return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
1730       }
1731     }
1732     for (unsigned i = 0; i != NumElts; ++i) {
1733       SDValue SrcOp = Op.getOperand(i);
1734       if (SrcOp.isUndef()) {
1735         KnownUndef.setBit(i);
1736       } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
1737                  (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) {
1738         KnownZero.setBit(i);
1739       }
1740     }
1741     break;
1742   }
1743   case ISD::CONCAT_VECTORS: {
1744     EVT SubVT = Op.getOperand(0).getValueType();
1745     unsigned NumSubVecs = Op.getNumOperands();
1746     unsigned NumSubElts = SubVT.getVectorNumElements();
1747     for (unsigned i = 0; i != NumSubVecs; ++i) {
1748       SDValue SubOp = Op.getOperand(i);
1749       APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
1750       APInt SubUndef, SubZero;
1751       if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
1752                                      Depth + 1))
1753         return true;
1754       KnownUndef.insertBits(SubUndef, i * NumSubElts);
1755       KnownZero.insertBits(SubZero, i * NumSubElts);
1756     }
1757     break;
1758   }
1759   case ISD::INSERT_SUBVECTOR: {
1760     if (!isa<ConstantSDNode>(Op.getOperand(2)))
1761       break;
1762     SDValue Base = Op.getOperand(0);
1763     SDValue Sub = Op.getOperand(1);
1764     EVT SubVT = Sub.getValueType();
1765     unsigned NumSubElts = SubVT.getVectorNumElements();
1766     const APInt &Idx = Op.getConstantOperandAPInt(2);
1767     if (Idx.ugt(NumElts - NumSubElts))
1768       break;
1769     unsigned SubIdx = Idx.getZExtValue();
1770     APInt SubElts = DemandedElts.extractBits(NumSubElts, SubIdx);
1771     APInt SubUndef, SubZero;
1772     if (SimplifyDemandedVectorElts(Sub, SubElts, SubUndef, SubZero, TLO,
1773                                    Depth + 1))
1774       return true;
1775     APInt BaseElts = DemandedElts;
1776     BaseElts.insertBits(APInt::getNullValue(NumSubElts), SubIdx);
1777     if (SimplifyDemandedVectorElts(Base, BaseElts, KnownUndef, KnownZero, TLO,
1778                                    Depth + 1))
1779       return true;
1780     KnownUndef.insertBits(SubUndef, SubIdx);
1781     KnownZero.insertBits(SubZero, SubIdx);
1782     break;
1783   }
1784   case ISD::EXTRACT_SUBVECTOR: {
1785     SDValue Src = Op.getOperand(0);
1786     ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1787     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1788     if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
1789       // Offset the demanded elts by the subvector index.
1790       uint64_t Idx = SubIdx->getZExtValue();
1791       APInt SrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
1792       APInt SrcUndef, SrcZero;
1793       if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
1794                                      Depth + 1))
1795         return true;
1796       KnownUndef = SrcUndef.extractBits(NumElts, Idx);
1797       KnownZero = SrcZero.extractBits(NumElts, Idx);
1798     }
1799     break;
1800   }
1801   case ISD::INSERT_VECTOR_ELT: {
1802     SDValue Vec = Op.getOperand(0);
1803     SDValue Scl = Op.getOperand(1);
1804     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1805 
1806     // For a legal, constant insertion index, if we don't need this insertion
1807     // then strip it, else remove it from the demanded elts.
1808     if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
1809       unsigned Idx = CIdx->getZExtValue();
1810       if (!DemandedElts[Idx])
1811         return TLO.CombineTo(Op, Vec);
1812 
1813       APInt DemandedVecElts(DemandedElts);
1814       DemandedVecElts.clearBit(Idx);
1815       if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
1816                                      KnownZero, TLO, Depth + 1))
1817         return true;
1818 
1819       KnownUndef.clearBit(Idx);
1820       if (Scl.isUndef())
1821         KnownUndef.setBit(Idx);
1822 
1823       KnownZero.clearBit(Idx);
1824       if (isNullConstant(Scl) || isNullFPConstant(Scl))
1825         KnownZero.setBit(Idx);
1826       break;
1827     }
1828 
1829     APInt VecUndef, VecZero;
1830     if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
1831                                    Depth + 1))
1832       return true;
1833     // Without knowing the insertion index we can't set KnownUndef/KnownZero.
1834     break;
1835   }
1836   case ISD::VSELECT: {
1837     // Try to transform the select condition based on the current demanded
1838     // elements.
1839     // TODO: If a condition element is undef, we can choose from one arm of the
1840     //       select (and if one arm is undef, then we can propagate that to the
1841     //       result).
1842     // TODO - add support for constant vselect masks (see IR version of this).
1843     APInt UnusedUndef, UnusedZero;
1844     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UnusedUndef,
1845                                    UnusedZero, TLO, Depth + 1))
1846       return true;
1847 
1848     // See if we can simplify either vselect operand.
1849     APInt DemandedLHS(DemandedElts);
1850     APInt DemandedRHS(DemandedElts);
1851     APInt UndefLHS, ZeroLHS;
1852     APInt UndefRHS, ZeroRHS;
1853     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS,
1854                                    ZeroLHS, TLO, Depth + 1))
1855       return true;
1856     if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS,
1857                                    ZeroRHS, TLO, Depth + 1))
1858       return true;
1859 
1860     KnownUndef = UndefLHS & UndefRHS;
1861     KnownZero = ZeroLHS & ZeroRHS;
1862     break;
1863   }
1864   case ISD::VECTOR_SHUFFLE: {
1865     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1866 
1867     // Collect demanded elements from shuffle operands..
1868     APInt DemandedLHS(NumElts, 0);
1869     APInt DemandedRHS(NumElts, 0);
1870     for (unsigned i = 0; i != NumElts; ++i) {
1871       int M = ShuffleMask[i];
1872       if (M < 0 || !DemandedElts[i])
1873         continue;
1874       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
1875       if (M < (int)NumElts)
1876         DemandedLHS.setBit(M);
1877       else
1878         DemandedRHS.setBit(M - NumElts);
1879     }
1880 
1881     // See if we can simplify either shuffle operand.
1882     APInt UndefLHS, ZeroLHS;
1883     APInt UndefRHS, ZeroRHS;
1884     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS,
1885                                    ZeroLHS, TLO, Depth + 1))
1886       return true;
1887     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS,
1888                                    ZeroRHS, TLO, Depth + 1))
1889       return true;
1890 
1891     // Simplify mask using undef elements from LHS/RHS.
1892     bool Updated = false;
1893     bool IdentityLHS = true, IdentityRHS = true;
1894     SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end());
1895     for (unsigned i = 0; i != NumElts; ++i) {
1896       int &M = NewMask[i];
1897       if (M < 0)
1898         continue;
1899       if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
1900           (M >= (int)NumElts && UndefRHS[M - NumElts])) {
1901         Updated = true;
1902         M = -1;
1903       }
1904       IdentityLHS &= (M < 0) || (M == (int)i);
1905       IdentityRHS &= (M < 0) || ((M - NumElts) == i);
1906     }
1907 
1908     // Update legal shuffle masks based on demanded elements if it won't reduce
1909     // to Identity which can cause premature removal of the shuffle mask.
1910     if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps &&
1911         isShuffleMaskLegal(NewMask, VT))
1912       return TLO.CombineTo(Op,
1913                            TLO.DAG.getVectorShuffle(VT, DL, Op.getOperand(0),
1914                                                     Op.getOperand(1), NewMask));
1915 
1916     // Propagate undef/zero elements from LHS/RHS.
1917     for (unsigned i = 0; i != NumElts; ++i) {
1918       int M = ShuffleMask[i];
1919       if (M < 0) {
1920         KnownUndef.setBit(i);
1921       } else if (M < (int)NumElts) {
1922         if (UndefLHS[M])
1923           KnownUndef.setBit(i);
1924         if (ZeroLHS[M])
1925           KnownZero.setBit(i);
1926       } else {
1927         if (UndefRHS[M - NumElts])
1928           KnownUndef.setBit(i);
1929         if (ZeroRHS[M - NumElts])
1930           KnownZero.setBit(i);
1931       }
1932     }
1933     break;
1934   }
1935   case ISD::SIGN_EXTEND_VECTOR_INREG:
1936   case ISD::ZERO_EXTEND_VECTOR_INREG: {
1937     APInt SrcUndef, SrcZero;
1938     SDValue Src = Op.getOperand(0);
1939     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1940     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts);
1941     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
1942                                    Depth + 1))
1943       return true;
1944     KnownZero = SrcZero.zextOrTrunc(NumElts);
1945     KnownUndef = SrcUndef.zextOrTrunc(NumElts);
1946 
1947     if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
1948       // zext(undef) upper bits are guaranteed to be zero.
1949       if (DemandedElts.isSubsetOf(KnownUndef))
1950         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
1951       KnownUndef.clearAllBits();
1952     }
1953     break;
1954   }
1955 
1956   // TODO: There are more binop opcodes that could be handled here - MUL, MIN,
1957   // MAX, saturated math, etc.
1958   case ISD::OR:
1959   case ISD::XOR:
1960   case ISD::ADD:
1961   case ISD::SUB:
1962   case ISD::FADD:
1963   case ISD::FSUB:
1964   case ISD::FMUL:
1965   case ISD::FDIV:
1966   case ISD::FREM: {
1967     APInt UndefRHS, ZeroRHS;
1968     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, UndefRHS,
1969                                    ZeroRHS, TLO, Depth + 1))
1970       return true;
1971     APInt UndefLHS, ZeroLHS;
1972     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UndefLHS,
1973                                    ZeroLHS, TLO, Depth + 1))
1974       return true;
1975 
1976     KnownZero = ZeroLHS & ZeroRHS;
1977     KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
1978     break;
1979   }
1980   case ISD::AND: {
1981     APInt SrcUndef, SrcZero;
1982     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, SrcUndef,
1983                                    SrcZero, TLO, Depth + 1))
1984       return true;
1985     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
1986                                    KnownZero, TLO, Depth + 1))
1987       return true;
1988 
1989     // If either side has a zero element, then the result element is zero, even
1990     // if the other is an UNDEF.
1991     // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
1992     // and then handle 'and' nodes with the rest of the binop opcodes.
1993     KnownZero |= SrcZero;
1994     KnownUndef &= SrcUndef;
1995     KnownUndef &= ~KnownZero;
1996     break;
1997   }
1998   case ISD::TRUNCATE:
1999   case ISD::SIGN_EXTEND:
2000   case ISD::ZERO_EXTEND:
2001     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
2002                                    KnownZero, TLO, Depth + 1))
2003       return true;
2004 
2005     if (Op.getOpcode() == ISD::ZERO_EXTEND) {
2006       // zext(undef) upper bits are guaranteed to be zero.
2007       if (DemandedElts.isSubsetOf(KnownUndef))
2008         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
2009       KnownUndef.clearAllBits();
2010     }
2011     break;
2012   default: {
2013     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
2014       if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
2015                                                   KnownZero, TLO, Depth))
2016         return true;
2017     } else {
2018       KnownBits Known;
2019       APInt DemandedBits = APInt::getAllOnesValue(EltSizeInBits);
2020       if (SimplifyDemandedBits(Op, DemandedBits, DemandedEltMask, Known, TLO,
2021                                Depth, AssumeSingleUse))
2022         return true;
2023     }
2024     break;
2025   }
2026   }
2027   assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
2028 
2029   // Constant fold all undef cases.
2030   // TODO: Handle zero cases as well.
2031   if (DemandedElts.isSubsetOf(KnownUndef))
2032     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2033 
2034   return false;
2035 }
2036 
2037 /// Determine which of the bits specified in Mask are known to be either zero or
2038 /// one and return them in the Known.
2039 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
2040                                                    KnownBits &Known,
2041                                                    const APInt &DemandedElts,
2042                                                    const SelectionDAG &DAG,
2043                                                    unsigned Depth) const {
2044   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2045           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2046           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2047           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2048          "Should use MaskedValueIsZero if you don't know whether Op"
2049          " is a target node!");
2050   Known.resetAll();
2051 }
2052 
2053 void TargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
2054                                                    KnownBits &Known,
2055                                                    const APInt &DemandedElts,
2056                                                    const SelectionDAG &DAG,
2057                                                    unsigned Depth) const {
2058   assert(isa<FrameIndexSDNode>(Op) && "expected FrameIndex");
2059 
2060   if (unsigned Align = DAG.InferPtrAlignment(Op)) {
2061     // The low bits are known zero if the pointer is aligned.
2062     Known.Zero.setLowBits(Log2_32(Align));
2063   }
2064 }
2065 
2066 /// This method can be implemented by targets that want to expose additional
2067 /// information about sign bits to the DAG Combiner.
2068 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
2069                                                          const APInt &,
2070                                                          const SelectionDAG &,
2071                                                          unsigned Depth) const {
2072   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2073           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2074           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2075           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2076          "Should use ComputeNumSignBits if you don't know whether Op"
2077          " is a target node!");
2078   return 1;
2079 }
2080 
2081 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
2082     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
2083     TargetLoweringOpt &TLO, unsigned Depth) const {
2084   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2085           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2086           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2087           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2088          "Should use SimplifyDemandedVectorElts if you don't know whether Op"
2089          " is a target node!");
2090   return false;
2091 }
2092 
2093 bool TargetLowering::SimplifyDemandedBitsForTargetNode(
2094     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
2095     KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
2096   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2097           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2098           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2099           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2100          "Should use SimplifyDemandedBits if you don't know whether Op"
2101          " is a target node!");
2102   computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
2103   return false;
2104 }
2105 
2106 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
2107                                                   const SelectionDAG &DAG,
2108                                                   bool SNaN,
2109                                                   unsigned Depth) const {
2110   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2111           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2112           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2113           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2114          "Should use isKnownNeverNaN if you don't know whether Op"
2115          " is a target node!");
2116   return false;
2117 }
2118 
2119 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
2120 // work with truncating build vectors and vectors with elements of less than
2121 // 8 bits.
2122 bool TargetLowering::isConstTrueVal(const SDNode *N) const {
2123   if (!N)
2124     return false;
2125 
2126   APInt CVal;
2127   if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
2128     CVal = CN->getAPIntValue();
2129   } else if (auto *BV = dyn_cast<BuildVectorSDNode>(N)) {
2130     auto *CN = BV->getConstantSplatNode();
2131     if (!CN)
2132       return false;
2133 
2134     // If this is a truncating build vector, truncate the splat value.
2135     // Otherwise, we may fail to match the expected values below.
2136     unsigned BVEltWidth = BV->getValueType(0).getScalarSizeInBits();
2137     CVal = CN->getAPIntValue();
2138     if (BVEltWidth < CVal.getBitWidth())
2139       CVal = CVal.trunc(BVEltWidth);
2140   } else {
2141     return false;
2142   }
2143 
2144   switch (getBooleanContents(N->getValueType(0))) {
2145   case UndefinedBooleanContent:
2146     return CVal[0];
2147   case ZeroOrOneBooleanContent:
2148     return CVal.isOneValue();
2149   case ZeroOrNegativeOneBooleanContent:
2150     return CVal.isAllOnesValue();
2151   }
2152 
2153   llvm_unreachable("Invalid boolean contents");
2154 }
2155 
2156 bool TargetLowering::isConstFalseVal(const SDNode *N) const {
2157   if (!N)
2158     return false;
2159 
2160   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
2161   if (!CN) {
2162     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
2163     if (!BV)
2164       return false;
2165 
2166     // Only interested in constant splats, we don't care about undef
2167     // elements in identifying boolean constants and getConstantSplatNode
2168     // returns NULL if all ops are undef;
2169     CN = BV->getConstantSplatNode();
2170     if (!CN)
2171       return false;
2172   }
2173 
2174   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
2175     return !CN->getAPIntValue()[0];
2176 
2177   return CN->isNullValue();
2178 }
2179 
2180 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
2181                                        bool SExt) const {
2182   if (VT == MVT::i1)
2183     return N->isOne();
2184 
2185   TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
2186   switch (Cnt) {
2187   case TargetLowering::ZeroOrOneBooleanContent:
2188     // An extended value of 1 is always true, unless its original type is i1,
2189     // in which case it will be sign extended to -1.
2190     return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
2191   case TargetLowering::UndefinedBooleanContent:
2192   case TargetLowering::ZeroOrNegativeOneBooleanContent:
2193     return N->isAllOnesValue() && SExt;
2194   }
2195   llvm_unreachable("Unexpected enumeration.");
2196 }
2197 
2198 /// This helper function of SimplifySetCC tries to optimize the comparison when
2199 /// either operand of the SetCC node is a bitwise-and instruction.
2200 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
2201                                          ISD::CondCode Cond, const SDLoc &DL,
2202                                          DAGCombinerInfo &DCI) const {
2203   // Match these patterns in any of their permutations:
2204   // (X & Y) == Y
2205   // (X & Y) != Y
2206   if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
2207     std::swap(N0, N1);
2208 
2209   EVT OpVT = N0.getValueType();
2210   if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
2211       (Cond != ISD::SETEQ && Cond != ISD::SETNE))
2212     return SDValue();
2213 
2214   SDValue X, Y;
2215   if (N0.getOperand(0) == N1) {
2216     X = N0.getOperand(1);
2217     Y = N0.getOperand(0);
2218   } else if (N0.getOperand(1) == N1) {
2219     X = N0.getOperand(0);
2220     Y = N0.getOperand(1);
2221   } else {
2222     return SDValue();
2223   }
2224 
2225   SelectionDAG &DAG = DCI.DAG;
2226   SDValue Zero = DAG.getConstant(0, DL, OpVT);
2227   if (DAG.isKnownToBeAPowerOfTwo(Y)) {
2228     // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
2229     // Note that where Y is variable and is known to have at most one bit set
2230     // (for example, if it is Z & 1) we cannot do this; the expressions are not
2231     // equivalent when Y == 0.
2232     Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
2233     if (DCI.isBeforeLegalizeOps() ||
2234         isCondCodeLegal(Cond, N0.getSimpleValueType()))
2235       return DAG.getSetCC(DL, VT, N0, Zero, Cond);
2236   } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
2237     // If the target supports an 'and-not' or 'and-complement' logic operation,
2238     // try to use that to make a comparison operation more efficient.
2239     // But don't do this transform if the mask is a single bit because there are
2240     // more efficient ways to deal with that case (for example, 'bt' on x86 or
2241     // 'rlwinm' on PPC).
2242 
2243     // Bail out if the compare operand that we want to turn into a zero is
2244     // already a zero (otherwise, infinite loop).
2245     auto *YConst = dyn_cast<ConstantSDNode>(Y);
2246     if (YConst && YConst->isNullValue())
2247       return SDValue();
2248 
2249     // Transform this into: ~X & Y == 0.
2250     SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
2251     SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
2252     return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
2253   }
2254 
2255   return SDValue();
2256 }
2257 
2258 /// There are multiple IR patterns that could be checking whether certain
2259 /// truncation of a signed number would be lossy or not. The pattern which is
2260 /// best at IR level, may not lower optimally. Thus, we want to unfold it.
2261 /// We are looking for the following pattern: (KeptBits is a constant)
2262 ///   (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
2263 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
2264 /// KeptBits also can't be 1, that would have been folded to  %x dstcond 0
2265 /// We will unfold it into the natural trunc+sext pattern:
2266 ///   ((%x << C) a>> C) dstcond %x
2267 /// Where  C = bitwidth(x) - KeptBits  and  C u< bitwidth(x)
2268 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
2269     EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
2270     const SDLoc &DL) const {
2271   // We must be comparing with a constant.
2272   ConstantSDNode *C1;
2273   if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
2274     return SDValue();
2275 
2276   // N0 should be:  add %x, (1 << (KeptBits-1))
2277   if (N0->getOpcode() != ISD::ADD)
2278     return SDValue();
2279 
2280   // And we must be 'add'ing a constant.
2281   ConstantSDNode *C01;
2282   if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
2283     return SDValue();
2284 
2285   SDValue X = N0->getOperand(0);
2286   EVT XVT = X.getValueType();
2287 
2288   // Validate constants ...
2289 
2290   APInt I1 = C1->getAPIntValue();
2291 
2292   ISD::CondCode NewCond;
2293   if (Cond == ISD::CondCode::SETULT) {
2294     NewCond = ISD::CondCode::SETEQ;
2295   } else if (Cond == ISD::CondCode::SETULE) {
2296     NewCond = ISD::CondCode::SETEQ;
2297     // But need to 'canonicalize' the constant.
2298     I1 += 1;
2299   } else if (Cond == ISD::CondCode::SETUGT) {
2300     NewCond = ISD::CondCode::SETNE;
2301     // But need to 'canonicalize' the constant.
2302     I1 += 1;
2303   } else if (Cond == ISD::CondCode::SETUGE) {
2304     NewCond = ISD::CondCode::SETNE;
2305   } else
2306     return SDValue();
2307 
2308   APInt I01 = C01->getAPIntValue();
2309 
2310   auto checkConstants = [&I1, &I01]() -> bool {
2311     // Both of them must be power-of-two, and the constant from setcc is bigger.
2312     return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
2313   };
2314 
2315   if (checkConstants()) {
2316     // Great, e.g. got  icmp ult i16 (add i16 %x, 128), 256
2317   } else {
2318     // What if we invert constants? (and the target predicate)
2319     I1.negate();
2320     I01.negate();
2321     NewCond = getSetCCInverse(NewCond, /*isInteger=*/true);
2322     if (!checkConstants())
2323       return SDValue();
2324     // Great, e.g. got  icmp uge i16 (add i16 %x, -128), -256
2325   }
2326 
2327   // They are power-of-two, so which bit is set?
2328   const unsigned KeptBits = I1.logBase2();
2329   const unsigned KeptBitsMinusOne = I01.logBase2();
2330 
2331   // Magic!
2332   if (KeptBits != (KeptBitsMinusOne + 1))
2333     return SDValue();
2334   assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
2335 
2336   // We don't want to do this in every single case.
2337   SelectionDAG &DAG = DCI.DAG;
2338   if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck(
2339           XVT, KeptBits))
2340     return SDValue();
2341 
2342   const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits;
2343   assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable");
2344 
2345   // Unfold into:  ((%x << C) a>> C) cond %x
2346   // Where 'cond' will be either 'eq' or 'ne'.
2347   SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT);
2348   SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt);
2349   SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt);
2350   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond);
2351 
2352   return T2;
2353 }
2354 
2355 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as
2356 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
2357 /// handle the commuted versions of these patterns.
2358 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
2359                                            ISD::CondCode Cond, const SDLoc &DL,
2360                                            DAGCombinerInfo &DCI) const {
2361   unsigned BOpcode = N0.getOpcode();
2362   assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
2363          "Unexpected binop");
2364   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
2365 
2366   // (X + Y) == X --> Y == 0
2367   // (X - Y) == X --> Y == 0
2368   // (X ^ Y) == X --> Y == 0
2369   SelectionDAG &DAG = DCI.DAG;
2370   EVT OpVT = N0.getValueType();
2371   SDValue X = N0.getOperand(0);
2372   SDValue Y = N0.getOperand(1);
2373   if (X == N1)
2374     return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
2375 
2376   if (Y != N1)
2377     return SDValue();
2378 
2379   // (X + Y) == Y --> X == 0
2380   // (X ^ Y) == Y --> X == 0
2381   if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
2382     return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
2383 
2384   // The shift would not be valid if the operands are boolean (i1).
2385   if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
2386     return SDValue();
2387 
2388   // (X - Y) == Y --> X == Y << 1
2389   EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(),
2390                                  !DCI.isBeforeLegalize());
2391   SDValue One = DAG.getConstant(1, DL, ShiftVT);
2392   SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
2393   if (!DCI.isCalledByLegalizer())
2394     DCI.AddToWorklist(YShl1.getNode());
2395   return DAG.getSetCC(DL, VT, X, YShl1, Cond);
2396 }
2397 
2398 /// Try to simplify a setcc built with the specified operands and cc. If it is
2399 /// unable to simplify it, return a null SDValue.
2400 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
2401                                       ISD::CondCode Cond, bool foldBooleans,
2402                                       DAGCombinerInfo &DCI,
2403                                       const SDLoc &dl) const {
2404   SelectionDAG &DAG = DCI.DAG;
2405   EVT OpVT = N0.getValueType();
2406 
2407   // Constant fold or commute setcc.
2408   if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
2409     return Fold;
2410 
2411   // Ensure that the constant occurs on the RHS and fold constant comparisons.
2412   // TODO: Handle non-splat vector constants. All undef causes trouble.
2413   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
2414   if (isConstOrConstSplat(N0) &&
2415       (DCI.isBeforeLegalizeOps() ||
2416        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
2417     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
2418 
2419   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
2420     const APInt &C1 = N1C->getAPIntValue();
2421 
2422     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
2423     // equality comparison, then we're just comparing whether X itself is
2424     // zero.
2425     if (N0.getOpcode() == ISD::SRL && (C1.isNullValue() || C1.isOneValue()) &&
2426         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
2427         N0.getOperand(1).getOpcode() == ISD::Constant) {
2428       const APInt &ShAmt = N0.getConstantOperandAPInt(1);
2429       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2430           ShAmt == Log2_32(N0.getValueSizeInBits())) {
2431         if ((C1 == 0) == (Cond == ISD::SETEQ)) {
2432           // (srl (ctlz x), 5) == 0  -> X != 0
2433           // (srl (ctlz x), 5) != 1  -> X != 0
2434           Cond = ISD::SETNE;
2435         } else {
2436           // (srl (ctlz x), 5) != 0  -> X == 0
2437           // (srl (ctlz x), 5) == 1  -> X == 0
2438           Cond = ISD::SETEQ;
2439         }
2440         SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
2441         return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
2442                             Zero, Cond);
2443       }
2444     }
2445 
2446     SDValue CTPOP = N0;
2447     // Look through truncs that don't change the value of a ctpop.
2448     if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
2449       CTPOP = N0.getOperand(0);
2450 
2451     if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
2452         (N0 == CTPOP ||
2453          N0.getValueSizeInBits() > Log2_32_Ceil(CTPOP.getValueSizeInBits()))) {
2454       EVT CTVT = CTPOP.getValueType();
2455       SDValue CTOp = CTPOP.getOperand(0);
2456 
2457       // (ctpop x) u< 2 -> (x & x-1) == 0
2458       // (ctpop x) u> 1 -> (x & x-1) != 0
2459       if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
2460         SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
2461                                   DAG.getConstant(1, dl, CTVT));
2462         SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
2463         ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
2464         return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC);
2465       }
2466 
2467       // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
2468     }
2469 
2470     // (zext x) == C --> x == (trunc C)
2471     // (sext x) == C --> x == (trunc C)
2472     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2473         DCI.isBeforeLegalize() && N0->hasOneUse()) {
2474       unsigned MinBits = N0.getValueSizeInBits();
2475       SDValue PreExt;
2476       bool Signed = false;
2477       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
2478         // ZExt
2479         MinBits = N0->getOperand(0).getValueSizeInBits();
2480         PreExt = N0->getOperand(0);
2481       } else if (N0->getOpcode() == ISD::AND) {
2482         // DAGCombine turns costly ZExts into ANDs
2483         if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
2484           if ((C->getAPIntValue()+1).isPowerOf2()) {
2485             MinBits = C->getAPIntValue().countTrailingOnes();
2486             PreExt = N0->getOperand(0);
2487           }
2488       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
2489         // SExt
2490         MinBits = N0->getOperand(0).getValueSizeInBits();
2491         PreExt = N0->getOperand(0);
2492         Signed = true;
2493       } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
2494         // ZEXTLOAD / SEXTLOAD
2495         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
2496           MinBits = LN0->getMemoryVT().getSizeInBits();
2497           PreExt = N0;
2498         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
2499           Signed = true;
2500           MinBits = LN0->getMemoryVT().getSizeInBits();
2501           PreExt = N0;
2502         }
2503       }
2504 
2505       // Figure out how many bits we need to preserve this constant.
2506       unsigned ReqdBits = Signed ?
2507         C1.getBitWidth() - C1.getNumSignBits() + 1 :
2508         C1.getActiveBits();
2509 
2510       // Make sure we're not losing bits from the constant.
2511       if (MinBits > 0 &&
2512           MinBits < C1.getBitWidth() &&
2513           MinBits >= ReqdBits) {
2514         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
2515         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
2516           // Will get folded away.
2517           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
2518           if (MinBits == 1 && C1 == 1)
2519             // Invert the condition.
2520             return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
2521                                 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
2522           SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
2523           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
2524         }
2525 
2526         // If truncating the setcc operands is not desirable, we can still
2527         // simplify the expression in some cases:
2528         // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
2529         // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
2530         // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
2531         // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
2532         // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
2533         // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
2534         SDValue TopSetCC = N0->getOperand(0);
2535         unsigned N0Opc = N0->getOpcode();
2536         bool SExt = (N0Opc == ISD::SIGN_EXTEND);
2537         if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
2538             TopSetCC.getOpcode() == ISD::SETCC &&
2539             (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
2540             (isConstFalseVal(N1C) ||
2541              isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
2542 
2543           bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) ||
2544                          (!N1C->isNullValue() && Cond == ISD::SETNE);
2545 
2546           if (!Inverse)
2547             return TopSetCC;
2548 
2549           ISD::CondCode InvCond = ISD::getSetCCInverse(
2550               cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
2551               TopSetCC.getOperand(0).getValueType().isInteger());
2552           return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
2553                                       TopSetCC.getOperand(1),
2554                                       InvCond);
2555         }
2556       }
2557     }
2558 
2559     // If the LHS is '(and load, const)', the RHS is 0, the test is for
2560     // equality or unsigned, and all 1 bits of the const are in the same
2561     // partial word, see if we can shorten the load.
2562     if (DCI.isBeforeLegalize() &&
2563         !ISD::isSignedIntSetCC(Cond) &&
2564         N0.getOpcode() == ISD::AND && C1 == 0 &&
2565         N0.getNode()->hasOneUse() &&
2566         isa<LoadSDNode>(N0.getOperand(0)) &&
2567         N0.getOperand(0).getNode()->hasOneUse() &&
2568         isa<ConstantSDNode>(N0.getOperand(1))) {
2569       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
2570       APInt bestMask;
2571       unsigned bestWidth = 0, bestOffset = 0;
2572       if (!Lod->isVolatile() && Lod->isUnindexed()) {
2573         unsigned origWidth = N0.getValueSizeInBits();
2574         unsigned maskWidth = origWidth;
2575         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
2576         // 8 bits, but have to be careful...
2577         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
2578           origWidth = Lod->getMemoryVT().getSizeInBits();
2579         const APInt &Mask = N0.getConstantOperandAPInt(1);
2580         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
2581           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
2582           for (unsigned offset=0; offset<origWidth/width; offset++) {
2583             if (Mask.isSubsetOf(newMask)) {
2584               if (DAG.getDataLayout().isLittleEndian())
2585                 bestOffset = (uint64_t)offset * (width/8);
2586               else
2587                 bestOffset = (origWidth/width - offset - 1) * (width/8);
2588               bestMask = Mask.lshr(offset * (width/8) * 8);
2589               bestWidth = width;
2590               break;
2591             }
2592             newMask <<= width;
2593           }
2594         }
2595       }
2596       if (bestWidth) {
2597         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
2598         if (newVT.isRound() &&
2599             shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) {
2600           EVT PtrType = Lod->getOperand(1).getValueType();
2601           SDValue Ptr = Lod->getBasePtr();
2602           if (bestOffset != 0)
2603             Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
2604                               DAG.getConstant(bestOffset, dl, PtrType));
2605           unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
2606           SDValue NewLoad = DAG.getLoad(
2607               newVT, dl, Lod->getChain(), Ptr,
2608               Lod->getPointerInfo().getWithOffset(bestOffset), NewAlign);
2609           return DAG.getSetCC(dl, VT,
2610                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
2611                                       DAG.getConstant(bestMask.trunc(bestWidth),
2612                                                       dl, newVT)),
2613                               DAG.getConstant(0LL, dl, newVT), Cond);
2614         }
2615       }
2616     }
2617 
2618     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
2619     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
2620       unsigned InSize = N0.getOperand(0).getValueSizeInBits();
2621 
2622       // If the comparison constant has bits in the upper part, the
2623       // zero-extended value could never match.
2624       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
2625                                               C1.getBitWidth() - InSize))) {
2626         switch (Cond) {
2627         case ISD::SETUGT:
2628         case ISD::SETUGE:
2629         case ISD::SETEQ:
2630           return DAG.getConstant(0, dl, VT);
2631         case ISD::SETULT:
2632         case ISD::SETULE:
2633         case ISD::SETNE:
2634           return DAG.getConstant(1, dl, VT);
2635         case ISD::SETGT:
2636         case ISD::SETGE:
2637           // True if the sign bit of C1 is set.
2638           return DAG.getConstant(C1.isNegative(), dl, VT);
2639         case ISD::SETLT:
2640         case ISD::SETLE:
2641           // True if the sign bit of C1 isn't set.
2642           return DAG.getConstant(C1.isNonNegative(), dl, VT);
2643         default:
2644           break;
2645         }
2646       }
2647 
2648       // Otherwise, we can perform the comparison with the low bits.
2649       switch (Cond) {
2650       case ISD::SETEQ:
2651       case ISD::SETNE:
2652       case ISD::SETUGT:
2653       case ISD::SETUGE:
2654       case ISD::SETULT:
2655       case ISD::SETULE: {
2656         EVT newVT = N0.getOperand(0).getValueType();
2657         if (DCI.isBeforeLegalizeOps() ||
2658             (isOperationLegal(ISD::SETCC, newVT) &&
2659              isCondCodeLegal(Cond, newVT.getSimpleVT()))) {
2660           EVT NewSetCCVT =
2661               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT);
2662           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
2663 
2664           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
2665                                           NewConst, Cond);
2666           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
2667         }
2668         break;
2669       }
2670       default:
2671         break; // todo, be more careful with signed comparisons
2672       }
2673     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2674                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
2675       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
2676       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
2677       EVT ExtDstTy = N0.getValueType();
2678       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
2679 
2680       // If the constant doesn't fit into the number of bits for the source of
2681       // the sign extension, it is impossible for both sides to be equal.
2682       if (C1.getMinSignedBits() > ExtSrcTyBits)
2683         return DAG.getConstant(Cond == ISD::SETNE, dl, VT);
2684 
2685       SDValue ZextOp;
2686       EVT Op0Ty = N0.getOperand(0).getValueType();
2687       if (Op0Ty == ExtSrcTy) {
2688         ZextOp = N0.getOperand(0);
2689       } else {
2690         APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
2691         ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
2692                              DAG.getConstant(Imm, dl, Op0Ty));
2693       }
2694       if (!DCI.isCalledByLegalizer())
2695         DCI.AddToWorklist(ZextOp.getNode());
2696       // Otherwise, make this a use of a zext.
2697       return DAG.getSetCC(dl, VT, ZextOp,
2698                           DAG.getConstant(C1 & APInt::getLowBitsSet(
2699                                                               ExtDstTyBits,
2700                                                               ExtSrcTyBits),
2701                                           dl, ExtDstTy),
2702                           Cond);
2703     } else if ((N1C->isNullValue() || N1C->isOne()) &&
2704                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
2705       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
2706       if (N0.getOpcode() == ISD::SETCC &&
2707           isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
2708         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
2709         if (TrueWhenTrue)
2710           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
2711         // Invert the condition.
2712         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
2713         CC = ISD::getSetCCInverse(CC,
2714                                   N0.getOperand(0).getValueType().isInteger());
2715         if (DCI.isBeforeLegalizeOps() ||
2716             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
2717           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
2718       }
2719 
2720       if ((N0.getOpcode() == ISD::XOR ||
2721            (N0.getOpcode() == ISD::AND &&
2722             N0.getOperand(0).getOpcode() == ISD::XOR &&
2723             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
2724           isa<ConstantSDNode>(N0.getOperand(1)) &&
2725           cast<ConstantSDNode>(N0.getOperand(1))->isOne()) {
2726         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
2727         // can only do this if the top bits are known zero.
2728         unsigned BitWidth = N0.getValueSizeInBits();
2729         if (DAG.MaskedValueIsZero(N0,
2730                                   APInt::getHighBitsSet(BitWidth,
2731                                                         BitWidth-1))) {
2732           // Okay, get the un-inverted input value.
2733           SDValue Val;
2734           if (N0.getOpcode() == ISD::XOR) {
2735             Val = N0.getOperand(0);
2736           } else {
2737             assert(N0.getOpcode() == ISD::AND &&
2738                     N0.getOperand(0).getOpcode() == ISD::XOR);
2739             // ((X^1)&1)^1 -> X & 1
2740             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
2741                               N0.getOperand(0).getOperand(0),
2742                               N0.getOperand(1));
2743           }
2744 
2745           return DAG.getSetCC(dl, VT, Val, N1,
2746                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
2747         }
2748       } else if (N1C->isOne() &&
2749                  (VT == MVT::i1 ||
2750                   getBooleanContents(N0->getValueType(0)) ==
2751                       ZeroOrOneBooleanContent)) {
2752         SDValue Op0 = N0;
2753         if (Op0.getOpcode() == ISD::TRUNCATE)
2754           Op0 = Op0.getOperand(0);
2755 
2756         if ((Op0.getOpcode() == ISD::XOR) &&
2757             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
2758             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
2759           // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
2760           Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
2761           return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
2762                               Cond);
2763         }
2764         if (Op0.getOpcode() == ISD::AND &&
2765             isa<ConstantSDNode>(Op0.getOperand(1)) &&
2766             cast<ConstantSDNode>(Op0.getOperand(1))->isOne()) {
2767           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
2768           if (Op0.getValueType().bitsGT(VT))
2769             Op0 = DAG.getNode(ISD::AND, dl, VT,
2770                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
2771                           DAG.getConstant(1, dl, VT));
2772           else if (Op0.getValueType().bitsLT(VT))
2773             Op0 = DAG.getNode(ISD::AND, dl, VT,
2774                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
2775                         DAG.getConstant(1, dl, VT));
2776 
2777           return DAG.getSetCC(dl, VT, Op0,
2778                               DAG.getConstant(0, dl, Op0.getValueType()),
2779                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
2780         }
2781         if (Op0.getOpcode() == ISD::AssertZext &&
2782             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
2783           return DAG.getSetCC(dl, VT, Op0,
2784                               DAG.getConstant(0, dl, Op0.getValueType()),
2785                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
2786       }
2787     }
2788 
2789     if (SDValue V =
2790             optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
2791       return V;
2792   }
2793 
2794   // These simplifications apply to splat vectors as well.
2795   // TODO: Handle more splat vector cases.
2796   if (auto *N1C = isConstOrConstSplat(N1)) {
2797     const APInt &C1 = N1C->getAPIntValue();
2798 
2799     APInt MinVal, MaxVal;
2800     unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
2801     if (ISD::isSignedIntSetCC(Cond)) {
2802       MinVal = APInt::getSignedMinValue(OperandBitSize);
2803       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
2804     } else {
2805       MinVal = APInt::getMinValue(OperandBitSize);
2806       MaxVal = APInt::getMaxValue(OperandBitSize);
2807     }
2808 
2809     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
2810     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
2811       // X >= MIN --> true
2812       if (C1 == MinVal)
2813         return DAG.getBoolConstant(true, dl, VT, OpVT);
2814 
2815       if (!VT.isVector()) { // TODO: Support this for vectors.
2816         // X >= C0 --> X > (C0 - 1)
2817         APInt C = C1 - 1;
2818         ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
2819         if ((DCI.isBeforeLegalizeOps() ||
2820              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
2821             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
2822                                   isLegalICmpImmediate(C.getSExtValue())))) {
2823           return DAG.getSetCC(dl, VT, N0,
2824                               DAG.getConstant(C, dl, N1.getValueType()),
2825                               NewCC);
2826         }
2827       }
2828     }
2829 
2830     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
2831       // X <= MAX --> true
2832       if (C1 == MaxVal)
2833         return DAG.getBoolConstant(true, dl, VT, OpVT);
2834 
2835       // X <= C0 --> X < (C0 + 1)
2836       if (!VT.isVector()) { // TODO: Support this for vectors.
2837         APInt C = C1 + 1;
2838         ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
2839         if ((DCI.isBeforeLegalizeOps() ||
2840              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
2841             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
2842                                   isLegalICmpImmediate(C.getSExtValue())))) {
2843           return DAG.getSetCC(dl, VT, N0,
2844                               DAG.getConstant(C, dl, N1.getValueType()),
2845                               NewCC);
2846         }
2847       }
2848     }
2849 
2850     if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
2851       if (C1 == MinVal)
2852         return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
2853 
2854       // TODO: Support this for vectors after legalize ops.
2855       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
2856         // Canonicalize setlt X, Max --> setne X, Max
2857         if (C1 == MaxVal)
2858           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
2859 
2860         // If we have setult X, 1, turn it into seteq X, 0
2861         if (C1 == MinVal+1)
2862           return DAG.getSetCC(dl, VT, N0,
2863                               DAG.getConstant(MinVal, dl, N0.getValueType()),
2864                               ISD::SETEQ);
2865       }
2866     }
2867 
2868     if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
2869       if (C1 == MaxVal)
2870         return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
2871 
2872       // TODO: Support this for vectors after legalize ops.
2873       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
2874         // Canonicalize setgt X, Min --> setne X, Min
2875         if (C1 == MinVal)
2876           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
2877 
2878         // If we have setugt X, Max-1, turn it into seteq X, Max
2879         if (C1 == MaxVal-1)
2880           return DAG.getSetCC(dl, VT, N0,
2881                               DAG.getConstant(MaxVal, dl, N0.getValueType()),
2882                               ISD::SETEQ);
2883       }
2884     }
2885 
2886     // If we have "setcc X, C0", check to see if we can shrink the immediate
2887     // by changing cc.
2888     // TODO: Support this for vectors after legalize ops.
2889     if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
2890       // SETUGT X, SINTMAX  -> SETLT X, 0
2891       if (Cond == ISD::SETUGT &&
2892           C1 == APInt::getSignedMaxValue(OperandBitSize))
2893         return DAG.getSetCC(dl, VT, N0,
2894                             DAG.getConstant(0, dl, N1.getValueType()),
2895                             ISD::SETLT);
2896 
2897       // SETULT X, SINTMIN  -> SETGT X, -1
2898       if (Cond == ISD::SETULT &&
2899           C1 == APInt::getSignedMinValue(OperandBitSize)) {
2900         SDValue ConstMinusOne =
2901             DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl,
2902                             N1.getValueType());
2903         return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
2904       }
2905     }
2906   }
2907 
2908   // Back to non-vector simplifications.
2909   // TODO: Can we do these for vector splats?
2910   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
2911     const APInt &C1 = N1C->getAPIntValue();
2912 
2913     // Fold bit comparisons when we can.
2914     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2915         (VT == N0.getValueType() ||
2916          (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
2917         N0.getOpcode() == ISD::AND) {
2918       auto &DL = DAG.getDataLayout();
2919       if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2920         EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL,
2921                                        !DCI.isBeforeLegalize());
2922         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
2923           // Perform the xform if the AND RHS is a single bit.
2924           if (AndRHS->getAPIntValue().isPowerOf2()) {
2925             return DAG.getNode(ISD::TRUNCATE, dl, VT,
2926                               DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
2927                    DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl,
2928                                    ShiftTy)));
2929           }
2930         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
2931           // (X & 8) == 8  -->  (X & 8) >> 3
2932           // Perform the xform if C1 is a single bit.
2933           if (C1.isPowerOf2()) {
2934             return DAG.getNode(ISD::TRUNCATE, dl, VT,
2935                                DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
2936                                       DAG.getConstant(C1.logBase2(), dl,
2937                                                       ShiftTy)));
2938           }
2939         }
2940       }
2941     }
2942 
2943     if (C1.getMinSignedBits() <= 64 &&
2944         !isLegalICmpImmediate(C1.getSExtValue())) {
2945       // (X & -256) == 256 -> (X >> 8) == 1
2946       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2947           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
2948         if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2949           const APInt &AndRHSC = AndRHS->getAPIntValue();
2950           if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
2951             unsigned ShiftBits = AndRHSC.countTrailingZeros();
2952             auto &DL = DAG.getDataLayout();
2953             EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL,
2954                                            !DCI.isBeforeLegalize());
2955             EVT CmpTy = N0.getValueType();
2956             SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
2957                                         DAG.getConstant(ShiftBits, dl,
2958                                                         ShiftTy));
2959             SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy);
2960             return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
2961           }
2962         }
2963       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
2964                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
2965         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
2966         // X <  0x100000000 -> (X >> 32) <  1
2967         // X >= 0x100000000 -> (X >> 32) >= 1
2968         // X <= 0x0ffffffff -> (X >> 32) <  1
2969         // X >  0x0ffffffff -> (X >> 32) >= 1
2970         unsigned ShiftBits;
2971         APInt NewC = C1;
2972         ISD::CondCode NewCond = Cond;
2973         if (AdjOne) {
2974           ShiftBits = C1.countTrailingOnes();
2975           NewC = NewC + 1;
2976           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2977         } else {
2978           ShiftBits = C1.countTrailingZeros();
2979         }
2980         NewC.lshrInPlace(ShiftBits);
2981         if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
2982           isLegalICmpImmediate(NewC.getSExtValue())) {
2983           auto &DL = DAG.getDataLayout();
2984           EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL,
2985                                          !DCI.isBeforeLegalize());
2986           EVT CmpTy = N0.getValueType();
2987           SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
2988                                       DAG.getConstant(ShiftBits, dl, ShiftTy));
2989           SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy);
2990           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
2991         }
2992       }
2993     }
2994   }
2995 
2996   if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) {
2997     auto *CFP = cast<ConstantFPSDNode>(N1);
2998     assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
2999 
3000     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
3001     // constant if knowing that the operand is non-nan is enough.  We prefer to
3002     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
3003     // materialize 0.0.
3004     if (Cond == ISD::SETO || Cond == ISD::SETUO)
3005       return DAG.getSetCC(dl, VT, N0, N0, Cond);
3006 
3007     // setcc (fneg x), C -> setcc swap(pred) x, -C
3008     if (N0.getOpcode() == ISD::FNEG) {
3009       ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond);
3010       if (DCI.isBeforeLegalizeOps() ||
3011           isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
3012         SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
3013         return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
3014       }
3015     }
3016 
3017     // If the condition is not legal, see if we can find an equivalent one
3018     // which is legal.
3019     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
3020       // If the comparison was an awkward floating-point == or != and one of
3021       // the comparison operands is infinity or negative infinity, convert the
3022       // condition to a less-awkward <= or >=.
3023       if (CFP->getValueAPF().isInfinity()) {
3024         if (CFP->getValueAPF().isNegative()) {
3025           if (Cond == ISD::SETOEQ &&
3026               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
3027             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
3028           if (Cond == ISD::SETUEQ &&
3029               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
3030             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
3031           if (Cond == ISD::SETUNE &&
3032               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
3033             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
3034           if (Cond == ISD::SETONE &&
3035               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
3036             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
3037         } else {
3038           if (Cond == ISD::SETOEQ &&
3039               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
3040             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
3041           if (Cond == ISD::SETUEQ &&
3042               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
3043             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
3044           if (Cond == ISD::SETUNE &&
3045               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
3046             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
3047           if (Cond == ISD::SETONE &&
3048               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
3049             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
3050         }
3051       }
3052     }
3053   }
3054 
3055   if (N0 == N1) {
3056     // The sext(setcc()) => setcc() optimization relies on the appropriate
3057     // constant being emitted.
3058     assert(!N0.getValueType().isInteger() &&
3059            "Integer types should be handled by FoldSetCC");
3060 
3061     bool EqTrue = ISD::isTrueWhenEqual(Cond);
3062     unsigned UOF = ISD::getUnorderedFlavor(Cond);
3063     if (UOF == 2) // FP operators that are undefined on NaNs.
3064       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
3065     if (UOF == unsigned(EqTrue))
3066       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
3067     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
3068     // if it is not already.
3069     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
3070     if (NewCond != Cond &&
3071         (DCI.isBeforeLegalizeOps() ||
3072                             isCondCodeLegal(NewCond, N0.getSimpleValueType())))
3073       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
3074   }
3075 
3076   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3077       N0.getValueType().isInteger()) {
3078     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
3079         N0.getOpcode() == ISD::XOR) {
3080       // Simplify (X+Y) == (X+Z) -->  Y == Z
3081       if (N0.getOpcode() == N1.getOpcode()) {
3082         if (N0.getOperand(0) == N1.getOperand(0))
3083           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
3084         if (N0.getOperand(1) == N1.getOperand(1))
3085           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
3086         if (isCommutativeBinOp(N0.getOpcode())) {
3087           // If X op Y == Y op X, try other combinations.
3088           if (N0.getOperand(0) == N1.getOperand(1))
3089             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
3090                                 Cond);
3091           if (N0.getOperand(1) == N1.getOperand(0))
3092             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
3093                                 Cond);
3094         }
3095       }
3096 
3097       // If RHS is a legal immediate value for a compare instruction, we need
3098       // to be careful about increasing register pressure needlessly.
3099       bool LegalRHSImm = false;
3100 
3101       if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
3102         if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3103           // Turn (X+C1) == C2 --> X == C2-C1
3104           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
3105             return DAG.getSetCC(dl, VT, N0.getOperand(0),
3106                                 DAG.getConstant(RHSC->getAPIntValue()-
3107                                                 LHSR->getAPIntValue(),
3108                                 dl, N0.getValueType()), Cond);
3109           }
3110 
3111           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
3112           if (N0.getOpcode() == ISD::XOR)
3113             // If we know that all of the inverted bits are zero, don't bother
3114             // performing the inversion.
3115             if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
3116               return
3117                 DAG.getSetCC(dl, VT, N0.getOperand(0),
3118                              DAG.getConstant(LHSR->getAPIntValue() ^
3119                                                RHSC->getAPIntValue(),
3120                                              dl, N0.getValueType()),
3121                              Cond);
3122         }
3123 
3124         // Turn (C1-X) == C2 --> X == C1-C2
3125         if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
3126           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
3127             return
3128               DAG.getSetCC(dl, VT, N0.getOperand(1),
3129                            DAG.getConstant(SUBC->getAPIntValue() -
3130                                              RHSC->getAPIntValue(),
3131                                            dl, N0.getValueType()),
3132                            Cond);
3133           }
3134         }
3135 
3136         // Could RHSC fold directly into a compare?
3137         if (RHSC->getValueType(0).getSizeInBits() <= 64)
3138           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
3139       }
3140 
3141       // (X+Y) == X --> Y == 0 and similar folds.
3142       // Don't do this if X is an immediate that can fold into a cmp
3143       // instruction and X+Y has other uses. It could be an induction variable
3144       // chain, and the transform would increase register pressure.
3145       if (!LegalRHSImm || N0.hasOneUse())
3146         if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
3147           return V;
3148     }
3149 
3150     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
3151         N1.getOpcode() == ISD::XOR)
3152       if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
3153         return V;
3154 
3155     if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
3156       return V;
3157   }
3158 
3159   // Fold away ALL boolean setcc's.
3160   SDValue Temp;
3161   if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
3162     EVT OpVT = N0.getValueType();
3163     switch (Cond) {
3164     default: llvm_unreachable("Unknown integer setcc!");
3165     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
3166       Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
3167       N0 = DAG.getNOT(dl, Temp, OpVT);
3168       if (!DCI.isCalledByLegalizer())
3169         DCI.AddToWorklist(Temp.getNode());
3170       break;
3171     case ISD::SETNE:  // X != Y   -->  (X^Y)
3172       N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
3173       break;
3174     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
3175     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
3176       Temp = DAG.getNOT(dl, N0, OpVT);
3177       N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
3178       if (!DCI.isCalledByLegalizer())
3179         DCI.AddToWorklist(Temp.getNode());
3180       break;
3181     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
3182     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
3183       Temp = DAG.getNOT(dl, N1, OpVT);
3184       N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
3185       if (!DCI.isCalledByLegalizer())
3186         DCI.AddToWorklist(Temp.getNode());
3187       break;
3188     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
3189     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
3190       Temp = DAG.getNOT(dl, N0, OpVT);
3191       N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
3192       if (!DCI.isCalledByLegalizer())
3193         DCI.AddToWorklist(Temp.getNode());
3194       break;
3195     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
3196     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
3197       Temp = DAG.getNOT(dl, N1, OpVT);
3198       N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
3199       break;
3200     }
3201     if (VT.getScalarType() != MVT::i1) {
3202       if (!DCI.isCalledByLegalizer())
3203         DCI.AddToWorklist(N0.getNode());
3204       // FIXME: If running after legalize, we probably can't do this.
3205       ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT));
3206       N0 = DAG.getNode(ExtendCode, dl, VT, N0);
3207     }
3208     return N0;
3209   }
3210 
3211   // Could not fold it.
3212   return SDValue();
3213 }
3214 
3215 /// Returns true (and the GlobalValue and the offset) if the node is a
3216 /// GlobalAddress + offset.
3217 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA,
3218                                     int64_t &Offset) const {
3219 
3220   SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
3221 
3222   if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
3223     GA = GASD->getGlobal();
3224     Offset += GASD->getOffset();
3225     return true;
3226   }
3227 
3228   if (N->getOpcode() == ISD::ADD) {
3229     SDValue N1 = N->getOperand(0);
3230     SDValue N2 = N->getOperand(1);
3231     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
3232       if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
3233         Offset += V->getSExtValue();
3234         return true;
3235       }
3236     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
3237       if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
3238         Offset += V->getSExtValue();
3239         return true;
3240       }
3241     }
3242   }
3243 
3244   return false;
3245 }
3246 
3247 SDValue TargetLowering::PerformDAGCombine(SDNode *N,
3248                                           DAGCombinerInfo &DCI) const {
3249   // Default implementation: no optimization.
3250   return SDValue();
3251 }
3252 
3253 //===----------------------------------------------------------------------===//
3254 //  Inline Assembler Implementation Methods
3255 //===----------------------------------------------------------------------===//
3256 
3257 TargetLowering::ConstraintType
3258 TargetLowering::getConstraintType(StringRef Constraint) const {
3259   unsigned S = Constraint.size();
3260 
3261   if (S == 1) {
3262     switch (Constraint[0]) {
3263     default: break;
3264     case 'r': return C_RegisterClass;
3265     case 'm': // memory
3266     case 'o': // offsetable
3267     case 'V': // not offsetable
3268       return C_Memory;
3269     case 'i': // Simple Integer or Relocatable Constant
3270     case 'n': // Simple Integer
3271     case 'E': // Floating Point Constant
3272     case 'F': // Floating Point Constant
3273     case 's': // Relocatable Constant
3274     case 'p': // Address.
3275     case 'X': // Allow ANY value.
3276     case 'I': // Target registers.
3277     case 'J':
3278     case 'K':
3279     case 'L':
3280     case 'M':
3281     case 'N':
3282     case 'O':
3283     case 'P':
3284     case '<':
3285     case '>':
3286       return C_Other;
3287     }
3288   }
3289 
3290   if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
3291     if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
3292       return C_Memory;
3293     return C_Register;
3294   }
3295   return C_Unknown;
3296 }
3297 
3298 /// Try to replace an X constraint, which matches anything, with another that
3299 /// has more specific requirements based on the type of the corresponding
3300 /// operand.
3301 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
3302   if (ConstraintVT.isInteger())
3303     return "r";
3304   if (ConstraintVT.isFloatingPoint())
3305     return "f"; // works for many targets
3306   return nullptr;
3307 }
3308 
3309 SDValue TargetLowering::LowerAsmOutputForConstraint(
3310     SDValue &Chain, SDValue &Flag, SDLoc DL, const AsmOperandInfo &OpInfo,
3311     SelectionDAG &DAG) const {
3312   return SDValue();
3313 }
3314 
3315 /// Lower the specified operand into the Ops vector.
3316 /// If it is invalid, don't add anything to Ops.
3317 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3318                                                   std::string &Constraint,
3319                                                   std::vector<SDValue> &Ops,
3320                                                   SelectionDAG &DAG) const {
3321 
3322   if (Constraint.length() > 1) return;
3323 
3324   char ConstraintLetter = Constraint[0];
3325   switch (ConstraintLetter) {
3326   default: break;
3327   case 'X':     // Allows any operand; labels (basic block) use this.
3328     if (Op.getOpcode() == ISD::BasicBlock ||
3329         Op.getOpcode() == ISD::TargetBlockAddress) {
3330       Ops.push_back(Op);
3331       return;
3332     }
3333     LLVM_FALLTHROUGH;
3334   case 'i':    // Simple Integer or Relocatable Constant
3335   case 'n':    // Simple Integer
3336   case 's': {  // Relocatable Constant
3337     // These operands are interested in values of the form (GV+C), where C may
3338     // be folded in as an offset of GV, or it may be explicitly added.  Also, it
3339     // is possible and fine if either GV or C are missing.
3340     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3341     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
3342 
3343     // If we have "(add GV, C)", pull out GV/C
3344     if (Op.getOpcode() == ISD::ADD) {
3345       C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
3346       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
3347       if (!C || !GA) {
3348         C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
3349         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
3350       }
3351       if (!C || !GA) {
3352         C = nullptr;
3353         GA = nullptr;
3354       }
3355     }
3356 
3357     // If we find a valid operand, map to the TargetXXX version so that the
3358     // value itself doesn't get selected.
3359     if (GA) {   // Either &GV   or   &GV+C
3360       if (ConstraintLetter != 'n') {
3361         int64_t Offs = GA->getOffset();
3362         if (C) Offs += C->getZExtValue();
3363         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
3364                                                  C ? SDLoc(C) : SDLoc(),
3365                                                  Op.getValueType(), Offs));
3366       }
3367       return;
3368     }
3369     if (C) {   // just C, no GV.
3370       // Simple constants are not allowed for 's'.
3371       if (ConstraintLetter != 's') {
3372         // gcc prints these as sign extended.  Sign extend value to 64 bits
3373         // now; without this it would get ZExt'd later in
3374         // ScheduleDAGSDNodes::EmitNode, which is very generic.
3375         Ops.push_back(DAG.getTargetConstant(C->getSExtValue(),
3376                                             SDLoc(C), MVT::i64));
3377       }
3378       return;
3379     }
3380     break;
3381   }
3382   }
3383 }
3384 
3385 std::pair<unsigned, const TargetRegisterClass *>
3386 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
3387                                              StringRef Constraint,
3388                                              MVT VT) const {
3389   if (Constraint.empty() || Constraint[0] != '{')
3390     return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
3391   assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
3392 
3393   // Remove the braces from around the name.
3394   StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
3395 
3396   std::pair<unsigned, const TargetRegisterClass *> R =
3397       std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
3398 
3399   // Figure out which register class contains this reg.
3400   for (const TargetRegisterClass *RC : RI->regclasses()) {
3401     // If none of the value types for this register class are valid, we
3402     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
3403     if (!isLegalRC(*RI, *RC))
3404       continue;
3405 
3406     for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
3407          I != E; ++I) {
3408       if (RegName.equals_lower(RI->getRegAsmName(*I))) {
3409         std::pair<unsigned, const TargetRegisterClass *> S =
3410             std::make_pair(*I, RC);
3411 
3412         // If this register class has the requested value type, return it,
3413         // otherwise keep searching and return the first class found
3414         // if no other is found which explicitly has the requested type.
3415         if (RI->isTypeLegalForClass(*RC, VT))
3416           return S;
3417         if (!R.second)
3418           R = S;
3419       }
3420     }
3421   }
3422 
3423   return R;
3424 }
3425 
3426 //===----------------------------------------------------------------------===//
3427 // Constraint Selection.
3428 
3429 /// Return true of this is an input operand that is a matching constraint like
3430 /// "4".
3431 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
3432   assert(!ConstraintCode.empty() && "No known constraint!");
3433   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
3434 }
3435 
3436 /// If this is an input matching constraint, this method returns the output
3437 /// operand it matches.
3438 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
3439   assert(!ConstraintCode.empty() && "No known constraint!");
3440   return atoi(ConstraintCode.c_str());
3441 }
3442 
3443 /// Split up the constraint string from the inline assembly value into the
3444 /// specific constraints and their prefixes, and also tie in the associated
3445 /// operand values.
3446 /// If this returns an empty vector, and if the constraint string itself
3447 /// isn't empty, there was an error parsing.
3448 TargetLowering::AsmOperandInfoVector
3449 TargetLowering::ParseConstraints(const DataLayout &DL,
3450                                  const TargetRegisterInfo *TRI,
3451                                  ImmutableCallSite CS) const {
3452   /// Information about all of the constraints.
3453   AsmOperandInfoVector ConstraintOperands;
3454   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
3455   unsigned maCount = 0; // Largest number of multiple alternative constraints.
3456 
3457   // Do a prepass over the constraints, canonicalizing them, and building up the
3458   // ConstraintOperands list.
3459   unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
3460   unsigned ResNo = 0; // ResNo - The result number of the next output.
3461 
3462   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
3463     ConstraintOperands.emplace_back(std::move(CI));
3464     AsmOperandInfo &OpInfo = ConstraintOperands.back();
3465 
3466     // Update multiple alternative constraint count.
3467     if (OpInfo.multipleAlternatives.size() > maCount)
3468       maCount = OpInfo.multipleAlternatives.size();
3469 
3470     OpInfo.ConstraintVT = MVT::Other;
3471 
3472     // Compute the value type for each operand.
3473     switch (OpInfo.Type) {
3474     case InlineAsm::isOutput:
3475       // Indirect outputs just consume an argument.
3476       if (OpInfo.isIndirect) {
3477         OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
3478         break;
3479       }
3480 
3481       // The return value of the call is this value.  As such, there is no
3482       // corresponding argument.
3483       assert(!CS.getType()->isVoidTy() &&
3484              "Bad inline asm!");
3485       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
3486         OpInfo.ConstraintVT =
3487             getSimpleValueType(DL, STy->getElementType(ResNo));
3488       } else {
3489         assert(ResNo == 0 && "Asm only has one result!");
3490         OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType());
3491       }
3492       ++ResNo;
3493       break;
3494     case InlineAsm::isInput:
3495       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
3496       break;
3497     case InlineAsm::isClobber:
3498       // Nothing to do.
3499       break;
3500     }
3501 
3502     if (OpInfo.CallOperandVal) {
3503       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
3504       if (OpInfo.isIndirect) {
3505         llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
3506         if (!PtrTy)
3507           report_fatal_error("Indirect operand for inline asm not a pointer!");
3508         OpTy = PtrTy->getElementType();
3509       }
3510 
3511       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
3512       if (StructType *STy = dyn_cast<StructType>(OpTy))
3513         if (STy->getNumElements() == 1)
3514           OpTy = STy->getElementType(0);
3515 
3516       // If OpTy is not a single value, it may be a struct/union that we
3517       // can tile with integers.
3518       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
3519         unsigned BitSize = DL.getTypeSizeInBits(OpTy);
3520         switch (BitSize) {
3521         default: break;
3522         case 1:
3523         case 8:
3524         case 16:
3525         case 32:
3526         case 64:
3527         case 128:
3528           OpInfo.ConstraintVT =
3529               MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
3530           break;
3531         }
3532       } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
3533         unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
3534         OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
3535       } else {
3536         OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
3537       }
3538     }
3539   }
3540 
3541   // If we have multiple alternative constraints, select the best alternative.
3542   if (!ConstraintOperands.empty()) {
3543     if (maCount) {
3544       unsigned bestMAIndex = 0;
3545       int bestWeight = -1;
3546       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
3547       int weight = -1;
3548       unsigned maIndex;
3549       // Compute the sums of the weights for each alternative, keeping track
3550       // of the best (highest weight) one so far.
3551       for (maIndex = 0; maIndex < maCount; ++maIndex) {
3552         int weightSum = 0;
3553         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
3554              cIndex != eIndex; ++cIndex) {
3555           AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
3556           if (OpInfo.Type == InlineAsm::isClobber)
3557             continue;
3558 
3559           // If this is an output operand with a matching input operand,
3560           // look up the matching input. If their types mismatch, e.g. one
3561           // is an integer, the other is floating point, or their sizes are
3562           // different, flag it as an maCantMatch.
3563           if (OpInfo.hasMatchingInput()) {
3564             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
3565             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
3566               if ((OpInfo.ConstraintVT.isInteger() !=
3567                    Input.ConstraintVT.isInteger()) ||
3568                   (OpInfo.ConstraintVT.getSizeInBits() !=
3569                    Input.ConstraintVT.getSizeInBits())) {
3570                 weightSum = -1; // Can't match.
3571                 break;
3572               }
3573             }
3574           }
3575           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
3576           if (weight == -1) {
3577             weightSum = -1;
3578             break;
3579           }
3580           weightSum += weight;
3581         }
3582         // Update best.
3583         if (weightSum > bestWeight) {
3584           bestWeight = weightSum;
3585           bestMAIndex = maIndex;
3586         }
3587       }
3588 
3589       // Now select chosen alternative in each constraint.
3590       for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
3591            cIndex != eIndex; ++cIndex) {
3592         AsmOperandInfo &cInfo = ConstraintOperands[cIndex];
3593         if (cInfo.Type == InlineAsm::isClobber)
3594           continue;
3595         cInfo.selectAlternative(bestMAIndex);
3596       }
3597     }
3598   }
3599 
3600   // Check and hook up tied operands, choose constraint code to use.
3601   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
3602        cIndex != eIndex; ++cIndex) {
3603     AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
3604 
3605     // If this is an output operand with a matching input operand, look up the
3606     // matching input. If their types mismatch, e.g. one is an integer, the
3607     // other is floating point, or their sizes are different, flag it as an
3608     // error.
3609     if (OpInfo.hasMatchingInput()) {
3610       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
3611 
3612       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
3613         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
3614             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
3615                                          OpInfo.ConstraintVT);
3616         std::pair<unsigned, const TargetRegisterClass *> InputRC =
3617             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
3618                                          Input.ConstraintVT);
3619         if ((OpInfo.ConstraintVT.isInteger() !=
3620              Input.ConstraintVT.isInteger()) ||
3621             (MatchRC.second != InputRC.second)) {
3622           report_fatal_error("Unsupported asm: input constraint"
3623                              " with a matching output constraint of"
3624                              " incompatible type!");
3625         }
3626       }
3627     }
3628   }
3629 
3630   return ConstraintOperands;
3631 }
3632 
3633 /// Return an integer indicating how general CT is.
3634 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3635   switch (CT) {
3636   case TargetLowering::C_Other:
3637   case TargetLowering::C_Unknown:
3638     return 0;
3639   case TargetLowering::C_Register:
3640     return 1;
3641   case TargetLowering::C_RegisterClass:
3642     return 2;
3643   case TargetLowering::C_Memory:
3644     return 3;
3645   }
3646   llvm_unreachable("Invalid constraint type");
3647 }
3648 
3649 /// Examine constraint type and operand type and determine a weight value.
3650 /// This object must already have been set up with the operand type
3651 /// and the current alternative constraint selected.
3652 TargetLowering::ConstraintWeight
3653   TargetLowering::getMultipleConstraintMatchWeight(
3654     AsmOperandInfo &info, int maIndex) const {
3655   InlineAsm::ConstraintCodeVector *rCodes;
3656   if (maIndex >= (int)info.multipleAlternatives.size())
3657     rCodes = &info.Codes;
3658   else
3659     rCodes = &info.multipleAlternatives[maIndex].Codes;
3660   ConstraintWeight BestWeight = CW_Invalid;
3661 
3662   // Loop over the options, keeping track of the most general one.
3663   for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
3664     ConstraintWeight weight =
3665       getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
3666     if (weight > BestWeight)
3667       BestWeight = weight;
3668   }
3669 
3670   return BestWeight;
3671 }
3672 
3673 /// Examine constraint type and operand type and determine a weight value.
3674 /// This object must already have been set up with the operand type
3675 /// and the current alternative constraint selected.
3676 TargetLowering::ConstraintWeight
3677   TargetLowering::getSingleConstraintMatchWeight(
3678     AsmOperandInfo &info, const char *constraint) const {
3679   ConstraintWeight weight = CW_Invalid;
3680   Value *CallOperandVal = info.CallOperandVal;
3681     // If we don't have a value, we can't do a match,
3682     // but allow it at the lowest weight.
3683   if (!CallOperandVal)
3684     return CW_Default;
3685   // Look at the constraint type.
3686   switch (*constraint) {
3687     case 'i': // immediate integer.
3688     case 'n': // immediate integer with a known value.
3689       if (isa<ConstantInt>(CallOperandVal))
3690         weight = CW_Constant;
3691       break;
3692     case 's': // non-explicit intregal immediate.
3693       if (isa<GlobalValue>(CallOperandVal))
3694         weight = CW_Constant;
3695       break;
3696     case 'E': // immediate float if host format.
3697     case 'F': // immediate float.
3698       if (isa<ConstantFP>(CallOperandVal))
3699         weight = CW_Constant;
3700       break;
3701     case '<': // memory operand with autodecrement.
3702     case '>': // memory operand with autoincrement.
3703     case 'm': // memory operand.
3704     case 'o': // offsettable memory operand
3705     case 'V': // non-offsettable memory operand
3706       weight = CW_Memory;
3707       break;
3708     case 'r': // general register.
3709     case 'g': // general register, memory operand or immediate integer.
3710               // note: Clang converts "g" to "imr".
3711       if (CallOperandVal->getType()->isIntegerTy())
3712         weight = CW_Register;
3713       break;
3714     case 'X': // any operand.
3715   default:
3716     weight = CW_Default;
3717     break;
3718   }
3719   return weight;
3720 }
3721 
3722 /// If there are multiple different constraints that we could pick for this
3723 /// operand (e.g. "imr") try to pick the 'best' one.
3724 /// This is somewhat tricky: constraints fall into four classes:
3725 ///    Other         -> immediates and magic values
3726 ///    Register      -> one specific register
3727 ///    RegisterClass -> a group of regs
3728 ///    Memory        -> memory
3729 /// Ideally, we would pick the most specific constraint possible: if we have
3730 /// something that fits into a register, we would pick it.  The problem here
3731 /// is that if we have something that could either be in a register or in
3732 /// memory that use of the register could cause selection of *other*
3733 /// operands to fail: they might only succeed if we pick memory.  Because of
3734 /// this the heuristic we use is:
3735 ///
3736 ///  1) If there is an 'other' constraint, and if the operand is valid for
3737 ///     that constraint, use it.  This makes us take advantage of 'i'
3738 ///     constraints when available.
3739 ///  2) Otherwise, pick the most general constraint present.  This prefers
3740 ///     'm' over 'r', for example.
3741 ///
3742 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
3743                              const TargetLowering &TLI,
3744                              SDValue Op, SelectionDAG *DAG) {
3745   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
3746   unsigned BestIdx = 0;
3747   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
3748   int BestGenerality = -1;
3749 
3750   // Loop over the options, keeping track of the most general one.
3751   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
3752     TargetLowering::ConstraintType CType =
3753       TLI.getConstraintType(OpInfo.Codes[i]);
3754 
3755     // If this is an 'other' constraint, see if the operand is valid for it.
3756     // For example, on X86 we might have an 'rI' constraint.  If the operand
3757     // is an integer in the range [0..31] we want to use I (saving a load
3758     // of a register), otherwise we must use 'r'.
3759     if (CType == TargetLowering::C_Other && Op.getNode()) {
3760       assert(OpInfo.Codes[i].size() == 1 &&
3761              "Unhandled multi-letter 'other' constraint");
3762       std::vector<SDValue> ResultOps;
3763       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
3764                                        ResultOps, *DAG);
3765       if (!ResultOps.empty()) {
3766         BestType = CType;
3767         BestIdx = i;
3768         break;
3769       }
3770     }
3771 
3772     // Things with matching constraints can only be registers, per gcc
3773     // documentation.  This mainly affects "g" constraints.
3774     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
3775       continue;
3776 
3777     // This constraint letter is more general than the previous one, use it.
3778     int Generality = getConstraintGenerality(CType);
3779     if (Generality > BestGenerality) {
3780       BestType = CType;
3781       BestIdx = i;
3782       BestGenerality = Generality;
3783     }
3784   }
3785 
3786   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
3787   OpInfo.ConstraintType = BestType;
3788 }
3789 
3790 /// Determines the constraint code and constraint type to use for the specific
3791 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
3792 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
3793                                             SDValue Op,
3794                                             SelectionDAG *DAG) const {
3795   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
3796 
3797   // Single-letter constraints ('r') are very common.
3798   if (OpInfo.Codes.size() == 1) {
3799     OpInfo.ConstraintCode = OpInfo.Codes[0];
3800     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
3801   } else {
3802     ChooseConstraint(OpInfo, *this, Op, DAG);
3803   }
3804 
3805   // 'X' matches anything.
3806   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
3807     // Labels and constants are handled elsewhere ('X' is the only thing
3808     // that matches labels).  For Functions, the type here is the type of
3809     // the result, which is not what we want to look at; leave them alone.
3810     Value *v = OpInfo.CallOperandVal;
3811     if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
3812       OpInfo.CallOperandVal = v;
3813       return;
3814     }
3815 
3816     if (Op.getNode() && Op.getOpcode() == ISD::TargetBlockAddress)
3817       return;
3818 
3819     // Otherwise, try to resolve it to something we know about by looking at
3820     // the actual operand type.
3821     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
3822       OpInfo.ConstraintCode = Repl;
3823       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
3824     }
3825   }
3826 }
3827 
3828 /// Given an exact SDIV by a constant, create a multiplication
3829 /// with the multiplicative inverse of the constant.
3830 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N,
3831                               const SDLoc &dl, SelectionDAG &DAG,
3832                               SmallVectorImpl<SDNode *> &Created) {
3833   SDValue Op0 = N->getOperand(0);
3834   SDValue Op1 = N->getOperand(1);
3835   EVT VT = N->getValueType(0);
3836   EVT SVT = VT.getScalarType();
3837   EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
3838   EVT ShSVT = ShVT.getScalarType();
3839 
3840   bool UseSRA = false;
3841   SmallVector<SDValue, 16> Shifts, Factors;
3842 
3843   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
3844     if (C->isNullValue())
3845       return false;
3846     APInt Divisor = C->getAPIntValue();
3847     unsigned Shift = Divisor.countTrailingZeros();
3848     if (Shift) {
3849       Divisor.ashrInPlace(Shift);
3850       UseSRA = true;
3851     }
3852     // Calculate the multiplicative inverse, using Newton's method.
3853     APInt t;
3854     APInt Factor = Divisor;
3855     while ((t = Divisor * Factor) != 1)
3856       Factor *= APInt(Divisor.getBitWidth(), 2) - t;
3857     Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
3858     Factors.push_back(DAG.getConstant(Factor, dl, SVT));
3859     return true;
3860   };
3861 
3862   // Collect all magic values from the build vector.
3863   if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
3864     return SDValue();
3865 
3866   SDValue Shift, Factor;
3867   if (VT.isVector()) {
3868     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
3869     Factor = DAG.getBuildVector(VT, dl, Factors);
3870   } else {
3871     Shift = Shifts[0];
3872     Factor = Factors[0];
3873   }
3874 
3875   SDValue Res = Op0;
3876 
3877   // Shift the value upfront if it is even, so the LSB is one.
3878   if (UseSRA) {
3879     // TODO: For UDIV use SRL instead of SRA.
3880     SDNodeFlags Flags;
3881     Flags.setExact(true);
3882     Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags);
3883     Created.push_back(Res.getNode());
3884   }
3885 
3886   return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
3887 }
3888 
3889 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
3890                               SelectionDAG &DAG,
3891                               SmallVectorImpl<SDNode *> &Created) const {
3892   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3893   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3894   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
3895     return SDValue(N, 0); // Lower SDIV as SDIV
3896   return SDValue();
3897 }
3898 
3899 /// Given an ISD::SDIV node expressing a divide by constant,
3900 /// return a DAG expression to select that will generate the same value by
3901 /// multiplying by a magic number.
3902 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
3903 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
3904                                   bool IsAfterLegalization,
3905                                   SmallVectorImpl<SDNode *> &Created) const {
3906   SDLoc dl(N);
3907   EVT VT = N->getValueType(0);
3908   EVT SVT = VT.getScalarType();
3909   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
3910   EVT ShSVT = ShVT.getScalarType();
3911   unsigned EltBits = VT.getScalarSizeInBits();
3912 
3913   // Check to see if we can do this.
3914   // FIXME: We should be more aggressive here.
3915   if (!isTypeLegal(VT))
3916     return SDValue();
3917 
3918   // If the sdiv has an 'exact' bit we can use a simpler lowering.
3919   if (N->getFlags().hasExact())
3920     return BuildExactSDIV(*this, N, dl, DAG, Created);
3921 
3922   SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
3923 
3924   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
3925     if (C->isNullValue())
3926       return false;
3927 
3928     const APInt &Divisor = C->getAPIntValue();
3929     APInt::ms magics = Divisor.magic();
3930     int NumeratorFactor = 0;
3931     int ShiftMask = -1;
3932 
3933     if (Divisor.isOneValue() || Divisor.isAllOnesValue()) {
3934       // If d is +1/-1, we just multiply the numerator by +1/-1.
3935       NumeratorFactor = Divisor.getSExtValue();
3936       magics.m = 0;
3937       magics.s = 0;
3938       ShiftMask = 0;
3939     } else if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
3940       // If d > 0 and m < 0, add the numerator.
3941       NumeratorFactor = 1;
3942     } else if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
3943       // If d < 0 and m > 0, subtract the numerator.
3944       NumeratorFactor = -1;
3945     }
3946 
3947     MagicFactors.push_back(DAG.getConstant(magics.m, dl, SVT));
3948     Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT));
3949     Shifts.push_back(DAG.getConstant(magics.s, dl, ShSVT));
3950     ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT));
3951     return true;
3952   };
3953 
3954   SDValue N0 = N->getOperand(0);
3955   SDValue N1 = N->getOperand(1);
3956 
3957   // Collect the shifts / magic values from each element.
3958   if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern))
3959     return SDValue();
3960 
3961   SDValue MagicFactor, Factor, Shift, ShiftMask;
3962   if (VT.isVector()) {
3963     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
3964     Factor = DAG.getBuildVector(VT, dl, Factors);
3965     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
3966     ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
3967   } else {
3968     MagicFactor = MagicFactors[0];
3969     Factor = Factors[0];
3970     Shift = Shifts[0];
3971     ShiftMask = ShiftMasks[0];
3972   }
3973 
3974   // Multiply the numerator (operand 0) by the magic value.
3975   // FIXME: We should support doing a MUL in a wider type.
3976   SDValue Q;
3977   if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT)
3978                           : isOperationLegalOrCustom(ISD::MULHS, VT))
3979     Q = DAG.getNode(ISD::MULHS, dl, VT, N0, MagicFactor);
3980   else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT)
3981                                : isOperationLegalOrCustom(ISD::SMUL_LOHI, VT)) {
3982     SDValue LoHi =
3983         DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), N0, MagicFactor);
3984     Q = SDValue(LoHi.getNode(), 1);
3985   } else
3986     return SDValue(); // No mulhs or equivalent.
3987   Created.push_back(Q.getNode());
3988 
3989   // (Optionally) Add/subtract the numerator using Factor.
3990   Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
3991   Created.push_back(Factor.getNode());
3992   Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
3993   Created.push_back(Q.getNode());
3994 
3995   // Shift right algebraic by shift value.
3996   Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
3997   Created.push_back(Q.getNode());
3998 
3999   // Extract the sign bit, mask it and add it to the quotient.
4000   SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
4001   SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
4002   Created.push_back(T.getNode());
4003   T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
4004   Created.push_back(T.getNode());
4005   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
4006 }
4007 
4008 /// Given an ISD::UDIV node expressing a divide by constant,
4009 /// return a DAG expression to select that will generate the same value by
4010 /// multiplying by a magic number.
4011 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
4012 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
4013                                   bool IsAfterLegalization,
4014                                   SmallVectorImpl<SDNode *> &Created) const {
4015   SDLoc dl(N);
4016   EVT VT = N->getValueType(0);
4017   EVT SVT = VT.getScalarType();
4018   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
4019   EVT ShSVT = ShVT.getScalarType();
4020   unsigned EltBits = VT.getScalarSizeInBits();
4021 
4022   // Check to see if we can do this.
4023   // FIXME: We should be more aggressive here.
4024   if (!isTypeLegal(VT))
4025     return SDValue();
4026 
4027   bool UseNPQ = false;
4028   SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
4029 
4030   auto BuildUDIVPattern = [&](ConstantSDNode *C) {
4031     if (C->isNullValue())
4032       return false;
4033     // FIXME: We should use a narrower constant when the upper
4034     // bits are known to be zero.
4035     APInt Divisor = C->getAPIntValue();
4036     APInt::mu magics = Divisor.magicu();
4037     unsigned PreShift = 0, PostShift = 0;
4038 
4039     // If the divisor is even, we can avoid using the expensive fixup by
4040     // shifting the divided value upfront.
4041     if (magics.a != 0 && !Divisor[0]) {
4042       PreShift = Divisor.countTrailingZeros();
4043       // Get magic number for the shifted divisor.
4044       magics = Divisor.lshr(PreShift).magicu(PreShift);
4045       assert(magics.a == 0 && "Should use cheap fixup now");
4046     }
4047 
4048     APInt Magic = magics.m;
4049 
4050     unsigned SelNPQ;
4051     if (magics.a == 0 || Divisor.isOneValue()) {
4052       assert(magics.s < Divisor.getBitWidth() &&
4053              "We shouldn't generate an undefined shift!");
4054       PostShift = magics.s;
4055       SelNPQ = false;
4056     } else {
4057       PostShift = magics.s - 1;
4058       SelNPQ = true;
4059     }
4060 
4061     PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT));
4062     MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT));
4063     NPQFactors.push_back(
4064         DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1)
4065                                : APInt::getNullValue(EltBits),
4066                         dl, SVT));
4067     PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT));
4068     UseNPQ |= SelNPQ;
4069     return true;
4070   };
4071 
4072   SDValue N0 = N->getOperand(0);
4073   SDValue N1 = N->getOperand(1);
4074 
4075   // Collect the shifts/magic values from each element.
4076   if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern))
4077     return SDValue();
4078 
4079   SDValue PreShift, PostShift, MagicFactor, NPQFactor;
4080   if (VT.isVector()) {
4081     PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
4082     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
4083     NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
4084     PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
4085   } else {
4086     PreShift = PreShifts[0];
4087     MagicFactor = MagicFactors[0];
4088     PostShift = PostShifts[0];
4089   }
4090 
4091   SDValue Q = N0;
4092   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
4093   Created.push_back(Q.getNode());
4094 
4095   // FIXME: We should support doing a MUL in a wider type.
4096   auto GetMULHU = [&](SDValue X, SDValue Y) {
4097     if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT)
4098                             : isOperationLegalOrCustom(ISD::MULHU, VT))
4099       return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
4100     if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT)
4101                             : isOperationLegalOrCustom(ISD::UMUL_LOHI, VT)) {
4102       SDValue LoHi =
4103           DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
4104       return SDValue(LoHi.getNode(), 1);
4105     }
4106     return SDValue(); // No mulhu or equivalent
4107   };
4108 
4109   // Multiply the numerator (operand 0) by the magic value.
4110   Q = GetMULHU(Q, MagicFactor);
4111   if (!Q)
4112     return SDValue();
4113 
4114   Created.push_back(Q.getNode());
4115 
4116   if (UseNPQ) {
4117     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
4118     Created.push_back(NPQ.getNode());
4119 
4120     // For vectors we might have a mix of non-NPQ/NPQ paths, so use
4121     // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
4122     if (VT.isVector())
4123       NPQ = GetMULHU(NPQ, NPQFactor);
4124     else
4125       NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
4126 
4127     Created.push_back(NPQ.getNode());
4128 
4129     Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
4130     Created.push_back(Q.getNode());
4131   }
4132 
4133   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
4134   Created.push_back(Q.getNode());
4135 
4136   SDValue One = DAG.getConstant(1, dl, VT);
4137   SDValue IsOne = DAG.getSetCC(dl, VT, N1, One, ISD::SETEQ);
4138   return DAG.getSelect(dl, VT, IsOne, N0, Q);
4139 }
4140 
4141 bool TargetLowering::
4142 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
4143   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
4144     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
4145                                 "be a constant integer");
4146     return true;
4147   }
4148 
4149   return false;
4150 }
4151 
4152 //===----------------------------------------------------------------------===//
4153 // Legalization Utilities
4154 //===----------------------------------------------------------------------===//
4155 
4156 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl,
4157                                     SDValue LHS, SDValue RHS,
4158                                     SmallVectorImpl<SDValue> &Result,
4159                                     EVT HiLoVT, SelectionDAG &DAG,
4160                                     MulExpansionKind Kind, SDValue LL,
4161                                     SDValue LH, SDValue RL, SDValue RH) const {
4162   assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
4163          Opcode == ISD::SMUL_LOHI);
4164 
4165   bool HasMULHS = (Kind == MulExpansionKind::Always) ||
4166                   isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
4167   bool HasMULHU = (Kind == MulExpansionKind::Always) ||
4168                   isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
4169   bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
4170                       isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
4171   bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
4172                       isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
4173 
4174   if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
4175     return false;
4176 
4177   unsigned OuterBitSize = VT.getScalarSizeInBits();
4178   unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
4179   unsigned LHSSB = DAG.ComputeNumSignBits(LHS);
4180   unsigned RHSSB = DAG.ComputeNumSignBits(RHS);
4181 
4182   // LL, LH, RL, and RH must be either all NULL or all set to a value.
4183   assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
4184          (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
4185 
4186   SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
4187   auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
4188                           bool Signed) -> bool {
4189     if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
4190       Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
4191       Hi = SDValue(Lo.getNode(), 1);
4192       return true;
4193     }
4194     if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
4195       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
4196       Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
4197       return true;
4198     }
4199     return false;
4200   };
4201 
4202   SDValue Lo, Hi;
4203 
4204   if (!LL.getNode() && !RL.getNode() &&
4205       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
4206     LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
4207     RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
4208   }
4209 
4210   if (!LL.getNode())
4211     return false;
4212 
4213   APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
4214   if (DAG.MaskedValueIsZero(LHS, HighMask) &&
4215       DAG.MaskedValueIsZero(RHS, HighMask)) {
4216     // The inputs are both zero-extended.
4217     if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
4218       Result.push_back(Lo);
4219       Result.push_back(Hi);
4220       if (Opcode != ISD::MUL) {
4221         SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
4222         Result.push_back(Zero);
4223         Result.push_back(Zero);
4224       }
4225       return true;
4226     }
4227   }
4228 
4229   if (!VT.isVector() && Opcode == ISD::MUL && LHSSB > InnerBitSize &&
4230       RHSSB > InnerBitSize) {
4231     // The input values are both sign-extended.
4232     // TODO non-MUL case?
4233     if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
4234       Result.push_back(Lo);
4235       Result.push_back(Hi);
4236       return true;
4237     }
4238   }
4239 
4240   unsigned ShiftAmount = OuterBitSize - InnerBitSize;
4241   EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout());
4242   if (APInt::getMaxValue(ShiftAmountTy.getSizeInBits()).ult(ShiftAmount)) {
4243     // FIXME getShiftAmountTy does not always return a sensible result when VT
4244     // is an illegal type, and so the type may be too small to fit the shift
4245     // amount. Override it with i32. The shift will have to be legalized.
4246     ShiftAmountTy = MVT::i32;
4247   }
4248   SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy);
4249 
4250   if (!LH.getNode() && !RH.getNode() &&
4251       isOperationLegalOrCustom(ISD::SRL, VT) &&
4252       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
4253     LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
4254     LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
4255     RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
4256     RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
4257   }
4258 
4259   if (!LH.getNode())
4260     return false;
4261 
4262   if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
4263     return false;
4264 
4265   Result.push_back(Lo);
4266 
4267   if (Opcode == ISD::MUL) {
4268     RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
4269     LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
4270     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
4271     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
4272     Result.push_back(Hi);
4273     return true;
4274   }
4275 
4276   // Compute the full width result.
4277   auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
4278     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
4279     Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
4280     Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
4281     return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
4282   };
4283 
4284   SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
4285   if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
4286     return false;
4287 
4288   // This is effectively the add part of a multiply-add of half-sized operands,
4289   // so it cannot overflow.
4290   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
4291 
4292   if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
4293     return false;
4294 
4295   SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
4296   EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
4297 
4298   bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
4299                   isOperationLegalOrCustom(ISD::ADDE, VT));
4300   if (UseGlue)
4301     Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
4302                        Merge(Lo, Hi));
4303   else
4304     Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next,
4305                        Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
4306 
4307   SDValue Carry = Next.getValue(1);
4308   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
4309   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
4310 
4311   if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
4312     return false;
4313 
4314   if (UseGlue)
4315     Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
4316                      Carry);
4317   else
4318     Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
4319                      Zero, Carry);
4320 
4321   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
4322 
4323   if (Opcode == ISD::SMUL_LOHI) {
4324     SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
4325                                   DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
4326     Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
4327 
4328     NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
4329                           DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
4330     Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
4331   }
4332 
4333   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
4334   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
4335   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
4336   return true;
4337 }
4338 
4339 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
4340                                SelectionDAG &DAG, MulExpansionKind Kind,
4341                                SDValue LL, SDValue LH, SDValue RL,
4342                                SDValue RH) const {
4343   SmallVector<SDValue, 2> Result;
4344   bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), N,
4345                            N->getOperand(0), N->getOperand(1), Result, HiLoVT,
4346                            DAG, Kind, LL, LH, RL, RH);
4347   if (Ok) {
4348     assert(Result.size() == 2);
4349     Lo = Result[0];
4350     Hi = Result[1];
4351   }
4352   return Ok;
4353 }
4354 
4355 bool TargetLowering::expandFunnelShift(SDNode *Node, SDValue &Result,
4356                                        SelectionDAG &DAG) const {
4357   EVT VT = Node->getValueType(0);
4358 
4359   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
4360                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
4361                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
4362                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
4363     return false;
4364 
4365   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
4366   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
4367   SDValue X = Node->getOperand(0);
4368   SDValue Y = Node->getOperand(1);
4369   SDValue Z = Node->getOperand(2);
4370 
4371   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4372   bool IsFSHL = Node->getOpcode() == ISD::FSHL;
4373   SDLoc DL(SDValue(Node, 0));
4374 
4375   EVT ShVT = Z.getValueType();
4376   SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
4377   SDValue Zero = DAG.getConstant(0, DL, ShVT);
4378 
4379   SDValue ShAmt;
4380   if (isPowerOf2_32(EltSizeInBits)) {
4381     SDValue Mask = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
4382     ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
4383   } else {
4384     ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
4385   }
4386 
4387   SDValue InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
4388   SDValue ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
4389   SDValue ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
4390   SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
4391 
4392   // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
4393   // and that is undefined. We must compare and select to avoid UB.
4394   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShVT);
4395 
4396   // For fshl, 0-shift returns the 1st arg (X).
4397   // For fshr, 0-shift returns the 2nd arg (Y).
4398   SDValue IsZeroShift = DAG.getSetCC(DL, CCVT, ShAmt, Zero, ISD::SETEQ);
4399   Result = DAG.getSelect(DL, VT, IsZeroShift, IsFSHL ? X : Y, Or);
4400   return true;
4401 }
4402 
4403 // TODO: Merge with expandFunnelShift.
4404 bool TargetLowering::expandROT(SDNode *Node, SDValue &Result,
4405                                SelectionDAG &DAG) const {
4406   EVT VT = Node->getValueType(0);
4407   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4408   bool IsLeft = Node->getOpcode() == ISD::ROTL;
4409   SDValue Op0 = Node->getOperand(0);
4410   SDValue Op1 = Node->getOperand(1);
4411   SDLoc DL(SDValue(Node, 0));
4412 
4413   EVT ShVT = Op1.getValueType();
4414   SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
4415 
4416   // If a rotate in the other direction is legal, use it.
4417   unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
4418   if (isOperationLegal(RevRot, VT)) {
4419     SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, Op1);
4420     Result = DAG.getNode(RevRot, DL, VT, Op0, Sub);
4421     return true;
4422   }
4423 
4424   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
4425                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
4426                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
4427                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT) ||
4428                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT)))
4429     return false;
4430 
4431   // Otherwise,
4432   //   (rotl x, c) -> (or (shl x, (and c, w-1)), (srl x, (and w-c, w-1)))
4433   //   (rotr x, c) -> (or (srl x, (and c, w-1)), (shl x, (and w-c, w-1)))
4434   //
4435   assert(isPowerOf2_32(EltSizeInBits) && EltSizeInBits > 1 &&
4436          "Expecting the type bitwidth to be a power of 2");
4437   unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
4438   unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
4439   SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
4440   SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, Op1);
4441   SDValue And0 = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
4442   SDValue And1 = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
4443   Result = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ShOpc, DL, VT, Op0, And0),
4444                        DAG.getNode(HsOpc, DL, VT, Op0, And1));
4445   return true;
4446 }
4447 
4448 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
4449                                       SelectionDAG &DAG) const {
4450   SDValue Src = Node->getOperand(0);
4451   EVT SrcVT = Src.getValueType();
4452   EVT DstVT = Node->getValueType(0);
4453   SDLoc dl(SDValue(Node, 0));
4454 
4455   // FIXME: Only f32 to i64 conversions are supported.
4456   if (SrcVT != MVT::f32 || DstVT != MVT::i64)
4457     return false;
4458 
4459   // Expand f32 -> i64 conversion
4460   // This algorithm comes from compiler-rt's implementation of fixsfdi:
4461   // https://github.com/llvm/llvm-project/blob/master/compiler-rt/lib/builtins/fixsfdi.c
4462   unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
4463   EVT IntVT = SrcVT.changeTypeToInteger();
4464   EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
4465 
4466   SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
4467   SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
4468   SDValue Bias = DAG.getConstant(127, dl, IntVT);
4469   SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
4470   SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
4471   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
4472 
4473   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
4474 
4475   SDValue ExponentBits = DAG.getNode(
4476       ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
4477       DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
4478   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
4479 
4480   SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
4481                              DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
4482                              DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
4483   Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
4484 
4485   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
4486                           DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
4487                           DAG.getConstant(0x00800000, dl, IntVT));
4488 
4489   R = DAG.getZExtOrTrunc(R, dl, DstVT);
4490 
4491   R = DAG.getSelectCC(
4492       dl, Exponent, ExponentLoBit,
4493       DAG.getNode(ISD::SHL, dl, DstVT, R,
4494                   DAG.getZExtOrTrunc(
4495                       DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
4496                       dl, IntShVT)),
4497       DAG.getNode(ISD::SRL, dl, DstVT, R,
4498                   DAG.getZExtOrTrunc(
4499                       DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
4500                       dl, IntShVT)),
4501       ISD::SETGT);
4502 
4503   SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
4504                             DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
4505 
4506   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
4507                            DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
4508   return true;
4509 }
4510 
4511 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result,
4512                                       SelectionDAG &DAG) const {
4513   SDLoc dl(SDValue(Node, 0));
4514   SDValue Src = Node->getOperand(0);
4515 
4516   EVT SrcVT = Src.getValueType();
4517   EVT DstVT = Node->getValueType(0);
4518   EVT SetCCVT =
4519       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
4520 
4521   // Only expand vector types if we have the appropriate vector bit operations.
4522   if (DstVT.isVector() && (!isOperationLegalOrCustom(ISD::FP_TO_SINT, DstVT) ||
4523                            !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT)))
4524     return false;
4525 
4526   // If the maximum float value is smaller then the signed integer range,
4527   // the destination signmask can't be represented by the float, so we can
4528   // just use FP_TO_SINT directly.
4529   const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT);
4530   APFloat APF(APFSem, APInt::getNullValue(SrcVT.getScalarSizeInBits()));
4531   APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
4532   if (APFloat::opOverflow &
4533       APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
4534     Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
4535     return true;
4536   }
4537 
4538   SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
4539   SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
4540 
4541   bool Strict = shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
4542   if (Strict) {
4543     // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
4544     // signmask then offset (the result of which should be fully representable).
4545     // Sel = Src < 0x8000000000000000
4546     // Val = select Sel, Src, Src - 0x8000000000000000
4547     // Ofs = select Sel, 0, 0x8000000000000000
4548     // Result = fp_to_sint(Val) ^ Ofs
4549 
4550     // TODO: Should any fast-math-flags be set for the FSUB?
4551     SDValue Val = DAG.getSelect(dl, SrcVT, Sel, Src,
4552                                 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
4553     SDValue Ofs = DAG.getSelect(dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT),
4554                                 DAG.getConstant(SignMask, dl, DstVT));
4555     Result = DAG.getNode(ISD::XOR, dl, DstVT,
4556                          DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val), Ofs);
4557   } else {
4558     // Expand based on maximum range of FP_TO_SINT:
4559     // True = fp_to_sint(Src)
4560     // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
4561     // Result = select (Src < 0x8000000000000000), True, False
4562 
4563     SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
4564     // TODO: Should any fast-math-flags be set for the FSUB?
4565     SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
4566                                 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
4567     False = DAG.getNode(ISD::XOR, dl, DstVT, False,
4568                         DAG.getConstant(SignMask, dl, DstVT));
4569     Result = DAG.getSelect(dl, DstVT, Sel, True, False);
4570   }
4571   return true;
4572 }
4573 
4574 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result,
4575                                       SelectionDAG &DAG) const {
4576   SDValue Src = Node->getOperand(0);
4577   EVT SrcVT = Src.getValueType();
4578   EVT DstVT = Node->getValueType(0);
4579 
4580   if (SrcVT.getScalarType() != MVT::i64)
4581     return false;
4582 
4583   SDLoc dl(SDValue(Node, 0));
4584   EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout());
4585 
4586   if (DstVT.getScalarType() == MVT::f32) {
4587     // Only expand vector types if we have the appropriate vector bit
4588     // operations.
4589     if (SrcVT.isVector() &&
4590         (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
4591          !isOperationLegalOrCustom(ISD::FADD, DstVT) ||
4592          !isOperationLegalOrCustom(ISD::SINT_TO_FP, SrcVT) ||
4593          !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) ||
4594          !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT)))
4595       return false;
4596 
4597     // For unsigned conversions, convert them to signed conversions using the
4598     // algorithm from the x86_64 __floatundidf in compiler_rt.
4599     SDValue Fast = DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Src);
4600 
4601     SDValue ShiftConst = DAG.getConstant(1, dl, ShiftVT);
4602     SDValue Shr = DAG.getNode(ISD::SRL, dl, SrcVT, Src, ShiftConst);
4603     SDValue AndConst = DAG.getConstant(1, dl, SrcVT);
4604     SDValue And = DAG.getNode(ISD::AND, dl, SrcVT, Src, AndConst);
4605     SDValue Or = DAG.getNode(ISD::OR, dl, SrcVT, And, Shr);
4606 
4607     SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Or);
4608     SDValue Slow = DAG.getNode(ISD::FADD, dl, DstVT, SignCvt, SignCvt);
4609 
4610     // TODO: This really should be implemented using a branch rather than a
4611     // select.  We happen to get lucky and machinesink does the right
4612     // thing most of the time.  This would be a good candidate for a
4613     // pseudo-op, or, even better, for whole-function isel.
4614     EVT SetCCVT =
4615         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
4616 
4617     SDValue SignBitTest = DAG.getSetCC(
4618         dl, SetCCVT, Src, DAG.getConstant(0, dl, SrcVT), ISD::SETLT);
4619     Result = DAG.getSelect(dl, DstVT, SignBitTest, Slow, Fast);
4620     return true;
4621   }
4622 
4623   if (DstVT.getScalarType() == MVT::f64) {
4624     // Only expand vector types if we have the appropriate vector bit
4625     // operations.
4626     if (SrcVT.isVector() &&
4627         (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
4628          !isOperationLegalOrCustom(ISD::FADD, DstVT) ||
4629          !isOperationLegalOrCustom(ISD::FSUB, DstVT) ||
4630          !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) ||
4631          !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT)))
4632       return false;
4633 
4634     // Implementation of unsigned i64 to f64 following the algorithm in
4635     // __floatundidf in compiler_rt. This implementation has the advantage
4636     // of performing rounding correctly, both in the default rounding mode
4637     // and in all alternate rounding modes.
4638     SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
4639     SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
4640         BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT);
4641     SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
4642     SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
4643     SDValue HiShift = DAG.getConstant(32, dl, ShiftVT);
4644 
4645     SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
4646     SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
4647     SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
4648     SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
4649     SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
4650     SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
4651     SDValue HiSub = DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
4652     Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
4653     return true;
4654   }
4655 
4656   return false;
4657 }
4658 
4659 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node,
4660                                               SelectionDAG &DAG) const {
4661   SDLoc dl(Node);
4662   unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ?
4663     ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
4664   EVT VT = Node->getValueType(0);
4665   if (isOperationLegalOrCustom(NewOp, VT)) {
4666     SDValue Quiet0 = Node->getOperand(0);
4667     SDValue Quiet1 = Node->getOperand(1);
4668 
4669     if (!Node->getFlags().hasNoNaNs()) {
4670       // Insert canonicalizes if it's possible we need to quiet to get correct
4671       // sNaN behavior.
4672       if (!DAG.isKnownNeverSNaN(Quiet0)) {
4673         Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
4674                              Node->getFlags());
4675       }
4676       if (!DAG.isKnownNeverSNaN(Quiet1)) {
4677         Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
4678                              Node->getFlags());
4679       }
4680     }
4681 
4682     return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
4683   }
4684 
4685   return SDValue();
4686 }
4687 
4688 bool TargetLowering::expandCTPOP(SDNode *Node, SDValue &Result,
4689                                  SelectionDAG &DAG) const {
4690   SDLoc dl(Node);
4691   EVT VT = Node->getValueType(0);
4692   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
4693   SDValue Op = Node->getOperand(0);
4694   unsigned Len = VT.getScalarSizeInBits();
4695   assert(VT.isInteger() && "CTPOP not implemented for this type.");
4696 
4697   // TODO: Add support for irregular type lengths.
4698   if (!(Len <= 128 && Len % 8 == 0))
4699     return false;
4700 
4701   // Only expand vector types if we have the appropriate vector bit operations.
4702   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::ADD, VT) ||
4703                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
4704                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
4705                         (Len != 8 && !isOperationLegalOrCustom(ISD::MUL, VT)) ||
4706                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT)))
4707     return false;
4708 
4709   // This is the "best" algorithm from
4710   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
4711   SDValue Mask55 =
4712       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
4713   SDValue Mask33 =
4714       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
4715   SDValue Mask0F =
4716       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
4717   SDValue Mask01 =
4718       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
4719 
4720   // v = v - ((v >> 1) & 0x55555555...)
4721   Op = DAG.getNode(ISD::SUB, dl, VT, Op,
4722                    DAG.getNode(ISD::AND, dl, VT,
4723                                DAG.getNode(ISD::SRL, dl, VT, Op,
4724                                            DAG.getConstant(1, dl, ShVT)),
4725                                Mask55));
4726   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
4727   Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
4728                    DAG.getNode(ISD::AND, dl, VT,
4729                                DAG.getNode(ISD::SRL, dl, VT, Op,
4730                                            DAG.getConstant(2, dl, ShVT)),
4731                                Mask33));
4732   // v = (v + (v >> 4)) & 0x0F0F0F0F...
4733   Op = DAG.getNode(ISD::AND, dl, VT,
4734                    DAG.getNode(ISD::ADD, dl, VT, Op,
4735                                DAG.getNode(ISD::SRL, dl, VT, Op,
4736                                            DAG.getConstant(4, dl, ShVT))),
4737                    Mask0F);
4738   // v = (v * 0x01010101...) >> (Len - 8)
4739   if (Len > 8)
4740     Op =
4741         DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
4742                     DAG.getConstant(Len - 8, dl, ShVT));
4743 
4744   Result = Op;
4745   return true;
4746 }
4747 
4748 bool TargetLowering::expandCTLZ(SDNode *Node, SDValue &Result,
4749                                 SelectionDAG &DAG) const {
4750   SDLoc dl(Node);
4751   EVT VT = Node->getValueType(0);
4752   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
4753   SDValue Op = Node->getOperand(0);
4754   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
4755 
4756   // If the non-ZERO_UNDEF version is supported we can use that instead.
4757   if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF &&
4758       isOperationLegalOrCustom(ISD::CTLZ, VT)) {
4759     Result = DAG.getNode(ISD::CTLZ, dl, VT, Op);
4760     return true;
4761   }
4762 
4763   // If the ZERO_UNDEF version is supported use that and handle the zero case.
4764   if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) {
4765     EVT SetCCVT =
4766         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
4767     SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op);
4768     SDValue Zero = DAG.getConstant(0, dl, VT);
4769     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
4770     Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero,
4771                          DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
4772     return true;
4773   }
4774 
4775   // Only expand vector types if we have the appropriate vector bit operations.
4776   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
4777                         !isOperationLegalOrCustom(ISD::CTPOP, VT) ||
4778                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
4779                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
4780     return false;
4781 
4782   // for now, we do this:
4783   // x = x | (x >> 1);
4784   // x = x | (x >> 2);
4785   // ...
4786   // x = x | (x >>16);
4787   // x = x | (x >>32); // for 64-bit input
4788   // return popcount(~x);
4789   //
4790   // Ref: "Hacker's Delight" by Henry Warren
4791   for (unsigned i = 0; (1U << i) <= (NumBitsPerElt / 2); ++i) {
4792     SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
4793     Op = DAG.getNode(ISD::OR, dl, VT, Op,
4794                      DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
4795   }
4796   Op = DAG.getNOT(dl, Op, VT);
4797   Result = DAG.getNode(ISD::CTPOP, dl, VT, Op);
4798   return true;
4799 }
4800 
4801 bool TargetLowering::expandCTTZ(SDNode *Node, SDValue &Result,
4802                                 SelectionDAG &DAG) const {
4803   SDLoc dl(Node);
4804   EVT VT = Node->getValueType(0);
4805   SDValue Op = Node->getOperand(0);
4806   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
4807 
4808   // If the non-ZERO_UNDEF version is supported we can use that instead.
4809   if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
4810       isOperationLegalOrCustom(ISD::CTTZ, VT)) {
4811     Result = DAG.getNode(ISD::CTTZ, dl, VT, Op);
4812     return true;
4813   }
4814 
4815   // If the ZERO_UNDEF version is supported use that and handle the zero case.
4816   if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) {
4817     EVT SetCCVT =
4818         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
4819     SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op);
4820     SDValue Zero = DAG.getConstant(0, dl, VT);
4821     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
4822     Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero,
4823                          DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
4824     return true;
4825   }
4826 
4827   // Only expand vector types if we have the appropriate vector bit operations.
4828   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
4829                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
4830                          !isOperationLegalOrCustom(ISD::CTLZ, VT)) ||
4831                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
4832                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT) ||
4833                         !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
4834     return false;
4835 
4836   // for now, we use: { return popcount(~x & (x - 1)); }
4837   // unless the target has ctlz but not ctpop, in which case we use:
4838   // { return 32 - nlz(~x & (x-1)); }
4839   // Ref: "Hacker's Delight" by Henry Warren
4840   SDValue Tmp = DAG.getNode(
4841       ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
4842       DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
4843 
4844   // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
4845   if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) {
4846     Result =
4847         DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
4848                     DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
4849     return true;
4850   }
4851 
4852   Result = DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
4853   return true;
4854 }
4855 
4856 bool TargetLowering::expandABS(SDNode *N, SDValue &Result,
4857                                SelectionDAG &DAG) const {
4858   SDLoc dl(N);
4859   EVT VT = N->getValueType(0);
4860   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
4861   SDValue Op = N->getOperand(0);
4862 
4863   // Only expand vector types if we have the appropriate vector operations.
4864   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SRA, VT) ||
4865                         !isOperationLegalOrCustom(ISD::ADD, VT) ||
4866                         !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
4867     return false;
4868 
4869   SDValue Shift =
4870       DAG.getNode(ISD::SRA, dl, VT, Op,
4871                   DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT));
4872   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, Op, Shift);
4873   Result = DAG.getNode(ISD::XOR, dl, VT, Add, Shift);
4874   return true;
4875 }
4876 
4877 SDValue TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
4878                                             SelectionDAG &DAG) const {
4879   SDLoc SL(LD);
4880   SDValue Chain = LD->getChain();
4881   SDValue BasePTR = LD->getBasePtr();
4882   EVT SrcVT = LD->getMemoryVT();
4883   ISD::LoadExtType ExtType = LD->getExtensionType();
4884 
4885   unsigned NumElem = SrcVT.getVectorNumElements();
4886 
4887   EVT SrcEltVT = SrcVT.getScalarType();
4888   EVT DstEltVT = LD->getValueType(0).getScalarType();
4889 
4890   unsigned Stride = SrcEltVT.getSizeInBits() / 8;
4891   assert(SrcEltVT.isByteSized());
4892 
4893   SmallVector<SDValue, 8> Vals;
4894   SmallVector<SDValue, 8> LoadChains;
4895 
4896   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
4897     SDValue ScalarLoad =
4898         DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
4899                        LD->getPointerInfo().getWithOffset(Idx * Stride),
4900                        SrcEltVT, MinAlign(LD->getAlignment(), Idx * Stride),
4901                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
4902 
4903     BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, Stride);
4904 
4905     Vals.push_back(ScalarLoad.getValue(0));
4906     LoadChains.push_back(ScalarLoad.getValue(1));
4907   }
4908 
4909   SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
4910   SDValue Value = DAG.getBuildVector(LD->getValueType(0), SL, Vals);
4911 
4912   return DAG.getMergeValues({Value, NewChain}, SL);
4913 }
4914 
4915 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
4916                                              SelectionDAG &DAG) const {
4917   SDLoc SL(ST);
4918 
4919   SDValue Chain = ST->getChain();
4920   SDValue BasePtr = ST->getBasePtr();
4921   SDValue Value = ST->getValue();
4922   EVT StVT = ST->getMemoryVT();
4923 
4924   // The type of the data we want to save
4925   EVT RegVT = Value.getValueType();
4926   EVT RegSclVT = RegVT.getScalarType();
4927 
4928   // The type of data as saved in memory.
4929   EVT MemSclVT = StVT.getScalarType();
4930 
4931   EVT IdxVT = getVectorIdxTy(DAG.getDataLayout());
4932   unsigned NumElem = StVT.getVectorNumElements();
4933 
4934   // A vector must always be stored in memory as-is, i.e. without any padding
4935   // between the elements, since various code depend on it, e.g. in the
4936   // handling of a bitcast of a vector type to int, which may be done with a
4937   // vector store followed by an integer load. A vector that does not have
4938   // elements that are byte-sized must therefore be stored as an integer
4939   // built out of the extracted vector elements.
4940   if (!MemSclVT.isByteSized()) {
4941     unsigned NumBits = StVT.getSizeInBits();
4942     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
4943 
4944     SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
4945 
4946     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
4947       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
4948                                 DAG.getConstant(Idx, SL, IdxVT));
4949       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
4950       SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
4951       unsigned ShiftIntoIdx =
4952           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
4953       SDValue ShiftAmount =
4954           DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
4955       SDValue ShiftedElt =
4956           DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
4957       CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
4958     }
4959 
4960     return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
4961                         ST->getAlignment(), ST->getMemOperand()->getFlags(),
4962                         ST->getAAInfo());
4963   }
4964 
4965   // Store Stride in bytes
4966   unsigned Stride = MemSclVT.getSizeInBits() / 8;
4967   assert(Stride && "Zero stride!");
4968   // Extract each of the elements from the original vector and save them into
4969   // memory individually.
4970   SmallVector<SDValue, 8> Stores;
4971   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
4972     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
4973                               DAG.getConstant(Idx, SL, IdxVT));
4974 
4975     SDValue Ptr = DAG.getObjectPtrOffset(SL, BasePtr, Idx * Stride);
4976 
4977     // This scalar TruncStore may be illegal, but we legalize it later.
4978     SDValue Store = DAG.getTruncStore(
4979         Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
4980         MemSclVT, MinAlign(ST->getAlignment(), Idx * Stride),
4981         ST->getMemOperand()->getFlags(), ST->getAAInfo());
4982 
4983     Stores.push_back(Store);
4984   }
4985 
4986   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
4987 }
4988 
4989 std::pair<SDValue, SDValue>
4990 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
4991   assert(LD->getAddressingMode() == ISD::UNINDEXED &&
4992          "unaligned indexed loads not implemented!");
4993   SDValue Chain = LD->getChain();
4994   SDValue Ptr = LD->getBasePtr();
4995   EVT VT = LD->getValueType(0);
4996   EVT LoadedVT = LD->getMemoryVT();
4997   SDLoc dl(LD);
4998   auto &MF = DAG.getMachineFunction();
4999 
5000   if (VT.isFloatingPoint() || VT.isVector()) {
5001     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
5002     if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
5003       if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
5004           LoadedVT.isVector()) {
5005         // Scalarize the load and let the individual components be handled.
5006         SDValue Scalarized = scalarizeVectorLoad(LD, DAG);
5007         if (Scalarized->getOpcode() == ISD::MERGE_VALUES)
5008           return std::make_pair(Scalarized.getOperand(0), Scalarized.getOperand(1));
5009         return std::make_pair(Scalarized.getValue(0), Scalarized.getValue(1));
5010       }
5011 
5012       // Expand to a (misaligned) integer load of the same size,
5013       // then bitconvert to floating point or vector.
5014       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
5015                                     LD->getMemOperand());
5016       SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
5017       if (LoadedVT != VT)
5018         Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
5019                              ISD::ANY_EXTEND, dl, VT, Result);
5020 
5021       return std::make_pair(Result, newLoad.getValue(1));
5022     }
5023 
5024     // Copy the value to a (aligned) stack slot using (unaligned) integer
5025     // loads and stores, then do a (aligned) load from the stack slot.
5026     MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
5027     unsigned LoadedBytes = LoadedVT.getStoreSize();
5028     unsigned RegBytes = RegVT.getSizeInBits() / 8;
5029     unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
5030 
5031     // Make sure the stack slot is also aligned for the register type.
5032     SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
5033     auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
5034     SmallVector<SDValue, 8> Stores;
5035     SDValue StackPtr = StackBase;
5036     unsigned Offset = 0;
5037 
5038     EVT PtrVT = Ptr.getValueType();
5039     EVT StackPtrVT = StackPtr.getValueType();
5040 
5041     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
5042     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
5043 
5044     // Do all but one copies using the full register width.
5045     for (unsigned i = 1; i < NumRegs; i++) {
5046       // Load one integer register's worth from the original location.
5047       SDValue Load = DAG.getLoad(
5048           RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
5049           MinAlign(LD->getAlignment(), Offset), LD->getMemOperand()->getFlags(),
5050           LD->getAAInfo());
5051       // Follow the load with a store to the stack slot.  Remember the store.
5052       Stores.push_back(DAG.getStore(
5053           Load.getValue(1), dl, Load, StackPtr,
5054           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
5055       // Increment the pointers.
5056       Offset += RegBytes;
5057 
5058       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
5059       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
5060     }
5061 
5062     // The last copy may be partial.  Do an extending load.
5063     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
5064                                   8 * (LoadedBytes - Offset));
5065     SDValue Load =
5066         DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
5067                        LD->getPointerInfo().getWithOffset(Offset), MemVT,
5068                        MinAlign(LD->getAlignment(), Offset),
5069                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
5070     // Follow the load with a store to the stack slot.  Remember the store.
5071     // On big-endian machines this requires a truncating store to ensure
5072     // that the bits end up in the right place.
5073     Stores.push_back(DAG.getTruncStore(
5074         Load.getValue(1), dl, Load, StackPtr,
5075         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
5076 
5077     // The order of the stores doesn't matter - say it with a TokenFactor.
5078     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
5079 
5080     // Finally, perform the original load only redirected to the stack slot.
5081     Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
5082                           MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
5083                           LoadedVT);
5084 
5085     // Callers expect a MERGE_VALUES node.
5086     return std::make_pair(Load, TF);
5087   }
5088 
5089   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
5090          "Unaligned load of unsupported type.");
5091 
5092   // Compute the new VT that is half the size of the old one.  This is an
5093   // integer MVT.
5094   unsigned NumBits = LoadedVT.getSizeInBits();
5095   EVT NewLoadedVT;
5096   NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
5097   NumBits >>= 1;
5098 
5099   unsigned Alignment = LD->getAlignment();
5100   unsigned IncrementSize = NumBits / 8;
5101   ISD::LoadExtType HiExtType = LD->getExtensionType();
5102 
5103   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
5104   if (HiExtType == ISD::NON_EXTLOAD)
5105     HiExtType = ISD::ZEXTLOAD;
5106 
5107   // Load the value in two parts
5108   SDValue Lo, Hi;
5109   if (DAG.getDataLayout().isLittleEndian()) {
5110     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
5111                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
5112                         LD->getAAInfo());
5113 
5114     Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
5115     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
5116                         LD->getPointerInfo().getWithOffset(IncrementSize),
5117                         NewLoadedVT, MinAlign(Alignment, IncrementSize),
5118                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
5119   } else {
5120     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
5121                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
5122                         LD->getAAInfo());
5123 
5124     Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
5125     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
5126                         LD->getPointerInfo().getWithOffset(IncrementSize),
5127                         NewLoadedVT, MinAlign(Alignment, IncrementSize),
5128                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
5129   }
5130 
5131   // aggregate the two parts
5132   SDValue ShiftAmount =
5133       DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
5134                                                     DAG.getDataLayout()));
5135   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
5136   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
5137 
5138   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
5139                              Hi.getValue(1));
5140 
5141   return std::make_pair(Result, TF);
5142 }
5143 
5144 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
5145                                              SelectionDAG &DAG) const {
5146   assert(ST->getAddressingMode() == ISD::UNINDEXED &&
5147          "unaligned indexed stores not implemented!");
5148   SDValue Chain = ST->getChain();
5149   SDValue Ptr = ST->getBasePtr();
5150   SDValue Val = ST->getValue();
5151   EVT VT = Val.getValueType();
5152   int Alignment = ST->getAlignment();
5153   auto &MF = DAG.getMachineFunction();
5154   EVT MemVT = ST->getMemoryVT();
5155 
5156   SDLoc dl(ST);
5157   if (MemVT.isFloatingPoint() || MemVT.isVector()) {
5158     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
5159     if (isTypeLegal(intVT)) {
5160       if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
5161           MemVT.isVector()) {
5162         // Scalarize the store and let the individual components be handled.
5163         SDValue Result = scalarizeVectorStore(ST, DAG);
5164 
5165         return Result;
5166       }
5167       // Expand to a bitconvert of the value to the integer type of the
5168       // same size, then a (misaligned) int store.
5169       // FIXME: Does not handle truncating floating point stores!
5170       SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
5171       Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
5172                             Alignment, ST->getMemOperand()->getFlags());
5173       return Result;
5174     }
5175     // Do a (aligned) store to a stack slot, then copy from the stack slot
5176     // to the final destination using (unaligned) integer loads and stores.
5177     EVT StoredVT = ST->getMemoryVT();
5178     MVT RegVT =
5179       getRegisterType(*DAG.getContext(),
5180                       EVT::getIntegerVT(*DAG.getContext(),
5181                                         StoredVT.getSizeInBits()));
5182     EVT PtrVT = Ptr.getValueType();
5183     unsigned StoredBytes = StoredVT.getStoreSize();
5184     unsigned RegBytes = RegVT.getSizeInBits() / 8;
5185     unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
5186 
5187     // Make sure the stack slot is also aligned for the register type.
5188     SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
5189     auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
5190 
5191     // Perform the original store, only redirected to the stack slot.
5192     SDValue Store = DAG.getTruncStore(
5193         Chain, dl, Val, StackPtr,
5194         MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoredVT);
5195 
5196     EVT StackPtrVT = StackPtr.getValueType();
5197 
5198     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
5199     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
5200     SmallVector<SDValue, 8> Stores;
5201     unsigned Offset = 0;
5202 
5203     // Do all but one copies using the full register width.
5204     for (unsigned i = 1; i < NumRegs; i++) {
5205       // Load one integer register's worth from the stack slot.
5206       SDValue Load = DAG.getLoad(
5207           RegVT, dl, Store, StackPtr,
5208           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
5209       // Store it to the final location.  Remember the store.
5210       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
5211                                     ST->getPointerInfo().getWithOffset(Offset),
5212                                     MinAlign(ST->getAlignment(), Offset),
5213                                     ST->getMemOperand()->getFlags()));
5214       // Increment the pointers.
5215       Offset += RegBytes;
5216       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
5217       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
5218     }
5219 
5220     // The last store may be partial.  Do a truncating store.  On big-endian
5221     // machines this requires an extending load from the stack slot to ensure
5222     // that the bits are in the right place.
5223     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
5224                                   8 * (StoredBytes - Offset));
5225 
5226     // Load from the stack slot.
5227     SDValue Load = DAG.getExtLoad(
5228         ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
5229         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT);
5230 
5231     Stores.push_back(
5232         DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
5233                           ST->getPointerInfo().getWithOffset(Offset), MemVT,
5234                           MinAlign(ST->getAlignment(), Offset),
5235                           ST->getMemOperand()->getFlags(), ST->getAAInfo()));
5236     // The order of the stores doesn't matter - say it with a TokenFactor.
5237     SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
5238     return Result;
5239   }
5240 
5241   assert(ST->getMemoryVT().isInteger() &&
5242          !ST->getMemoryVT().isVector() &&
5243          "Unaligned store of unknown type.");
5244   // Get the half-size VT
5245   EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
5246   int NumBits = NewStoredVT.getSizeInBits();
5247   int IncrementSize = NumBits / 8;
5248 
5249   // Divide the stored value in two parts.
5250   SDValue ShiftAmount =
5251       DAG.getConstant(NumBits, dl, getShiftAmountTy(Val.getValueType(),
5252                                                     DAG.getDataLayout()));
5253   SDValue Lo = Val;
5254   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
5255 
5256   // Store the two parts
5257   SDValue Store1, Store2;
5258   Store1 = DAG.getTruncStore(Chain, dl,
5259                              DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
5260                              Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
5261                              ST->getMemOperand()->getFlags());
5262 
5263   Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
5264   Alignment = MinAlign(Alignment, IncrementSize);
5265   Store2 = DAG.getTruncStore(
5266       Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
5267       ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
5268       ST->getMemOperand()->getFlags(), ST->getAAInfo());
5269 
5270   SDValue Result =
5271     DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
5272   return Result;
5273 }
5274 
5275 SDValue
5276 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask,
5277                                        const SDLoc &DL, EVT DataVT,
5278                                        SelectionDAG &DAG,
5279                                        bool IsCompressedMemory) const {
5280   SDValue Increment;
5281   EVT AddrVT = Addr.getValueType();
5282   EVT MaskVT = Mask.getValueType();
5283   assert(DataVT.getVectorNumElements() == MaskVT.getVectorNumElements() &&
5284          "Incompatible types of Data and Mask");
5285   if (IsCompressedMemory) {
5286     // Incrementing the pointer according to number of '1's in the mask.
5287     EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
5288     SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
5289     if (MaskIntVT.getSizeInBits() < 32) {
5290       MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
5291       MaskIntVT = MVT::i32;
5292     }
5293 
5294     // Count '1's with POPCNT.
5295     Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
5296     Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
5297     // Scale is an element size in bytes.
5298     SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
5299                                     AddrVT);
5300     Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
5301   } else
5302     Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT);
5303 
5304   return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
5305 }
5306 
5307 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG,
5308                                        SDValue Idx,
5309                                        EVT VecVT,
5310                                        const SDLoc &dl) {
5311   if (isa<ConstantSDNode>(Idx))
5312     return Idx;
5313 
5314   EVT IdxVT = Idx.getValueType();
5315   unsigned NElts = VecVT.getVectorNumElements();
5316   if (isPowerOf2_32(NElts)) {
5317     APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(),
5318                                      Log2_32(NElts));
5319     return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
5320                        DAG.getConstant(Imm, dl, IdxVT));
5321   }
5322 
5323   return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
5324                      DAG.getConstant(NElts - 1, dl, IdxVT));
5325 }
5326 
5327 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG,
5328                                                 SDValue VecPtr, EVT VecVT,
5329                                                 SDValue Index) const {
5330   SDLoc dl(Index);
5331   // Make sure the index type is big enough to compute in.
5332   Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
5333 
5334   EVT EltVT = VecVT.getVectorElementType();
5335 
5336   // Calculate the element offset and add it to the pointer.
5337   unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
5338   assert(EltSize * 8 == EltVT.getSizeInBits() &&
5339          "Converting bits to bytes lost precision");
5340 
5341   Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl);
5342 
5343   EVT IdxVT = Index.getValueType();
5344 
5345   Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
5346                       DAG.getConstant(EltSize, dl, IdxVT));
5347   return DAG.getNode(ISD::ADD, dl, IdxVT, VecPtr, Index);
5348 }
5349 
5350 //===----------------------------------------------------------------------===//
5351 // Implementation of Emulated TLS Model
5352 //===----------------------------------------------------------------------===//
5353 
5354 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
5355                                                 SelectionDAG &DAG) const {
5356   // Access to address of TLS varialbe xyz is lowered to a function call:
5357   //   __emutls_get_address( address of global variable named "__emutls_v.xyz" )
5358   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5359   PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
5360   SDLoc dl(GA);
5361 
5362   ArgListTy Args;
5363   ArgListEntry Entry;
5364   std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
5365   Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
5366   StringRef EmuTlsVarName(NameString);
5367   GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
5368   assert(EmuTlsVar && "Cannot find EmuTlsVar ");
5369   Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
5370   Entry.Ty = VoidPtrType;
5371   Args.push_back(Entry);
5372 
5373   SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
5374 
5375   TargetLowering::CallLoweringInfo CLI(DAG);
5376   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
5377   CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
5378   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
5379 
5380   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5381   // At last for X86 targets, maybe good for other targets too?
5382   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5383   MFI.setAdjustsStack(true); // Is this only for X86 target?
5384   MFI.setHasCalls(true);
5385 
5386   assert((GA->getOffset() == 0) &&
5387          "Emulated TLS must have zero offset in GlobalAddressSDNode");
5388   return CallResult.first;
5389 }
5390 
5391 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
5392                                                 SelectionDAG &DAG) const {
5393   assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
5394   if (!isCtlzFast())
5395     return SDValue();
5396   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5397   SDLoc dl(Op);
5398   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
5399     if (C->isNullValue() && CC == ISD::SETEQ) {
5400       EVT VT = Op.getOperand(0).getValueType();
5401       SDValue Zext = Op.getOperand(0);
5402       if (VT.bitsLT(MVT::i32)) {
5403         VT = MVT::i32;
5404         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
5405       }
5406       unsigned Log2b = Log2_32(VT.getSizeInBits());
5407       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
5408       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
5409                                 DAG.getConstant(Log2b, dl, MVT::i32));
5410       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
5411     }
5412   }
5413   return SDValue();
5414 }
5415 
5416 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const {
5417   unsigned Opcode = Node->getOpcode();
5418   SDValue LHS = Node->getOperand(0);
5419   SDValue RHS = Node->getOperand(1);
5420   EVT VT = LHS.getValueType();
5421   SDLoc dl(Node);
5422 
5423   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
5424   assert(VT.isInteger() && "Expected operands to be integers");
5425 
5426   // usub.sat(a, b) -> umax(a, b) - b
5427   if (Opcode == ISD::USUBSAT && isOperationLegalOrCustom(ISD::UMAX, VT)) {
5428     SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
5429     return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
5430   }
5431 
5432   if (Opcode == ISD::UADDSAT && isOperationLegalOrCustom(ISD::UMIN, VT)) {
5433     SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
5434     SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
5435     return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
5436   }
5437 
5438   unsigned OverflowOp;
5439   switch (Opcode) {
5440   case ISD::SADDSAT:
5441     OverflowOp = ISD::SADDO;
5442     break;
5443   case ISD::UADDSAT:
5444     OverflowOp = ISD::UADDO;
5445     break;
5446   case ISD::SSUBSAT:
5447     OverflowOp = ISD::SSUBO;
5448     break;
5449   case ISD::USUBSAT:
5450     OverflowOp = ISD::USUBO;
5451     break;
5452   default:
5453     llvm_unreachable("Expected method to receive signed or unsigned saturation "
5454                      "addition or subtraction node.");
5455   }
5456 
5457   unsigned BitWidth = LHS.getScalarValueSizeInBits();
5458   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
5459   SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT),
5460                                LHS, RHS);
5461   SDValue SumDiff = Result.getValue(0);
5462   SDValue Overflow = Result.getValue(1);
5463   SDValue Zero = DAG.getConstant(0, dl, VT);
5464   SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
5465 
5466   if (Opcode == ISD::UADDSAT) {
5467     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
5468       // (LHS + RHS) | OverflowMask
5469       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
5470       return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
5471     }
5472     // Overflow ? 0xffff.... : (LHS + RHS)
5473     return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
5474   } else if (Opcode == ISD::USUBSAT) {
5475     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
5476       // (LHS - RHS) & ~OverflowMask
5477       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
5478       SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
5479       return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
5480     }
5481     // Overflow ? 0 : (LHS - RHS)
5482     return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
5483   } else {
5484     // SatMax -> Overflow && SumDiff < 0
5485     // SatMin -> Overflow && SumDiff >= 0
5486     APInt MinVal = APInt::getSignedMinValue(BitWidth);
5487     APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
5488     SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
5489     SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
5490     SDValue SumNeg = DAG.getSetCC(dl, BoolVT, SumDiff, Zero, ISD::SETLT);
5491     Result = DAG.getSelect(dl, VT, SumNeg, SatMax, SatMin);
5492     return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
5493   }
5494 }
5495 
5496 SDValue
5497 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const {
5498   assert((Node->getOpcode() == ISD::SMULFIX ||
5499           Node->getOpcode() == ISD::UMULFIX) &&
5500          "Expected opcode to be SMULFIX or UMULFIX.");
5501 
5502   SDLoc dl(Node);
5503   SDValue LHS = Node->getOperand(0);
5504   SDValue RHS = Node->getOperand(1);
5505   EVT VT = LHS.getValueType();
5506   unsigned Scale = Node->getConstantOperandVal(2);
5507 
5508   // [us]mul.fix(a, b, 0) -> mul(a, b)
5509   if (!Scale) {
5510     if (VT.isVector() && !isOperationLegalOrCustom(ISD::MUL, VT))
5511       return SDValue();
5512     return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
5513   }
5514 
5515   unsigned VTSize = VT.getScalarSizeInBits();
5516   bool Signed = Node->getOpcode() == ISD::SMULFIX;
5517 
5518   assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
5519          "Expected scale to be less than the number of bits if signed or at "
5520          "most the number of bits if unsigned.");
5521   assert(LHS.getValueType() == RHS.getValueType() &&
5522          "Expected both operands to be the same type");
5523 
5524   // Get the upper and lower bits of the result.
5525   SDValue Lo, Hi;
5526   unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
5527   unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
5528   if (isOperationLegalOrCustom(LoHiOp, VT)) {
5529     SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
5530     Lo = Result.getValue(0);
5531     Hi = Result.getValue(1);
5532   } else if (isOperationLegalOrCustom(HiOp, VT)) {
5533     Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
5534     Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
5535   } else if (VT.isVector()) {
5536     return SDValue();
5537   } else {
5538     report_fatal_error("Unable to expand fixed point multiplication.");
5539   }
5540 
5541   if (Scale == VTSize)
5542     // Result is just the top half since we'd be shifting by the width of the
5543     // operand.
5544     return Hi;
5545 
5546   // The result will need to be shifted right by the scale since both operands
5547   // are scaled. The result is given to us in 2 halves, so we only want part of
5548   // both in the result.
5549   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
5550   return DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
5551                      DAG.getConstant(Scale, dl, ShiftTy));
5552 }
5553 
5554 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result,
5555                                 SDValue &Overflow, SelectionDAG &DAG) const {
5556   SDLoc dl(Node);
5557   EVT VT = Node->getValueType(0);
5558   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
5559   SDValue LHS = Node->getOperand(0);
5560   SDValue RHS = Node->getOperand(1);
5561   bool isSigned = Node->getOpcode() == ISD::SMULO;
5562 
5563   // For power-of-two multiplications we can use a simpler shift expansion.
5564   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5565     const APInt &C = RHSC->getAPIntValue();
5566     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5567     if (C.isPowerOf2()) {
5568       // smulo(x, signed_min) is same as umulo(x, signed_min).
5569       bool UseArithShift = isSigned && !C.isMinSignedValue();
5570       EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout());
5571       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy);
5572       Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
5573       Overflow = DAG.getSetCC(dl, SetCCVT,
5574           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5575                       dl, VT, Result, ShiftAmt),
5576           LHS, ISD::SETNE);
5577       return true;
5578     }
5579   }
5580 
5581   EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2);
5582   if (VT.isVector())
5583     WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT,
5584                               VT.getVectorNumElements());
5585 
5586   SDValue BottomHalf;
5587   SDValue TopHalf;
5588   static const unsigned Ops[2][3] =
5589       { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
5590         { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
5591   if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
5592     BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
5593     TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
5594   } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
5595     BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
5596                              RHS);
5597     TopHalf = BottomHalf.getValue(1);
5598   } else if (isTypeLegal(WideVT)) {
5599     LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
5600     RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
5601     SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
5602     BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
5603     SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl,
5604         getShiftAmountTy(WideVT, DAG.getDataLayout()));
5605     TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
5606                           DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
5607   } else {
5608     if (VT.isVector())
5609       return false;
5610 
5611     // We can fall back to a libcall with an illegal type for the MUL if we
5612     // have a libcall big enough.
5613     // Also, we can fall back to a division in some cases, but that's a big
5614     // performance hit in the general case.
5615     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
5616     if (WideVT == MVT::i16)
5617       LC = RTLIB::MUL_I16;
5618     else if (WideVT == MVT::i32)
5619       LC = RTLIB::MUL_I32;
5620     else if (WideVT == MVT::i64)
5621       LC = RTLIB::MUL_I64;
5622     else if (WideVT == MVT::i128)
5623       LC = RTLIB::MUL_I128;
5624     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
5625 
5626     SDValue HiLHS;
5627     SDValue HiRHS;
5628     if (isSigned) {
5629       // The high part is obtained by SRA'ing all but one of the bits of low
5630       // part.
5631       unsigned LoSize = VT.getSizeInBits();
5632       HiLHS =
5633           DAG.getNode(ISD::SRA, dl, VT, LHS,
5634                       DAG.getConstant(LoSize - 1, dl,
5635                                       getPointerTy(DAG.getDataLayout())));
5636       HiRHS =
5637           DAG.getNode(ISD::SRA, dl, VT, RHS,
5638                       DAG.getConstant(LoSize - 1, dl,
5639                                       getPointerTy(DAG.getDataLayout())));
5640     } else {
5641         HiLHS = DAG.getConstant(0, dl, VT);
5642         HiRHS = DAG.getConstant(0, dl, VT);
5643     }
5644 
5645     // Here we're passing the 2 arguments explicitly as 4 arguments that are
5646     // pre-lowered to the correct types. This all depends upon WideVT not
5647     // being a legal type for the architecture and thus has to be split to
5648     // two arguments.
5649     SDValue Ret;
5650     if (DAG.getDataLayout().isLittleEndian()) {
5651       // Halves of WideVT are packed into registers in different order
5652       // depending on platform endianness. This is usually handled by
5653       // the C calling convention, but we can't defer to it in
5654       // the legalizer.
5655       SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
5656       Ret = makeLibCall(DAG, LC, WideVT, Args, isSigned, dl,
5657           /* doesNotReturn */ false, /* isReturnValueUsed */ true,
5658           /* isPostTypeLegalization */ true).first;
5659     } else {
5660       SDValue Args[] = { HiLHS, LHS, HiRHS, RHS };
5661       Ret = makeLibCall(DAG, LC, WideVT, Args, isSigned, dl,
5662           /* doesNotReturn */ false, /* isReturnValueUsed */ true,
5663           /* isPostTypeLegalization */ true).first;
5664     }
5665     assert(Ret.getOpcode() == ISD::MERGE_VALUES &&
5666            "Ret value is a collection of constituent nodes holding result.");
5667     if (DAG.getDataLayout().isLittleEndian()) {
5668       // Same as above.
5669       BottomHalf = Ret.getOperand(0);
5670       TopHalf = Ret.getOperand(1);
5671     } else {
5672       BottomHalf = Ret.getOperand(1);
5673       TopHalf = Ret.getOperand(0);
5674     }
5675   }
5676 
5677   Result = BottomHalf;
5678   if (isSigned) {
5679     SDValue ShiftAmt = DAG.getConstant(
5680         VT.getScalarSizeInBits() - 1, dl,
5681         getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout()));
5682     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
5683     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
5684   } else {
5685     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
5686                             DAG.getConstant(0, dl, VT), ISD::SETNE);
5687   }
5688 
5689   // Truncate the result if SetCC returns a larger type than needed.
5690   EVT RType = Node->getValueType(1);
5691   if (RType.getSizeInBits() < Overflow.getValueSizeInBits())
5692     Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
5693 
5694   assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
5695          "Unexpected result type for S/UMULO legalization");
5696   return true;
5697 }
5698 
5699 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const {
5700   SDLoc dl(Node);
5701   bool NoNaN = Node->getFlags().hasNoNaNs();
5702   unsigned BaseOpcode = 0;
5703   switch (Node->getOpcode()) {
5704   default: llvm_unreachable("Expected VECREDUCE opcode");
5705   case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break;
5706   case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break;
5707   case ISD::VECREDUCE_ADD:  BaseOpcode = ISD::ADD; break;
5708   case ISD::VECREDUCE_MUL:  BaseOpcode = ISD::MUL; break;
5709   case ISD::VECREDUCE_AND:  BaseOpcode = ISD::AND; break;
5710   case ISD::VECREDUCE_OR:   BaseOpcode = ISD::OR; break;
5711   case ISD::VECREDUCE_XOR:  BaseOpcode = ISD::XOR; break;
5712   case ISD::VECREDUCE_SMAX: BaseOpcode = ISD::SMAX; break;
5713   case ISD::VECREDUCE_SMIN: BaseOpcode = ISD::SMIN; break;
5714   case ISD::VECREDUCE_UMAX: BaseOpcode = ISD::UMAX; break;
5715   case ISD::VECREDUCE_UMIN: BaseOpcode = ISD::UMIN; break;
5716   case ISD::VECREDUCE_FMAX:
5717     BaseOpcode = NoNaN ? ISD::FMAXNUM : ISD::FMAXIMUM;
5718     break;
5719   case ISD::VECREDUCE_FMIN:
5720     BaseOpcode = NoNaN ? ISD::FMINNUM : ISD::FMINIMUM;
5721     break;
5722   }
5723 
5724   SDValue Op = Node->getOperand(0);
5725   EVT VT = Op.getValueType();
5726 
5727   // Try to use a shuffle reduction for power of two vectors.
5728   if (VT.isPow2VectorType()) {
5729     while (VT.getVectorNumElements() > 1) {
5730       EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
5731       if (!isOperationLegalOrCustom(BaseOpcode, HalfVT))
5732         break;
5733 
5734       SDValue Lo, Hi;
5735       std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
5736       Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi);
5737       VT = HalfVT;
5738     }
5739   }
5740 
5741   EVT EltVT = VT.getVectorElementType();
5742   unsigned NumElts = VT.getVectorNumElements();
5743 
5744   SmallVector<SDValue, 8> Ops;
5745   DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
5746 
5747   SDValue Res = Ops[0];
5748   for (unsigned i = 1; i < NumElts; i++)
5749     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags());
5750 
5751   // Result type may be wider than element type.
5752   if (EltVT != Node->getValueType(0))
5753     Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
5754   return Res;
5755 }
5756