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