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   // Constant fold or commute setcc.
2357   if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
2358     return Fold;
2359 
2360   // Ensure that the constant occurs on the RHS and fold constant comparisons.
2361   // TODO: Handle non-splat vector constants. All undef causes trouble.
2362   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
2363   if (isConstOrConstSplat(N0) &&
2364       (DCI.isBeforeLegalizeOps() ||
2365        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
2366     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
2367 
2368   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
2369     const APInt &C1 = N1C->getAPIntValue();
2370 
2371     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
2372     // equality comparison, then we're just comparing whether X itself is
2373     // zero.
2374     if (N0.getOpcode() == ISD::SRL && (C1.isNullValue() || C1.isOneValue()) &&
2375         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
2376         N0.getOperand(1).getOpcode() == ISD::Constant) {
2377       const APInt &ShAmt = N0.getConstantOperandAPInt(1);
2378       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2379           ShAmt == Log2_32(N0.getValueSizeInBits())) {
2380         if ((C1 == 0) == (Cond == ISD::SETEQ)) {
2381           // (srl (ctlz x), 5) == 0  -> X != 0
2382           // (srl (ctlz x), 5) != 1  -> X != 0
2383           Cond = ISD::SETNE;
2384         } else {
2385           // (srl (ctlz x), 5) != 0  -> X == 0
2386           // (srl (ctlz x), 5) == 1  -> X == 0
2387           Cond = ISD::SETEQ;
2388         }
2389         SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
2390         return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
2391                             Zero, Cond);
2392       }
2393     }
2394 
2395     SDValue CTPOP = N0;
2396     // Look through truncs that don't change the value of a ctpop.
2397     if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
2398       CTPOP = N0.getOperand(0);
2399 
2400     if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
2401         (N0 == CTPOP ||
2402          N0.getValueSizeInBits() > Log2_32_Ceil(CTPOP.getValueSizeInBits()))) {
2403       EVT CTVT = CTPOP.getValueType();
2404       SDValue CTOp = CTPOP.getOperand(0);
2405 
2406       // (ctpop x) u< 2 -> (x & x-1) == 0
2407       // (ctpop x) u> 1 -> (x & x-1) != 0
2408       if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
2409         SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
2410                                   DAG.getConstant(1, dl, CTVT));
2411         SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
2412         ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
2413         return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC);
2414       }
2415 
2416       // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
2417     }
2418 
2419     // (zext x) == C --> x == (trunc C)
2420     // (sext x) == C --> x == (trunc C)
2421     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2422         DCI.isBeforeLegalize() && N0->hasOneUse()) {
2423       unsigned MinBits = N0.getValueSizeInBits();
2424       SDValue PreExt;
2425       bool Signed = false;
2426       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
2427         // ZExt
2428         MinBits = N0->getOperand(0).getValueSizeInBits();
2429         PreExt = N0->getOperand(0);
2430       } else if (N0->getOpcode() == ISD::AND) {
2431         // DAGCombine turns costly ZExts into ANDs
2432         if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
2433           if ((C->getAPIntValue()+1).isPowerOf2()) {
2434             MinBits = C->getAPIntValue().countTrailingOnes();
2435             PreExt = N0->getOperand(0);
2436           }
2437       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
2438         // SExt
2439         MinBits = N0->getOperand(0).getValueSizeInBits();
2440         PreExt = N0->getOperand(0);
2441         Signed = true;
2442       } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
2443         // ZEXTLOAD / SEXTLOAD
2444         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
2445           MinBits = LN0->getMemoryVT().getSizeInBits();
2446           PreExt = N0;
2447         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
2448           Signed = true;
2449           MinBits = LN0->getMemoryVT().getSizeInBits();
2450           PreExt = N0;
2451         }
2452       }
2453 
2454       // Figure out how many bits we need to preserve this constant.
2455       unsigned ReqdBits = Signed ?
2456         C1.getBitWidth() - C1.getNumSignBits() + 1 :
2457         C1.getActiveBits();
2458 
2459       // Make sure we're not losing bits from the constant.
2460       if (MinBits > 0 &&
2461           MinBits < C1.getBitWidth() &&
2462           MinBits >= ReqdBits) {
2463         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
2464         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
2465           // Will get folded away.
2466           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
2467           if (MinBits == 1 && C1 == 1)
2468             // Invert the condition.
2469             return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
2470                                 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
2471           SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
2472           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
2473         }
2474 
2475         // If truncating the setcc operands is not desirable, we can still
2476         // simplify the expression in some cases:
2477         // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
2478         // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
2479         // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
2480         // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
2481         // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
2482         // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
2483         SDValue TopSetCC = N0->getOperand(0);
2484         unsigned N0Opc = N0->getOpcode();
2485         bool SExt = (N0Opc == ISD::SIGN_EXTEND);
2486         if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
2487             TopSetCC.getOpcode() == ISD::SETCC &&
2488             (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
2489             (isConstFalseVal(N1C) ||
2490              isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
2491 
2492           bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) ||
2493                          (!N1C->isNullValue() && Cond == ISD::SETNE);
2494 
2495           if (!Inverse)
2496             return TopSetCC;
2497 
2498           ISD::CondCode InvCond = ISD::getSetCCInverse(
2499               cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
2500               TopSetCC.getOperand(0).getValueType().isInteger());
2501           return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
2502                                       TopSetCC.getOperand(1),
2503                                       InvCond);
2504         }
2505       }
2506     }
2507 
2508     // If the LHS is '(and load, const)', the RHS is 0, the test is for
2509     // equality or unsigned, and all 1 bits of the const are in the same
2510     // partial word, see if we can shorten the load.
2511     if (DCI.isBeforeLegalize() &&
2512         !ISD::isSignedIntSetCC(Cond) &&
2513         N0.getOpcode() == ISD::AND && C1 == 0 &&
2514         N0.getNode()->hasOneUse() &&
2515         isa<LoadSDNode>(N0.getOperand(0)) &&
2516         N0.getOperand(0).getNode()->hasOneUse() &&
2517         isa<ConstantSDNode>(N0.getOperand(1))) {
2518       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
2519       APInt bestMask;
2520       unsigned bestWidth = 0, bestOffset = 0;
2521       if (!Lod->isVolatile() && Lod->isUnindexed()) {
2522         unsigned origWidth = N0.getValueSizeInBits();
2523         unsigned maskWidth = origWidth;
2524         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
2525         // 8 bits, but have to be careful...
2526         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
2527           origWidth = Lod->getMemoryVT().getSizeInBits();
2528         const APInt &Mask = N0.getConstantOperandAPInt(1);
2529         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
2530           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
2531           for (unsigned offset=0; offset<origWidth/width; offset++) {
2532             if (Mask.isSubsetOf(newMask)) {
2533               if (DAG.getDataLayout().isLittleEndian())
2534                 bestOffset = (uint64_t)offset * (width/8);
2535               else
2536                 bestOffset = (origWidth/width - offset - 1) * (width/8);
2537               bestMask = Mask.lshr(offset * (width/8) * 8);
2538               bestWidth = width;
2539               break;
2540             }
2541             newMask <<= width;
2542           }
2543         }
2544       }
2545       if (bestWidth) {
2546         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
2547         if (newVT.isRound() &&
2548             shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) {
2549           EVT PtrType = Lod->getOperand(1).getValueType();
2550           SDValue Ptr = Lod->getBasePtr();
2551           if (bestOffset != 0)
2552             Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
2553                               DAG.getConstant(bestOffset, dl, PtrType));
2554           unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
2555           SDValue NewLoad = DAG.getLoad(
2556               newVT, dl, Lod->getChain(), Ptr,
2557               Lod->getPointerInfo().getWithOffset(bestOffset), NewAlign);
2558           return DAG.getSetCC(dl, VT,
2559                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
2560                                       DAG.getConstant(bestMask.trunc(bestWidth),
2561                                                       dl, newVT)),
2562                               DAG.getConstant(0LL, dl, newVT), Cond);
2563         }
2564       }
2565     }
2566 
2567     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
2568     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
2569       unsigned InSize = N0.getOperand(0).getValueSizeInBits();
2570 
2571       // If the comparison constant has bits in the upper part, the
2572       // zero-extended value could never match.
2573       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
2574                                               C1.getBitWidth() - InSize))) {
2575         switch (Cond) {
2576         case ISD::SETUGT:
2577         case ISD::SETUGE:
2578         case ISD::SETEQ:
2579           return DAG.getConstant(0, dl, VT);
2580         case ISD::SETULT:
2581         case ISD::SETULE:
2582         case ISD::SETNE:
2583           return DAG.getConstant(1, dl, VT);
2584         case ISD::SETGT:
2585         case ISD::SETGE:
2586           // True if the sign bit of C1 is set.
2587           return DAG.getConstant(C1.isNegative(), dl, VT);
2588         case ISD::SETLT:
2589         case ISD::SETLE:
2590           // True if the sign bit of C1 isn't set.
2591           return DAG.getConstant(C1.isNonNegative(), dl, VT);
2592         default:
2593           break;
2594         }
2595       }
2596 
2597       // Otherwise, we can perform the comparison with the low bits.
2598       switch (Cond) {
2599       case ISD::SETEQ:
2600       case ISD::SETNE:
2601       case ISD::SETUGT:
2602       case ISD::SETUGE:
2603       case ISD::SETULT:
2604       case ISD::SETULE: {
2605         EVT newVT = N0.getOperand(0).getValueType();
2606         if (DCI.isBeforeLegalizeOps() ||
2607             (isOperationLegal(ISD::SETCC, newVT) &&
2608              isCondCodeLegal(Cond, newVT.getSimpleVT()))) {
2609           EVT NewSetCCVT =
2610               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT);
2611           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
2612 
2613           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
2614                                           NewConst, Cond);
2615           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
2616         }
2617         break;
2618       }
2619       default:
2620         break; // todo, be more careful with signed comparisons
2621       }
2622     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2623                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
2624       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
2625       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
2626       EVT ExtDstTy = N0.getValueType();
2627       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
2628 
2629       // If the constant doesn't fit into the number of bits for the source of
2630       // the sign extension, it is impossible for both sides to be equal.
2631       if (C1.getMinSignedBits() > ExtSrcTyBits)
2632         return DAG.getConstant(Cond == ISD::SETNE, dl, VT);
2633 
2634       SDValue ZextOp;
2635       EVT Op0Ty = N0.getOperand(0).getValueType();
2636       if (Op0Ty == ExtSrcTy) {
2637         ZextOp = N0.getOperand(0);
2638       } else {
2639         APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
2640         ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
2641                              DAG.getConstant(Imm, dl, Op0Ty));
2642       }
2643       if (!DCI.isCalledByLegalizer())
2644         DCI.AddToWorklist(ZextOp.getNode());
2645       // Otherwise, make this a use of a zext.
2646       return DAG.getSetCC(dl, VT, ZextOp,
2647                           DAG.getConstant(C1 & APInt::getLowBitsSet(
2648                                                               ExtDstTyBits,
2649                                                               ExtSrcTyBits),
2650                                           dl, ExtDstTy),
2651                           Cond);
2652     } else if ((N1C->isNullValue() || N1C->isOne()) &&
2653                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
2654       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
2655       if (N0.getOpcode() == ISD::SETCC &&
2656           isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
2657         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
2658         if (TrueWhenTrue)
2659           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
2660         // Invert the condition.
2661         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
2662         CC = ISD::getSetCCInverse(CC,
2663                                   N0.getOperand(0).getValueType().isInteger());
2664         if (DCI.isBeforeLegalizeOps() ||
2665             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
2666           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
2667       }
2668 
2669       if ((N0.getOpcode() == ISD::XOR ||
2670            (N0.getOpcode() == ISD::AND &&
2671             N0.getOperand(0).getOpcode() == ISD::XOR &&
2672             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
2673           isa<ConstantSDNode>(N0.getOperand(1)) &&
2674           cast<ConstantSDNode>(N0.getOperand(1))->isOne()) {
2675         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
2676         // can only do this if the top bits are known zero.
2677         unsigned BitWidth = N0.getValueSizeInBits();
2678         if (DAG.MaskedValueIsZero(N0,
2679                                   APInt::getHighBitsSet(BitWidth,
2680                                                         BitWidth-1))) {
2681           // Okay, get the un-inverted input value.
2682           SDValue Val;
2683           if (N0.getOpcode() == ISD::XOR) {
2684             Val = N0.getOperand(0);
2685           } else {
2686             assert(N0.getOpcode() == ISD::AND &&
2687                     N0.getOperand(0).getOpcode() == ISD::XOR);
2688             // ((X^1)&1)^1 -> X & 1
2689             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
2690                               N0.getOperand(0).getOperand(0),
2691                               N0.getOperand(1));
2692           }
2693 
2694           return DAG.getSetCC(dl, VT, Val, N1,
2695                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
2696         }
2697       } else if (N1C->isOne() &&
2698                  (VT == MVT::i1 ||
2699                   getBooleanContents(N0->getValueType(0)) ==
2700                       ZeroOrOneBooleanContent)) {
2701         SDValue Op0 = N0;
2702         if (Op0.getOpcode() == ISD::TRUNCATE)
2703           Op0 = Op0.getOperand(0);
2704 
2705         if ((Op0.getOpcode() == ISD::XOR) &&
2706             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
2707             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
2708           // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
2709           Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
2710           return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
2711                               Cond);
2712         }
2713         if (Op0.getOpcode() == ISD::AND &&
2714             isa<ConstantSDNode>(Op0.getOperand(1)) &&
2715             cast<ConstantSDNode>(Op0.getOperand(1))->isOne()) {
2716           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
2717           if (Op0.getValueType().bitsGT(VT))
2718             Op0 = DAG.getNode(ISD::AND, dl, VT,
2719                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
2720                           DAG.getConstant(1, dl, VT));
2721           else if (Op0.getValueType().bitsLT(VT))
2722             Op0 = DAG.getNode(ISD::AND, dl, VT,
2723                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
2724                         DAG.getConstant(1, dl, VT));
2725 
2726           return DAG.getSetCC(dl, VT, Op0,
2727                               DAG.getConstant(0, dl, Op0.getValueType()),
2728                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
2729         }
2730         if (Op0.getOpcode() == ISD::AssertZext &&
2731             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
2732           return DAG.getSetCC(dl, VT, Op0,
2733                               DAG.getConstant(0, dl, Op0.getValueType()),
2734                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
2735       }
2736     }
2737 
2738     if (SDValue V =
2739             optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
2740       return V;
2741   }
2742 
2743   // These simplifications apply to splat vectors as well.
2744   // TODO: Handle more splat vector cases.
2745   if (auto *N1C = isConstOrConstSplat(N1)) {
2746     const APInt &C1 = N1C->getAPIntValue();
2747 
2748     APInt MinVal, MaxVal;
2749     unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
2750     if (ISD::isSignedIntSetCC(Cond)) {
2751       MinVal = APInt::getSignedMinValue(OperandBitSize);
2752       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
2753     } else {
2754       MinVal = APInt::getMinValue(OperandBitSize);
2755       MaxVal = APInt::getMaxValue(OperandBitSize);
2756     }
2757 
2758     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
2759     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
2760       // X >= MIN --> true
2761       if (C1 == MinVal)
2762         return DAG.getBoolConstant(true, dl, VT, OpVT);
2763 
2764       if (!VT.isVector()) { // TODO: Support this for vectors.
2765         // X >= C0 --> X > (C0 - 1)
2766         APInt C = C1 - 1;
2767         ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
2768         if ((DCI.isBeforeLegalizeOps() ||
2769              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
2770             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
2771                                   isLegalICmpImmediate(C.getSExtValue())))) {
2772           return DAG.getSetCC(dl, VT, N0,
2773                               DAG.getConstant(C, dl, N1.getValueType()),
2774                               NewCC);
2775         }
2776       }
2777     }
2778 
2779     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
2780       // X <= MAX --> true
2781       if (C1 == MaxVal)
2782         return DAG.getBoolConstant(true, dl, VT, OpVT);
2783 
2784       // X <= C0 --> X < (C0 + 1)
2785       if (!VT.isVector()) { // TODO: Support this for vectors.
2786         APInt C = C1 + 1;
2787         ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
2788         if ((DCI.isBeforeLegalizeOps() ||
2789              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
2790             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
2791                                   isLegalICmpImmediate(C.getSExtValue())))) {
2792           return DAG.getSetCC(dl, VT, N0,
2793                               DAG.getConstant(C, dl, N1.getValueType()),
2794                               NewCC);
2795         }
2796       }
2797     }
2798 
2799     if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
2800       if (C1 == MinVal)
2801         return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
2802 
2803       // TODO: Support this for vectors after legalize ops.
2804       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
2805         // Canonicalize setlt X, Max --> setne X, Max
2806         if (C1 == MaxVal)
2807           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
2808 
2809         // If we have setult X, 1, turn it into seteq X, 0
2810         if (C1 == MinVal+1)
2811           return DAG.getSetCC(dl, VT, N0,
2812                               DAG.getConstant(MinVal, dl, N0.getValueType()),
2813                               ISD::SETEQ);
2814       }
2815     }
2816 
2817     if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
2818       if (C1 == MaxVal)
2819         return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
2820 
2821       // TODO: Support this for vectors after legalize ops.
2822       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
2823         // Canonicalize setgt X, Min --> setne X, Min
2824         if (C1 == MinVal)
2825           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
2826 
2827         // If we have setugt X, Max-1, turn it into seteq X, Max
2828         if (C1 == MaxVal-1)
2829           return DAG.getSetCC(dl, VT, N0,
2830                               DAG.getConstant(MaxVal, dl, N0.getValueType()),
2831                               ISD::SETEQ);
2832       }
2833     }
2834 
2835     // If we have "setcc X, C0", check to see if we can shrink the immediate
2836     // by changing cc.
2837     // TODO: Support this for vectors after legalize ops.
2838     if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
2839       // SETUGT X, SINTMAX  -> SETLT X, 0
2840       if (Cond == ISD::SETUGT &&
2841           C1 == APInt::getSignedMaxValue(OperandBitSize))
2842         return DAG.getSetCC(dl, VT, N0,
2843                             DAG.getConstant(0, dl, N1.getValueType()),
2844                             ISD::SETLT);
2845 
2846       // SETULT X, SINTMIN  -> SETGT X, -1
2847       if (Cond == ISD::SETULT &&
2848           C1 == APInt::getSignedMinValue(OperandBitSize)) {
2849         SDValue ConstMinusOne =
2850             DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl,
2851                             N1.getValueType());
2852         return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
2853       }
2854     }
2855   }
2856 
2857   // Back to non-vector simplifications.
2858   // TODO: Can we do these for vector splats?
2859   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
2860     const APInt &C1 = N1C->getAPIntValue();
2861 
2862     // Fold bit comparisons when we can.
2863     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2864         (VT == N0.getValueType() ||
2865          (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
2866         N0.getOpcode() == ISD::AND) {
2867       auto &DL = DAG.getDataLayout();
2868       if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2869         EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL,
2870                                        !DCI.isBeforeLegalize());
2871         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
2872           // Perform the xform if the AND RHS is a single bit.
2873           if (AndRHS->getAPIntValue().isPowerOf2()) {
2874             return DAG.getNode(ISD::TRUNCATE, dl, VT,
2875                               DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
2876                    DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl,
2877                                    ShiftTy)));
2878           }
2879         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
2880           // (X & 8) == 8  -->  (X & 8) >> 3
2881           // Perform the xform if C1 is a single bit.
2882           if (C1.isPowerOf2()) {
2883             return DAG.getNode(ISD::TRUNCATE, dl, VT,
2884                                DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
2885                                       DAG.getConstant(C1.logBase2(), dl,
2886                                                       ShiftTy)));
2887           }
2888         }
2889       }
2890     }
2891 
2892     if (C1.getMinSignedBits() <= 64 &&
2893         !isLegalICmpImmediate(C1.getSExtValue())) {
2894       // (X & -256) == 256 -> (X >> 8) == 1
2895       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2896           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
2897         if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2898           const APInt &AndRHSC = AndRHS->getAPIntValue();
2899           if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
2900             unsigned ShiftBits = AndRHSC.countTrailingZeros();
2901             auto &DL = DAG.getDataLayout();
2902             EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL,
2903                                            !DCI.isBeforeLegalize());
2904             EVT CmpTy = N0.getValueType();
2905             SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
2906                                         DAG.getConstant(ShiftBits, dl,
2907                                                         ShiftTy));
2908             SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy);
2909             return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
2910           }
2911         }
2912       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
2913                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
2914         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
2915         // X <  0x100000000 -> (X >> 32) <  1
2916         // X >= 0x100000000 -> (X >> 32) >= 1
2917         // X <= 0x0ffffffff -> (X >> 32) <  1
2918         // X >  0x0ffffffff -> (X >> 32) >= 1
2919         unsigned ShiftBits;
2920         APInt NewC = C1;
2921         ISD::CondCode NewCond = Cond;
2922         if (AdjOne) {
2923           ShiftBits = C1.countTrailingOnes();
2924           NewC = NewC + 1;
2925           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2926         } else {
2927           ShiftBits = C1.countTrailingZeros();
2928         }
2929         NewC.lshrInPlace(ShiftBits);
2930         if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
2931           isLegalICmpImmediate(NewC.getSExtValue())) {
2932           auto &DL = DAG.getDataLayout();
2933           EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL,
2934                                          !DCI.isBeforeLegalize());
2935           EVT CmpTy = N0.getValueType();
2936           SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
2937                                       DAG.getConstant(ShiftBits, dl, ShiftTy));
2938           SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy);
2939           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
2940         }
2941       }
2942     }
2943   }
2944 
2945   if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) {
2946     auto *CFP = cast<ConstantFPSDNode>(N1);
2947 
2948     // If the RHS of an FP comparison is a constant, simplify it away in
2949     // some cases.
2950     if (CFP->getValueAPF().isNaN()) {
2951       // If an operand is known to be a nan, we can fold it.
2952       switch (ISD::getUnorderedFlavor(Cond)) {
2953       default: llvm_unreachable("Unknown flavor!");
2954       case 0:  // Known false.
2955         return DAG.getBoolConstant(false, dl, VT, OpVT);
2956       case 1:  // Known true.
2957         return DAG.getBoolConstant(true, dl, VT, OpVT);
2958       case 2:  // Undefined.
2959         return DAG.getUNDEF(VT);
2960       }
2961     }
2962 
2963     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
2964     // constant if knowing that the operand is non-nan is enough.  We prefer to
2965     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
2966     // materialize 0.0.
2967     if (Cond == ISD::SETO || Cond == ISD::SETUO)
2968       return DAG.getSetCC(dl, VT, N0, N0, Cond);
2969 
2970     // setcc (fneg x), C -> setcc swap(pred) x, -C
2971     if (N0.getOpcode() == ISD::FNEG) {
2972       ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond);
2973       if (DCI.isBeforeLegalizeOps() ||
2974           isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
2975         SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
2976         return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
2977       }
2978     }
2979 
2980     // If the condition is not legal, see if we can find an equivalent one
2981     // which is legal.
2982     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
2983       // If the comparison was an awkward floating-point == or != and one of
2984       // the comparison operands is infinity or negative infinity, convert the
2985       // condition to a less-awkward <= or >=.
2986       if (CFP->getValueAPF().isInfinity()) {
2987         if (CFP->getValueAPF().isNegative()) {
2988           if (Cond == ISD::SETOEQ &&
2989               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
2990             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
2991           if (Cond == ISD::SETUEQ &&
2992               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
2993             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
2994           if (Cond == ISD::SETUNE &&
2995               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
2996             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
2997           if (Cond == ISD::SETONE &&
2998               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
2999             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
3000         } else {
3001           if (Cond == ISD::SETOEQ &&
3002               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
3003             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
3004           if (Cond == ISD::SETUEQ &&
3005               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
3006             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
3007           if (Cond == ISD::SETUNE &&
3008               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
3009             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
3010           if (Cond == ISD::SETONE &&
3011               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
3012             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
3013         }
3014       }
3015     }
3016   }
3017 
3018   if (N0 == N1) {
3019     // The sext(setcc()) => setcc() optimization relies on the appropriate
3020     // constant being emitted.
3021 
3022     bool EqTrue = ISD::isTrueWhenEqual(Cond);
3023 
3024     // We can always fold X == X for integer setcc's.
3025     if (N0.getValueType().isInteger())
3026       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
3027 
3028     unsigned UOF = ISD::getUnorderedFlavor(Cond);
3029     if (UOF == 2) // FP operators that are undefined on NaNs.
3030       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
3031     if (UOF == unsigned(EqTrue))
3032       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
3033     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
3034     // if it is not already.
3035     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
3036     if (NewCond != Cond &&
3037         (DCI.isBeforeLegalizeOps() ||
3038                             isCondCodeLegal(NewCond, N0.getSimpleValueType())))
3039       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
3040   }
3041 
3042   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3043       N0.getValueType().isInteger()) {
3044     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
3045         N0.getOpcode() == ISD::XOR) {
3046       // Simplify (X+Y) == (X+Z) -->  Y == Z
3047       if (N0.getOpcode() == N1.getOpcode()) {
3048         if (N0.getOperand(0) == N1.getOperand(0))
3049           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
3050         if (N0.getOperand(1) == N1.getOperand(1))
3051           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
3052         if (isCommutativeBinOp(N0.getOpcode())) {
3053           // If X op Y == Y op X, try other combinations.
3054           if (N0.getOperand(0) == N1.getOperand(1))
3055             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
3056                                 Cond);
3057           if (N0.getOperand(1) == N1.getOperand(0))
3058             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
3059                                 Cond);
3060         }
3061       }
3062 
3063       // If RHS is a legal immediate value for a compare instruction, we need
3064       // to be careful about increasing register pressure needlessly.
3065       bool LegalRHSImm = false;
3066 
3067       if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
3068         if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3069           // Turn (X+C1) == C2 --> X == C2-C1
3070           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
3071             return DAG.getSetCC(dl, VT, N0.getOperand(0),
3072                                 DAG.getConstant(RHSC->getAPIntValue()-
3073                                                 LHSR->getAPIntValue(),
3074                                 dl, N0.getValueType()), Cond);
3075           }
3076 
3077           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
3078           if (N0.getOpcode() == ISD::XOR)
3079             // If we know that all of the inverted bits are zero, don't bother
3080             // performing the inversion.
3081             if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
3082               return
3083                 DAG.getSetCC(dl, VT, N0.getOperand(0),
3084                              DAG.getConstant(LHSR->getAPIntValue() ^
3085                                                RHSC->getAPIntValue(),
3086                                              dl, N0.getValueType()),
3087                              Cond);
3088         }
3089 
3090         // Turn (C1-X) == C2 --> X == C1-C2
3091         if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
3092           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
3093             return
3094               DAG.getSetCC(dl, VT, N0.getOperand(1),
3095                            DAG.getConstant(SUBC->getAPIntValue() -
3096                                              RHSC->getAPIntValue(),
3097                                            dl, N0.getValueType()),
3098                            Cond);
3099           }
3100         }
3101 
3102         // Could RHSC fold directly into a compare?
3103         if (RHSC->getValueType(0).getSizeInBits() <= 64)
3104           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
3105       }
3106 
3107       // (X+Y) == X --> Y == 0 and similar folds.
3108       // Don't do this if X is an immediate that can fold into a cmp
3109       // instruction and X+Y has other uses. It could be an induction variable
3110       // chain, and the transform would increase register pressure.
3111       if (!LegalRHSImm || N0.hasOneUse())
3112         if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
3113           return V;
3114     }
3115 
3116     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
3117         N1.getOpcode() == ISD::XOR)
3118       if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
3119         return V;
3120 
3121     if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
3122       return V;
3123   }
3124 
3125   // Fold away ALL boolean setcc's.
3126   SDValue Temp;
3127   if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
3128     EVT OpVT = N0.getValueType();
3129     switch (Cond) {
3130     default: llvm_unreachable("Unknown integer setcc!");
3131     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
3132       Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
3133       N0 = DAG.getNOT(dl, Temp, OpVT);
3134       if (!DCI.isCalledByLegalizer())
3135         DCI.AddToWorklist(Temp.getNode());
3136       break;
3137     case ISD::SETNE:  // X != Y   -->  (X^Y)
3138       N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
3139       break;
3140     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
3141     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
3142       Temp = DAG.getNOT(dl, N0, OpVT);
3143       N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
3144       if (!DCI.isCalledByLegalizer())
3145         DCI.AddToWorklist(Temp.getNode());
3146       break;
3147     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
3148     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
3149       Temp = DAG.getNOT(dl, N1, OpVT);
3150       N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
3151       if (!DCI.isCalledByLegalizer())
3152         DCI.AddToWorklist(Temp.getNode());
3153       break;
3154     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
3155     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
3156       Temp = DAG.getNOT(dl, N0, OpVT);
3157       N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
3158       if (!DCI.isCalledByLegalizer())
3159         DCI.AddToWorklist(Temp.getNode());
3160       break;
3161     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
3162     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
3163       Temp = DAG.getNOT(dl, N1, OpVT);
3164       N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
3165       break;
3166     }
3167     if (VT.getScalarType() != MVT::i1) {
3168       if (!DCI.isCalledByLegalizer())
3169         DCI.AddToWorklist(N0.getNode());
3170       // FIXME: If running after legalize, we probably can't do this.
3171       ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT));
3172       N0 = DAG.getNode(ExtendCode, dl, VT, N0);
3173     }
3174     return N0;
3175   }
3176 
3177   // Could not fold it.
3178   return SDValue();
3179 }
3180 
3181 /// Returns true (and the GlobalValue and the offset) if the node is a
3182 /// GlobalAddress + offset.
3183 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA,
3184                                     int64_t &Offset) const {
3185 
3186   SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
3187 
3188   if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
3189     GA = GASD->getGlobal();
3190     Offset += GASD->getOffset();
3191     return true;
3192   }
3193 
3194   if (N->getOpcode() == ISD::ADD) {
3195     SDValue N1 = N->getOperand(0);
3196     SDValue N2 = N->getOperand(1);
3197     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
3198       if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
3199         Offset += V->getSExtValue();
3200         return true;
3201       }
3202     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
3203       if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
3204         Offset += V->getSExtValue();
3205         return true;
3206       }
3207     }
3208   }
3209 
3210   return false;
3211 }
3212 
3213 SDValue TargetLowering::PerformDAGCombine(SDNode *N,
3214                                           DAGCombinerInfo &DCI) const {
3215   // Default implementation: no optimization.
3216   return SDValue();
3217 }
3218 
3219 //===----------------------------------------------------------------------===//
3220 //  Inline Assembler Implementation Methods
3221 //===----------------------------------------------------------------------===//
3222 
3223 TargetLowering::ConstraintType
3224 TargetLowering::getConstraintType(StringRef Constraint) const {
3225   unsigned S = Constraint.size();
3226 
3227   if (S == 1) {
3228     switch (Constraint[0]) {
3229     default: break;
3230     case 'r': return C_RegisterClass;
3231     case 'm': // memory
3232     case 'o': // offsetable
3233     case 'V': // not offsetable
3234       return C_Memory;
3235     case 'i': // Simple Integer or Relocatable Constant
3236     case 'n': // Simple Integer
3237     case 'E': // Floating Point Constant
3238     case 'F': // Floating Point Constant
3239     case 's': // Relocatable Constant
3240     case 'p': // Address.
3241     case 'X': // Allow ANY value.
3242     case 'I': // Target registers.
3243     case 'J':
3244     case 'K':
3245     case 'L':
3246     case 'M':
3247     case 'N':
3248     case 'O':
3249     case 'P':
3250     case '<':
3251     case '>':
3252       return C_Other;
3253     }
3254   }
3255 
3256   if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
3257     if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
3258       return C_Memory;
3259     return C_Register;
3260   }
3261   return C_Unknown;
3262 }
3263 
3264 /// Try to replace an X constraint, which matches anything, with another that
3265 /// has more specific requirements based on the type of the corresponding
3266 /// operand.
3267 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
3268   if (ConstraintVT.isInteger())
3269     return "r";
3270   if (ConstraintVT.isFloatingPoint())
3271     return "f"; // works for many targets
3272   return nullptr;
3273 }
3274 
3275 SDValue TargetLowering::LowerAsmOutputForConstraint(
3276     SDValue &Chain, SDValue &Flag, SDLoc DL, const AsmOperandInfo &OpInfo,
3277     SelectionDAG &DAG) const {
3278   return SDValue();
3279 }
3280 
3281 /// Lower the specified operand into the Ops vector.
3282 /// If it is invalid, don't add anything to Ops.
3283 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3284                                                   std::string &Constraint,
3285                                                   std::vector<SDValue> &Ops,
3286                                                   SelectionDAG &DAG) const {
3287 
3288   if (Constraint.length() > 1) return;
3289 
3290   char ConstraintLetter = Constraint[0];
3291   switch (ConstraintLetter) {
3292   default: break;
3293   case 'X':     // Allows any operand; labels (basic block) use this.
3294     if (Op.getOpcode() == ISD::BasicBlock ||
3295         Op.getOpcode() == ISD::TargetBlockAddress) {
3296       Ops.push_back(Op);
3297       return;
3298     }
3299     LLVM_FALLTHROUGH;
3300   case 'i':    // Simple Integer or Relocatable Constant
3301   case 'n':    // Simple Integer
3302   case 's': {  // Relocatable Constant
3303     // These operands are interested in values of the form (GV+C), where C may
3304     // be folded in as an offset of GV, or it may be explicitly added.  Also, it
3305     // is possible and fine if either GV or C are missing.
3306     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3307     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
3308 
3309     // If we have "(add GV, C)", pull out GV/C
3310     if (Op.getOpcode() == ISD::ADD) {
3311       C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
3312       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
3313       if (!C || !GA) {
3314         C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
3315         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
3316       }
3317       if (!C || !GA) {
3318         C = nullptr;
3319         GA = nullptr;
3320       }
3321     }
3322 
3323     // If we find a valid operand, map to the TargetXXX version so that the
3324     // value itself doesn't get selected.
3325     if (GA) {   // Either &GV   or   &GV+C
3326       if (ConstraintLetter != 'n') {
3327         int64_t Offs = GA->getOffset();
3328         if (C) Offs += C->getZExtValue();
3329         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
3330                                                  C ? SDLoc(C) : SDLoc(),
3331                                                  Op.getValueType(), Offs));
3332       }
3333       return;
3334     }
3335     if (C) {   // just C, no GV.
3336       // Simple constants are not allowed for 's'.
3337       if (ConstraintLetter != 's') {
3338         // gcc prints these as sign extended.  Sign extend value to 64 bits
3339         // now; without this it would get ZExt'd later in
3340         // ScheduleDAGSDNodes::EmitNode, which is very generic.
3341         Ops.push_back(DAG.getTargetConstant(C->getSExtValue(),
3342                                             SDLoc(C), MVT::i64));
3343       }
3344       return;
3345     }
3346     break;
3347   }
3348   }
3349 }
3350 
3351 std::pair<unsigned, const TargetRegisterClass *>
3352 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
3353                                              StringRef Constraint,
3354                                              MVT VT) const {
3355   if (Constraint.empty() || Constraint[0] != '{')
3356     return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
3357   assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
3358 
3359   // Remove the braces from around the name.
3360   StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
3361 
3362   std::pair<unsigned, const TargetRegisterClass *> R =
3363       std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
3364 
3365   // Figure out which register class contains this reg.
3366   for (const TargetRegisterClass *RC : RI->regclasses()) {
3367     // If none of the value types for this register class are valid, we
3368     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
3369     if (!isLegalRC(*RI, *RC))
3370       continue;
3371 
3372     for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
3373          I != E; ++I) {
3374       if (RegName.equals_lower(RI->getRegAsmName(*I))) {
3375         std::pair<unsigned, const TargetRegisterClass *> S =
3376             std::make_pair(*I, RC);
3377 
3378         // If this register class has the requested value type, return it,
3379         // otherwise keep searching and return the first class found
3380         // if no other is found which explicitly has the requested type.
3381         if (RI->isTypeLegalForClass(*RC, VT))
3382           return S;
3383         if (!R.second)
3384           R = S;
3385       }
3386     }
3387   }
3388 
3389   return R;
3390 }
3391 
3392 //===----------------------------------------------------------------------===//
3393 // Constraint Selection.
3394 
3395 /// Return true of this is an input operand that is a matching constraint like
3396 /// "4".
3397 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
3398   assert(!ConstraintCode.empty() && "No known constraint!");
3399   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
3400 }
3401 
3402 /// If this is an input matching constraint, this method returns the output
3403 /// operand it matches.
3404 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
3405   assert(!ConstraintCode.empty() && "No known constraint!");
3406   return atoi(ConstraintCode.c_str());
3407 }
3408 
3409 /// Split up the constraint string from the inline assembly value into the
3410 /// specific constraints and their prefixes, and also tie in the associated
3411 /// operand values.
3412 /// If this returns an empty vector, and if the constraint string itself
3413 /// isn't empty, there was an error parsing.
3414 TargetLowering::AsmOperandInfoVector
3415 TargetLowering::ParseConstraints(const DataLayout &DL,
3416                                  const TargetRegisterInfo *TRI,
3417                                  ImmutableCallSite CS) const {
3418   /// Information about all of the constraints.
3419   AsmOperandInfoVector ConstraintOperands;
3420   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
3421   unsigned maCount = 0; // Largest number of multiple alternative constraints.
3422 
3423   // Do a prepass over the constraints, canonicalizing them, and building up the
3424   // ConstraintOperands list.
3425   unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
3426   unsigned ResNo = 0; // ResNo - The result number of the next output.
3427 
3428   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
3429     ConstraintOperands.emplace_back(std::move(CI));
3430     AsmOperandInfo &OpInfo = ConstraintOperands.back();
3431 
3432     // Update multiple alternative constraint count.
3433     if (OpInfo.multipleAlternatives.size() > maCount)
3434       maCount = OpInfo.multipleAlternatives.size();
3435 
3436     OpInfo.ConstraintVT = MVT::Other;
3437 
3438     // Compute the value type for each operand.
3439     switch (OpInfo.Type) {
3440     case InlineAsm::isOutput:
3441       // Indirect outputs just consume an argument.
3442       if (OpInfo.isIndirect) {
3443         OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
3444         break;
3445       }
3446 
3447       // The return value of the call is this value.  As such, there is no
3448       // corresponding argument.
3449       assert(!CS.getType()->isVoidTy() &&
3450              "Bad inline asm!");
3451       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
3452         OpInfo.ConstraintVT =
3453             getSimpleValueType(DL, STy->getElementType(ResNo));
3454       } else {
3455         assert(ResNo == 0 && "Asm only has one result!");
3456         OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType());
3457       }
3458       ++ResNo;
3459       break;
3460     case InlineAsm::isInput:
3461       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
3462       break;
3463     case InlineAsm::isClobber:
3464       // Nothing to do.
3465       break;
3466     }
3467 
3468     if (OpInfo.CallOperandVal) {
3469       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
3470       if (OpInfo.isIndirect) {
3471         llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
3472         if (!PtrTy)
3473           report_fatal_error("Indirect operand for inline asm not a pointer!");
3474         OpTy = PtrTy->getElementType();
3475       }
3476 
3477       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
3478       if (StructType *STy = dyn_cast<StructType>(OpTy))
3479         if (STy->getNumElements() == 1)
3480           OpTy = STy->getElementType(0);
3481 
3482       // If OpTy is not a single value, it may be a struct/union that we
3483       // can tile with integers.
3484       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
3485         unsigned BitSize = DL.getTypeSizeInBits(OpTy);
3486         switch (BitSize) {
3487         default: break;
3488         case 1:
3489         case 8:
3490         case 16:
3491         case 32:
3492         case 64:
3493         case 128:
3494           OpInfo.ConstraintVT =
3495               MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
3496           break;
3497         }
3498       } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
3499         unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
3500         OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
3501       } else {
3502         OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
3503       }
3504     }
3505   }
3506 
3507   // If we have multiple alternative constraints, select the best alternative.
3508   if (!ConstraintOperands.empty()) {
3509     if (maCount) {
3510       unsigned bestMAIndex = 0;
3511       int bestWeight = -1;
3512       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
3513       int weight = -1;
3514       unsigned maIndex;
3515       // Compute the sums of the weights for each alternative, keeping track
3516       // of the best (highest weight) one so far.
3517       for (maIndex = 0; maIndex < maCount; ++maIndex) {
3518         int weightSum = 0;
3519         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
3520              cIndex != eIndex; ++cIndex) {
3521           AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
3522           if (OpInfo.Type == InlineAsm::isClobber)
3523             continue;
3524 
3525           // If this is an output operand with a matching input operand,
3526           // look up the matching input. If their types mismatch, e.g. one
3527           // is an integer, the other is floating point, or their sizes are
3528           // different, flag it as an maCantMatch.
3529           if (OpInfo.hasMatchingInput()) {
3530             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
3531             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
3532               if ((OpInfo.ConstraintVT.isInteger() !=
3533                    Input.ConstraintVT.isInteger()) ||
3534                   (OpInfo.ConstraintVT.getSizeInBits() !=
3535                    Input.ConstraintVT.getSizeInBits())) {
3536                 weightSum = -1; // Can't match.
3537                 break;
3538               }
3539             }
3540           }
3541           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
3542           if (weight == -1) {
3543             weightSum = -1;
3544             break;
3545           }
3546           weightSum += weight;
3547         }
3548         // Update best.
3549         if (weightSum > bestWeight) {
3550           bestWeight = weightSum;
3551           bestMAIndex = maIndex;
3552         }
3553       }
3554 
3555       // Now select chosen alternative in each constraint.
3556       for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
3557            cIndex != eIndex; ++cIndex) {
3558         AsmOperandInfo &cInfo = ConstraintOperands[cIndex];
3559         if (cInfo.Type == InlineAsm::isClobber)
3560           continue;
3561         cInfo.selectAlternative(bestMAIndex);
3562       }
3563     }
3564   }
3565 
3566   // Check and hook up tied operands, choose constraint code to use.
3567   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
3568        cIndex != eIndex; ++cIndex) {
3569     AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
3570 
3571     // If this is an output operand with a matching input operand, look up the
3572     // matching input. If their types mismatch, e.g. one is an integer, the
3573     // other is floating point, or their sizes are different, flag it as an
3574     // error.
3575     if (OpInfo.hasMatchingInput()) {
3576       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
3577 
3578       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
3579         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
3580             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
3581                                          OpInfo.ConstraintVT);
3582         std::pair<unsigned, const TargetRegisterClass *> InputRC =
3583             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
3584                                          Input.ConstraintVT);
3585         if ((OpInfo.ConstraintVT.isInteger() !=
3586              Input.ConstraintVT.isInteger()) ||
3587             (MatchRC.second != InputRC.second)) {
3588           report_fatal_error("Unsupported asm: input constraint"
3589                              " with a matching output constraint of"
3590                              " incompatible type!");
3591         }
3592       }
3593     }
3594   }
3595 
3596   return ConstraintOperands;
3597 }
3598 
3599 /// Return an integer indicating how general CT is.
3600 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3601   switch (CT) {
3602   case TargetLowering::C_Other:
3603   case TargetLowering::C_Unknown:
3604     return 0;
3605   case TargetLowering::C_Register:
3606     return 1;
3607   case TargetLowering::C_RegisterClass:
3608     return 2;
3609   case TargetLowering::C_Memory:
3610     return 3;
3611   }
3612   llvm_unreachable("Invalid constraint type");
3613 }
3614 
3615 /// Examine constraint type and operand type and determine a weight value.
3616 /// This object must already have been set up with the operand type
3617 /// and the current alternative constraint selected.
3618 TargetLowering::ConstraintWeight
3619   TargetLowering::getMultipleConstraintMatchWeight(
3620     AsmOperandInfo &info, int maIndex) const {
3621   InlineAsm::ConstraintCodeVector *rCodes;
3622   if (maIndex >= (int)info.multipleAlternatives.size())
3623     rCodes = &info.Codes;
3624   else
3625     rCodes = &info.multipleAlternatives[maIndex].Codes;
3626   ConstraintWeight BestWeight = CW_Invalid;
3627 
3628   // Loop over the options, keeping track of the most general one.
3629   for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
3630     ConstraintWeight weight =
3631       getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
3632     if (weight > BestWeight)
3633       BestWeight = weight;
3634   }
3635 
3636   return BestWeight;
3637 }
3638 
3639 /// Examine constraint type and operand type and determine a weight value.
3640 /// This object must already have been set up with the operand type
3641 /// and the current alternative constraint selected.
3642 TargetLowering::ConstraintWeight
3643   TargetLowering::getSingleConstraintMatchWeight(
3644     AsmOperandInfo &info, const char *constraint) const {
3645   ConstraintWeight weight = CW_Invalid;
3646   Value *CallOperandVal = info.CallOperandVal;
3647     // If we don't have a value, we can't do a match,
3648     // but allow it at the lowest weight.
3649   if (!CallOperandVal)
3650     return CW_Default;
3651   // Look at the constraint type.
3652   switch (*constraint) {
3653     case 'i': // immediate integer.
3654     case 'n': // immediate integer with a known value.
3655       if (isa<ConstantInt>(CallOperandVal))
3656         weight = CW_Constant;
3657       break;
3658     case 's': // non-explicit intregal immediate.
3659       if (isa<GlobalValue>(CallOperandVal))
3660         weight = CW_Constant;
3661       break;
3662     case 'E': // immediate float if host format.
3663     case 'F': // immediate float.
3664       if (isa<ConstantFP>(CallOperandVal))
3665         weight = CW_Constant;
3666       break;
3667     case '<': // memory operand with autodecrement.
3668     case '>': // memory operand with autoincrement.
3669     case 'm': // memory operand.
3670     case 'o': // offsettable memory operand
3671     case 'V': // non-offsettable memory operand
3672       weight = CW_Memory;
3673       break;
3674     case 'r': // general register.
3675     case 'g': // general register, memory operand or immediate integer.
3676               // note: Clang converts "g" to "imr".
3677       if (CallOperandVal->getType()->isIntegerTy())
3678         weight = CW_Register;
3679       break;
3680     case 'X': // any operand.
3681   default:
3682     weight = CW_Default;
3683     break;
3684   }
3685   return weight;
3686 }
3687 
3688 /// If there are multiple different constraints that we could pick for this
3689 /// operand (e.g. "imr") try to pick the 'best' one.
3690 /// This is somewhat tricky: constraints fall into four classes:
3691 ///    Other         -> immediates and magic values
3692 ///    Register      -> one specific register
3693 ///    RegisterClass -> a group of regs
3694 ///    Memory        -> memory
3695 /// Ideally, we would pick the most specific constraint possible: if we have
3696 /// something that fits into a register, we would pick it.  The problem here
3697 /// is that if we have something that could either be in a register or in
3698 /// memory that use of the register could cause selection of *other*
3699 /// operands to fail: they might only succeed if we pick memory.  Because of
3700 /// this the heuristic we use is:
3701 ///
3702 ///  1) If there is an 'other' constraint, and if the operand is valid for
3703 ///     that constraint, use it.  This makes us take advantage of 'i'
3704 ///     constraints when available.
3705 ///  2) Otherwise, pick the most general constraint present.  This prefers
3706 ///     'm' over 'r', for example.
3707 ///
3708 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
3709                              const TargetLowering &TLI,
3710                              SDValue Op, SelectionDAG *DAG) {
3711   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
3712   unsigned BestIdx = 0;
3713   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
3714   int BestGenerality = -1;
3715 
3716   // Loop over the options, keeping track of the most general one.
3717   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
3718     TargetLowering::ConstraintType CType =
3719       TLI.getConstraintType(OpInfo.Codes[i]);
3720 
3721     // If this is an 'other' constraint, see if the operand is valid for it.
3722     // For example, on X86 we might have an 'rI' constraint.  If the operand
3723     // is an integer in the range [0..31] we want to use I (saving a load
3724     // of a register), otherwise we must use 'r'.
3725     if (CType == TargetLowering::C_Other && Op.getNode()) {
3726       assert(OpInfo.Codes[i].size() == 1 &&
3727              "Unhandled multi-letter 'other' constraint");
3728       std::vector<SDValue> ResultOps;
3729       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
3730                                        ResultOps, *DAG);
3731       if (!ResultOps.empty()) {
3732         BestType = CType;
3733         BestIdx = i;
3734         break;
3735       }
3736     }
3737 
3738     // Things with matching constraints can only be registers, per gcc
3739     // documentation.  This mainly affects "g" constraints.
3740     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
3741       continue;
3742 
3743     // This constraint letter is more general than the previous one, use it.
3744     int Generality = getConstraintGenerality(CType);
3745     if (Generality > BestGenerality) {
3746       BestType = CType;
3747       BestIdx = i;
3748       BestGenerality = Generality;
3749     }
3750   }
3751 
3752   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
3753   OpInfo.ConstraintType = BestType;
3754 }
3755 
3756 /// Determines the constraint code and constraint type to use for the specific
3757 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
3758 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
3759                                             SDValue Op,
3760                                             SelectionDAG *DAG) const {
3761   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
3762 
3763   // Single-letter constraints ('r') are very common.
3764   if (OpInfo.Codes.size() == 1) {
3765     OpInfo.ConstraintCode = OpInfo.Codes[0];
3766     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
3767   } else {
3768     ChooseConstraint(OpInfo, *this, Op, DAG);
3769   }
3770 
3771   // 'X' matches anything.
3772   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
3773     // Labels and constants are handled elsewhere ('X' is the only thing
3774     // that matches labels).  For Functions, the type here is the type of
3775     // the result, which is not what we want to look at; leave them alone.
3776     Value *v = OpInfo.CallOperandVal;
3777     if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
3778       OpInfo.CallOperandVal = v;
3779       return;
3780     }
3781 
3782     if (Op.getNode() && Op.getOpcode() == ISD::TargetBlockAddress)
3783       return;
3784 
3785     // Otherwise, try to resolve it to something we know about by looking at
3786     // the actual operand type.
3787     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
3788       OpInfo.ConstraintCode = Repl;
3789       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
3790     }
3791   }
3792 }
3793 
3794 /// Given an exact SDIV by a constant, create a multiplication
3795 /// with the multiplicative inverse of the constant.
3796 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N,
3797                               const SDLoc &dl, SelectionDAG &DAG,
3798                               SmallVectorImpl<SDNode *> &Created) {
3799   SDValue Op0 = N->getOperand(0);
3800   SDValue Op1 = N->getOperand(1);
3801   EVT VT = N->getValueType(0);
3802   EVT SVT = VT.getScalarType();
3803   EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
3804   EVT ShSVT = ShVT.getScalarType();
3805 
3806   bool UseSRA = false;
3807   SmallVector<SDValue, 16> Shifts, Factors;
3808 
3809   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
3810     if (C->isNullValue())
3811       return false;
3812     APInt Divisor = C->getAPIntValue();
3813     unsigned Shift = Divisor.countTrailingZeros();
3814     if (Shift) {
3815       Divisor.ashrInPlace(Shift);
3816       UseSRA = true;
3817     }
3818     // Calculate the multiplicative inverse, using Newton's method.
3819     APInt t;
3820     APInt Factor = Divisor;
3821     while ((t = Divisor * Factor) != 1)
3822       Factor *= APInt(Divisor.getBitWidth(), 2) - t;
3823     Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
3824     Factors.push_back(DAG.getConstant(Factor, dl, SVT));
3825     return true;
3826   };
3827 
3828   // Collect all magic values from the build vector.
3829   if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
3830     return SDValue();
3831 
3832   SDValue Shift, Factor;
3833   if (VT.isVector()) {
3834     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
3835     Factor = DAG.getBuildVector(VT, dl, Factors);
3836   } else {
3837     Shift = Shifts[0];
3838     Factor = Factors[0];
3839   }
3840 
3841   SDValue Res = Op0;
3842 
3843   // Shift the value upfront if it is even, so the LSB is one.
3844   if (UseSRA) {
3845     // TODO: For UDIV use SRL instead of SRA.
3846     SDNodeFlags Flags;
3847     Flags.setExact(true);
3848     Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags);
3849     Created.push_back(Res.getNode());
3850   }
3851 
3852   return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
3853 }
3854 
3855 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
3856                               SelectionDAG &DAG,
3857                               SmallVectorImpl<SDNode *> &Created) const {
3858   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3859   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3860   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
3861     return SDValue(N, 0); // Lower SDIV as SDIV
3862   return SDValue();
3863 }
3864 
3865 /// Given an ISD::SDIV node expressing a divide by constant,
3866 /// return a DAG expression to select that will generate the same value by
3867 /// multiplying by a magic number.
3868 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
3869 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
3870                                   bool IsAfterLegalization,
3871                                   SmallVectorImpl<SDNode *> &Created) const {
3872   SDLoc dl(N);
3873   EVT VT = N->getValueType(0);
3874   EVT SVT = VT.getScalarType();
3875   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
3876   EVT ShSVT = ShVT.getScalarType();
3877   unsigned EltBits = VT.getScalarSizeInBits();
3878 
3879   // Check to see if we can do this.
3880   // FIXME: We should be more aggressive here.
3881   if (!isTypeLegal(VT))
3882     return SDValue();
3883 
3884   // If the sdiv has an 'exact' bit we can use a simpler lowering.
3885   if (N->getFlags().hasExact())
3886     return BuildExactSDIV(*this, N, dl, DAG, Created);
3887 
3888   SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
3889 
3890   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
3891     if (C->isNullValue())
3892       return false;
3893 
3894     const APInt &Divisor = C->getAPIntValue();
3895     APInt::ms magics = Divisor.magic();
3896     int NumeratorFactor = 0;
3897     int ShiftMask = -1;
3898 
3899     if (Divisor.isOneValue() || Divisor.isAllOnesValue()) {
3900       // If d is +1/-1, we just multiply the numerator by +1/-1.
3901       NumeratorFactor = Divisor.getSExtValue();
3902       magics.m = 0;
3903       magics.s = 0;
3904       ShiftMask = 0;
3905     } else if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
3906       // If d > 0 and m < 0, add the numerator.
3907       NumeratorFactor = 1;
3908     } else if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
3909       // If d < 0 and m > 0, subtract the numerator.
3910       NumeratorFactor = -1;
3911     }
3912 
3913     MagicFactors.push_back(DAG.getConstant(magics.m, dl, SVT));
3914     Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT));
3915     Shifts.push_back(DAG.getConstant(magics.s, dl, ShSVT));
3916     ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT));
3917     return true;
3918   };
3919 
3920   SDValue N0 = N->getOperand(0);
3921   SDValue N1 = N->getOperand(1);
3922 
3923   // Collect the shifts / magic values from each element.
3924   if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern))
3925     return SDValue();
3926 
3927   SDValue MagicFactor, Factor, Shift, ShiftMask;
3928   if (VT.isVector()) {
3929     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
3930     Factor = DAG.getBuildVector(VT, dl, Factors);
3931     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
3932     ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
3933   } else {
3934     MagicFactor = MagicFactors[0];
3935     Factor = Factors[0];
3936     Shift = Shifts[0];
3937     ShiftMask = ShiftMasks[0];
3938   }
3939 
3940   // Multiply the numerator (operand 0) by the magic value.
3941   // FIXME: We should support doing a MUL in a wider type.
3942   SDValue Q;
3943   if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT)
3944                           : isOperationLegalOrCustom(ISD::MULHS, VT))
3945     Q = DAG.getNode(ISD::MULHS, dl, VT, N0, MagicFactor);
3946   else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT)
3947                                : isOperationLegalOrCustom(ISD::SMUL_LOHI, VT)) {
3948     SDValue LoHi =
3949         DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), N0, MagicFactor);
3950     Q = SDValue(LoHi.getNode(), 1);
3951   } else
3952     return SDValue(); // No mulhs or equivalent.
3953   Created.push_back(Q.getNode());
3954 
3955   // (Optionally) Add/subtract the numerator using Factor.
3956   Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
3957   Created.push_back(Factor.getNode());
3958   Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
3959   Created.push_back(Q.getNode());
3960 
3961   // Shift right algebraic by shift value.
3962   Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
3963   Created.push_back(Q.getNode());
3964 
3965   // Extract the sign bit, mask it and add it to the quotient.
3966   SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
3967   SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
3968   Created.push_back(T.getNode());
3969   T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
3970   Created.push_back(T.getNode());
3971   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
3972 }
3973 
3974 /// Given an ISD::UDIV node expressing a divide by constant,
3975 /// return a DAG expression to select that will generate the same value by
3976 /// multiplying by a magic number.
3977 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
3978 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
3979                                   bool IsAfterLegalization,
3980                                   SmallVectorImpl<SDNode *> &Created) const {
3981   SDLoc dl(N);
3982   EVT VT = N->getValueType(0);
3983   EVT SVT = VT.getScalarType();
3984   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
3985   EVT ShSVT = ShVT.getScalarType();
3986   unsigned EltBits = VT.getScalarSizeInBits();
3987 
3988   // Check to see if we can do this.
3989   // FIXME: We should be more aggressive here.
3990   if (!isTypeLegal(VT))
3991     return SDValue();
3992 
3993   bool UseNPQ = false;
3994   SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
3995 
3996   auto BuildUDIVPattern = [&](ConstantSDNode *C) {
3997     if (C->isNullValue())
3998       return false;
3999     // FIXME: We should use a narrower constant when the upper
4000     // bits are known to be zero.
4001     APInt Divisor = C->getAPIntValue();
4002     APInt::mu magics = Divisor.magicu();
4003     unsigned PreShift = 0, PostShift = 0;
4004 
4005     // If the divisor is even, we can avoid using the expensive fixup by
4006     // shifting the divided value upfront.
4007     if (magics.a != 0 && !Divisor[0]) {
4008       PreShift = Divisor.countTrailingZeros();
4009       // Get magic number for the shifted divisor.
4010       magics = Divisor.lshr(PreShift).magicu(PreShift);
4011       assert(magics.a == 0 && "Should use cheap fixup now");
4012     }
4013 
4014     APInt Magic = magics.m;
4015 
4016     unsigned SelNPQ;
4017     if (magics.a == 0 || Divisor.isOneValue()) {
4018       assert(magics.s < Divisor.getBitWidth() &&
4019              "We shouldn't generate an undefined shift!");
4020       PostShift = magics.s;
4021       SelNPQ = false;
4022     } else {
4023       PostShift = magics.s - 1;
4024       SelNPQ = true;
4025     }
4026 
4027     PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT));
4028     MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT));
4029     NPQFactors.push_back(
4030         DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1)
4031                                : APInt::getNullValue(EltBits),
4032                         dl, SVT));
4033     PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT));
4034     UseNPQ |= SelNPQ;
4035     return true;
4036   };
4037 
4038   SDValue N0 = N->getOperand(0);
4039   SDValue N1 = N->getOperand(1);
4040 
4041   // Collect the shifts/magic values from each element.
4042   if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern))
4043     return SDValue();
4044 
4045   SDValue PreShift, PostShift, MagicFactor, NPQFactor;
4046   if (VT.isVector()) {
4047     PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
4048     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
4049     NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
4050     PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
4051   } else {
4052     PreShift = PreShifts[0];
4053     MagicFactor = MagicFactors[0];
4054     PostShift = PostShifts[0];
4055   }
4056 
4057   SDValue Q = N0;
4058   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
4059   Created.push_back(Q.getNode());
4060 
4061   // FIXME: We should support doing a MUL in a wider type.
4062   auto GetMULHU = [&](SDValue X, SDValue Y) {
4063     if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT)
4064                             : isOperationLegalOrCustom(ISD::MULHU, VT))
4065       return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
4066     if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT)
4067                             : isOperationLegalOrCustom(ISD::UMUL_LOHI, VT)) {
4068       SDValue LoHi =
4069           DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
4070       return SDValue(LoHi.getNode(), 1);
4071     }
4072     return SDValue(); // No mulhu or equivalent
4073   };
4074 
4075   // Multiply the numerator (operand 0) by the magic value.
4076   Q = GetMULHU(Q, MagicFactor);
4077   if (!Q)
4078     return SDValue();
4079 
4080   Created.push_back(Q.getNode());
4081 
4082   if (UseNPQ) {
4083     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
4084     Created.push_back(NPQ.getNode());
4085 
4086     // For vectors we might have a mix of non-NPQ/NPQ paths, so use
4087     // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
4088     if (VT.isVector())
4089       NPQ = GetMULHU(NPQ, NPQFactor);
4090     else
4091       NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
4092 
4093     Created.push_back(NPQ.getNode());
4094 
4095     Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
4096     Created.push_back(Q.getNode());
4097   }
4098 
4099   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
4100   Created.push_back(Q.getNode());
4101 
4102   SDValue One = DAG.getConstant(1, dl, VT);
4103   SDValue IsOne = DAG.getSetCC(dl, VT, N1, One, ISD::SETEQ);
4104   return DAG.getSelect(dl, VT, IsOne, N0, Q);
4105 }
4106 
4107 bool TargetLowering::
4108 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
4109   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
4110     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
4111                                 "be a constant integer");
4112     return true;
4113   }
4114 
4115   return false;
4116 }
4117 
4118 //===----------------------------------------------------------------------===//
4119 // Legalization Utilities
4120 //===----------------------------------------------------------------------===//
4121 
4122 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl,
4123                                     SDValue LHS, SDValue RHS,
4124                                     SmallVectorImpl<SDValue> &Result,
4125                                     EVT HiLoVT, SelectionDAG &DAG,
4126                                     MulExpansionKind Kind, SDValue LL,
4127                                     SDValue LH, SDValue RL, SDValue RH) const {
4128   assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
4129          Opcode == ISD::SMUL_LOHI);
4130 
4131   bool HasMULHS = (Kind == MulExpansionKind::Always) ||
4132                   isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
4133   bool HasMULHU = (Kind == MulExpansionKind::Always) ||
4134                   isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
4135   bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
4136                       isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
4137   bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
4138                       isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
4139 
4140   if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
4141     return false;
4142 
4143   unsigned OuterBitSize = VT.getScalarSizeInBits();
4144   unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
4145   unsigned LHSSB = DAG.ComputeNumSignBits(LHS);
4146   unsigned RHSSB = DAG.ComputeNumSignBits(RHS);
4147 
4148   // LL, LH, RL, and RH must be either all NULL or all set to a value.
4149   assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
4150          (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
4151 
4152   SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
4153   auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
4154                           bool Signed) -> bool {
4155     if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
4156       Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
4157       Hi = SDValue(Lo.getNode(), 1);
4158       return true;
4159     }
4160     if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
4161       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
4162       Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
4163       return true;
4164     }
4165     return false;
4166   };
4167 
4168   SDValue Lo, Hi;
4169 
4170   if (!LL.getNode() && !RL.getNode() &&
4171       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
4172     LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
4173     RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
4174   }
4175 
4176   if (!LL.getNode())
4177     return false;
4178 
4179   APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
4180   if (DAG.MaskedValueIsZero(LHS, HighMask) &&
4181       DAG.MaskedValueIsZero(RHS, HighMask)) {
4182     // The inputs are both zero-extended.
4183     if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
4184       Result.push_back(Lo);
4185       Result.push_back(Hi);
4186       if (Opcode != ISD::MUL) {
4187         SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
4188         Result.push_back(Zero);
4189         Result.push_back(Zero);
4190       }
4191       return true;
4192     }
4193   }
4194 
4195   if (!VT.isVector() && Opcode == ISD::MUL && LHSSB > InnerBitSize &&
4196       RHSSB > InnerBitSize) {
4197     // The input values are both sign-extended.
4198     // TODO non-MUL case?
4199     if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
4200       Result.push_back(Lo);
4201       Result.push_back(Hi);
4202       return true;
4203     }
4204   }
4205 
4206   unsigned ShiftAmount = OuterBitSize - InnerBitSize;
4207   EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout());
4208   if (APInt::getMaxValue(ShiftAmountTy.getSizeInBits()).ult(ShiftAmount)) {
4209     // FIXME getShiftAmountTy does not always return a sensible result when VT
4210     // is an illegal type, and so the type may be too small to fit the shift
4211     // amount. Override it with i32. The shift will have to be legalized.
4212     ShiftAmountTy = MVT::i32;
4213   }
4214   SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy);
4215 
4216   if (!LH.getNode() && !RH.getNode() &&
4217       isOperationLegalOrCustom(ISD::SRL, VT) &&
4218       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
4219     LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
4220     LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
4221     RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
4222     RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
4223   }
4224 
4225   if (!LH.getNode())
4226     return false;
4227 
4228   if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
4229     return false;
4230 
4231   Result.push_back(Lo);
4232 
4233   if (Opcode == ISD::MUL) {
4234     RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
4235     LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
4236     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
4237     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
4238     Result.push_back(Hi);
4239     return true;
4240   }
4241 
4242   // Compute the full width result.
4243   auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
4244     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
4245     Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
4246     Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
4247     return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
4248   };
4249 
4250   SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
4251   if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
4252     return false;
4253 
4254   // This is effectively the add part of a multiply-add of half-sized operands,
4255   // so it cannot overflow.
4256   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
4257 
4258   if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
4259     return false;
4260 
4261   SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
4262   EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
4263 
4264   bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
4265                   isOperationLegalOrCustom(ISD::ADDE, VT));
4266   if (UseGlue)
4267     Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
4268                        Merge(Lo, Hi));
4269   else
4270     Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next,
4271                        Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
4272 
4273   SDValue Carry = Next.getValue(1);
4274   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
4275   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
4276 
4277   if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
4278     return false;
4279 
4280   if (UseGlue)
4281     Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
4282                      Carry);
4283   else
4284     Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
4285                      Zero, Carry);
4286 
4287   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
4288 
4289   if (Opcode == ISD::SMUL_LOHI) {
4290     SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
4291                                   DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
4292     Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
4293 
4294     NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
4295                           DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
4296     Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
4297   }
4298 
4299   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
4300   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
4301   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
4302   return true;
4303 }
4304 
4305 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
4306                                SelectionDAG &DAG, MulExpansionKind Kind,
4307                                SDValue LL, SDValue LH, SDValue RL,
4308                                SDValue RH) const {
4309   SmallVector<SDValue, 2> Result;
4310   bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), N,
4311                            N->getOperand(0), N->getOperand(1), Result, HiLoVT,
4312                            DAG, Kind, LL, LH, RL, RH);
4313   if (Ok) {
4314     assert(Result.size() == 2);
4315     Lo = Result[0];
4316     Hi = Result[1];
4317   }
4318   return Ok;
4319 }
4320 
4321 bool TargetLowering::expandFunnelShift(SDNode *Node, SDValue &Result,
4322                                        SelectionDAG &DAG) const {
4323   EVT VT = Node->getValueType(0);
4324 
4325   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
4326                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
4327                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
4328                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
4329     return false;
4330 
4331   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
4332   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
4333   SDValue X = Node->getOperand(0);
4334   SDValue Y = Node->getOperand(1);
4335   SDValue Z = Node->getOperand(2);
4336 
4337   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4338   bool IsFSHL = Node->getOpcode() == ISD::FSHL;
4339   SDLoc DL(SDValue(Node, 0));
4340 
4341   EVT ShVT = Z.getValueType();
4342   SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
4343   SDValue Zero = DAG.getConstant(0, DL, ShVT);
4344 
4345   SDValue ShAmt;
4346   if (isPowerOf2_32(EltSizeInBits)) {
4347     SDValue Mask = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
4348     ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
4349   } else {
4350     ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
4351   }
4352 
4353   SDValue InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
4354   SDValue ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
4355   SDValue ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
4356   SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
4357 
4358   // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
4359   // and that is undefined. We must compare and select to avoid UB.
4360   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShVT);
4361 
4362   // For fshl, 0-shift returns the 1st arg (X).
4363   // For fshr, 0-shift returns the 2nd arg (Y).
4364   SDValue IsZeroShift = DAG.getSetCC(DL, CCVT, ShAmt, Zero, ISD::SETEQ);
4365   Result = DAG.getSelect(DL, VT, IsZeroShift, IsFSHL ? X : Y, Or);
4366   return true;
4367 }
4368 
4369 // TODO: Merge with expandFunnelShift.
4370 bool TargetLowering::expandROT(SDNode *Node, SDValue &Result,
4371                                SelectionDAG &DAG) const {
4372   EVT VT = Node->getValueType(0);
4373   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4374   bool IsLeft = Node->getOpcode() == ISD::ROTL;
4375   SDValue Op0 = Node->getOperand(0);
4376   SDValue Op1 = Node->getOperand(1);
4377   SDLoc DL(SDValue(Node, 0));
4378 
4379   EVT ShVT = Op1.getValueType();
4380   SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
4381 
4382   // If a rotate in the other direction is legal, use it.
4383   unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
4384   if (isOperationLegal(RevRot, VT)) {
4385     SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, Op1);
4386     Result = DAG.getNode(RevRot, DL, VT, Op0, Sub);
4387     return true;
4388   }
4389 
4390   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
4391                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
4392                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
4393                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT) ||
4394                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT)))
4395     return false;
4396 
4397   // Otherwise,
4398   //   (rotl x, c) -> (or (shl x, (and c, w-1)), (srl x, (and w-c, w-1)))
4399   //   (rotr x, c) -> (or (srl x, (and c, w-1)), (shl x, (and w-c, w-1)))
4400   //
4401   assert(isPowerOf2_32(EltSizeInBits) && EltSizeInBits > 1 &&
4402          "Expecting the type bitwidth to be a power of 2");
4403   unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
4404   unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
4405   SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
4406   SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, Op1);
4407   SDValue And0 = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
4408   SDValue And1 = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
4409   Result = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ShOpc, DL, VT, Op0, And0),
4410                        DAG.getNode(HsOpc, DL, VT, Op0, And1));
4411   return true;
4412 }
4413 
4414 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
4415                                       SelectionDAG &DAG) const {
4416   SDValue Src = Node->getOperand(0);
4417   EVT SrcVT = Src.getValueType();
4418   EVT DstVT = Node->getValueType(0);
4419   SDLoc dl(SDValue(Node, 0));
4420 
4421   // FIXME: Only f32 to i64 conversions are supported.
4422   if (SrcVT != MVT::f32 || DstVT != MVT::i64)
4423     return false;
4424 
4425   // Expand f32 -> i64 conversion
4426   // This algorithm comes from compiler-rt's implementation of fixsfdi:
4427   // https://github.com/llvm/llvm-project/blob/master/compiler-rt/lib/builtins/fixsfdi.c
4428   unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
4429   EVT IntVT = SrcVT.changeTypeToInteger();
4430   EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
4431 
4432   SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
4433   SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
4434   SDValue Bias = DAG.getConstant(127, dl, IntVT);
4435   SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
4436   SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
4437   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
4438 
4439   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
4440 
4441   SDValue ExponentBits = DAG.getNode(
4442       ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
4443       DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
4444   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
4445 
4446   SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
4447                              DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
4448                              DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
4449   Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
4450 
4451   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
4452                           DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
4453                           DAG.getConstant(0x00800000, dl, IntVT));
4454 
4455   R = DAG.getZExtOrTrunc(R, dl, DstVT);
4456 
4457   R = DAG.getSelectCC(
4458       dl, Exponent, ExponentLoBit,
4459       DAG.getNode(ISD::SHL, dl, DstVT, R,
4460                   DAG.getZExtOrTrunc(
4461                       DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
4462                       dl, IntShVT)),
4463       DAG.getNode(ISD::SRL, dl, DstVT, R,
4464                   DAG.getZExtOrTrunc(
4465                       DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
4466                       dl, IntShVT)),
4467       ISD::SETGT);
4468 
4469   SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
4470                             DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
4471 
4472   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
4473                            DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
4474   return true;
4475 }
4476 
4477 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result,
4478                                       SelectionDAG &DAG) const {
4479   SDLoc dl(SDValue(Node, 0));
4480   SDValue Src = Node->getOperand(0);
4481 
4482   EVT SrcVT = Src.getValueType();
4483   EVT DstVT = Node->getValueType(0);
4484   EVT SetCCVT =
4485       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
4486 
4487   // Only expand vector types if we have the appropriate vector bit operations.
4488   if (DstVT.isVector() && (!isOperationLegalOrCustom(ISD::FP_TO_SINT, DstVT) ||
4489                            !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT)))
4490     return false;
4491 
4492   // If the maximum float value is smaller then the signed integer range,
4493   // the destination signmask can't be represented by the float, so we can
4494   // just use FP_TO_SINT directly.
4495   const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT);
4496   APFloat APF(APFSem, APInt::getNullValue(SrcVT.getScalarSizeInBits()));
4497   APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
4498   if (APFloat::opOverflow &
4499       APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
4500     Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
4501     return true;
4502   }
4503 
4504   SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
4505   SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
4506 
4507   bool Strict = shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
4508   if (Strict) {
4509     // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
4510     // signmask then offset (the result of which should be fully representable).
4511     // Sel = Src < 0x8000000000000000
4512     // Val = select Sel, Src, Src - 0x8000000000000000
4513     // Ofs = select Sel, 0, 0x8000000000000000
4514     // Result = fp_to_sint(Val) ^ Ofs
4515 
4516     // TODO: Should any fast-math-flags be set for the FSUB?
4517     SDValue Val = DAG.getSelect(dl, SrcVT, Sel, Src,
4518                                 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
4519     SDValue Ofs = DAG.getSelect(dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT),
4520                                 DAG.getConstant(SignMask, dl, DstVT));
4521     Result = DAG.getNode(ISD::XOR, dl, DstVT,
4522                          DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val), Ofs);
4523   } else {
4524     // Expand based on maximum range of FP_TO_SINT:
4525     // True = fp_to_sint(Src)
4526     // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
4527     // Result = select (Src < 0x8000000000000000), True, False
4528 
4529     SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
4530     // TODO: Should any fast-math-flags be set for the FSUB?
4531     SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
4532                                 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
4533     False = DAG.getNode(ISD::XOR, dl, DstVT, False,
4534                         DAG.getConstant(SignMask, dl, DstVT));
4535     Result = DAG.getSelect(dl, DstVT, Sel, True, False);
4536   }
4537   return true;
4538 }
4539 
4540 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result,
4541                                       SelectionDAG &DAG) const {
4542   SDValue Src = Node->getOperand(0);
4543   EVT SrcVT = Src.getValueType();
4544   EVT DstVT = Node->getValueType(0);
4545 
4546   if (SrcVT.getScalarType() != MVT::i64)
4547     return false;
4548 
4549   SDLoc dl(SDValue(Node, 0));
4550   EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout());
4551 
4552   if (DstVT.getScalarType() == MVT::f32) {
4553     // Only expand vector types if we have the appropriate vector bit
4554     // operations.
4555     if (SrcVT.isVector() &&
4556         (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
4557          !isOperationLegalOrCustom(ISD::FADD, DstVT) ||
4558          !isOperationLegalOrCustom(ISD::SINT_TO_FP, SrcVT) ||
4559          !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) ||
4560          !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT)))
4561       return false;
4562 
4563     // For unsigned conversions, convert them to signed conversions using the
4564     // algorithm from the x86_64 __floatundidf in compiler_rt.
4565     SDValue Fast = DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Src);
4566 
4567     SDValue ShiftConst = DAG.getConstant(1, dl, ShiftVT);
4568     SDValue Shr = DAG.getNode(ISD::SRL, dl, SrcVT, Src, ShiftConst);
4569     SDValue AndConst = DAG.getConstant(1, dl, SrcVT);
4570     SDValue And = DAG.getNode(ISD::AND, dl, SrcVT, Src, AndConst);
4571     SDValue Or = DAG.getNode(ISD::OR, dl, SrcVT, And, Shr);
4572 
4573     SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Or);
4574     SDValue Slow = DAG.getNode(ISD::FADD, dl, DstVT, SignCvt, SignCvt);
4575 
4576     // TODO: This really should be implemented using a branch rather than a
4577     // select.  We happen to get lucky and machinesink does the right
4578     // thing most of the time.  This would be a good candidate for a
4579     // pseudo-op, or, even better, for whole-function isel.
4580     EVT SetCCVT =
4581         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
4582 
4583     SDValue SignBitTest = DAG.getSetCC(
4584         dl, SetCCVT, Src, DAG.getConstant(0, dl, SrcVT), ISD::SETLT);
4585     Result = DAG.getSelect(dl, DstVT, SignBitTest, Slow, Fast);
4586     return true;
4587   }
4588 
4589   if (DstVT.getScalarType() == MVT::f64) {
4590     // Only expand vector types if we have the appropriate vector bit
4591     // operations.
4592     if (SrcVT.isVector() &&
4593         (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
4594          !isOperationLegalOrCustom(ISD::FADD, DstVT) ||
4595          !isOperationLegalOrCustom(ISD::FSUB, DstVT) ||
4596          !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) ||
4597          !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT)))
4598       return false;
4599 
4600     // Implementation of unsigned i64 to f64 following the algorithm in
4601     // __floatundidf in compiler_rt. This implementation has the advantage
4602     // of performing rounding correctly, both in the default rounding mode
4603     // and in all alternate rounding modes.
4604     SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
4605     SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
4606         BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT);
4607     SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
4608     SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
4609     SDValue HiShift = DAG.getConstant(32, dl, ShiftVT);
4610 
4611     SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
4612     SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
4613     SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
4614     SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
4615     SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
4616     SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
4617     SDValue HiSub = DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
4618     Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
4619     return true;
4620   }
4621 
4622   return false;
4623 }
4624 
4625 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node,
4626                                               SelectionDAG &DAG) const {
4627   SDLoc dl(Node);
4628   unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ?
4629     ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
4630   EVT VT = Node->getValueType(0);
4631   if (isOperationLegalOrCustom(NewOp, VT)) {
4632     SDValue Quiet0 = Node->getOperand(0);
4633     SDValue Quiet1 = Node->getOperand(1);
4634 
4635     if (!Node->getFlags().hasNoNaNs()) {
4636       // Insert canonicalizes if it's possible we need to quiet to get correct
4637       // sNaN behavior.
4638       if (!DAG.isKnownNeverSNaN(Quiet0)) {
4639         Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
4640                              Node->getFlags());
4641       }
4642       if (!DAG.isKnownNeverSNaN(Quiet1)) {
4643         Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
4644                              Node->getFlags());
4645       }
4646     }
4647 
4648     return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
4649   }
4650 
4651   return SDValue();
4652 }
4653 
4654 bool TargetLowering::expandCTPOP(SDNode *Node, SDValue &Result,
4655                                  SelectionDAG &DAG) const {
4656   SDLoc dl(Node);
4657   EVT VT = Node->getValueType(0);
4658   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
4659   SDValue Op = Node->getOperand(0);
4660   unsigned Len = VT.getScalarSizeInBits();
4661   assert(VT.isInteger() && "CTPOP not implemented for this type.");
4662 
4663   // TODO: Add support for irregular type lengths.
4664   if (!(Len <= 128 && Len % 8 == 0))
4665     return false;
4666 
4667   // Only expand vector types if we have the appropriate vector bit operations.
4668   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::ADD, VT) ||
4669                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
4670                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
4671                         (Len != 8 && !isOperationLegalOrCustom(ISD::MUL, VT)) ||
4672                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT)))
4673     return false;
4674 
4675   // This is the "best" algorithm from
4676   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
4677   SDValue Mask55 =
4678       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
4679   SDValue Mask33 =
4680       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
4681   SDValue Mask0F =
4682       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
4683   SDValue Mask01 =
4684       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
4685 
4686   // v = v - ((v >> 1) & 0x55555555...)
4687   Op = DAG.getNode(ISD::SUB, dl, VT, Op,
4688                    DAG.getNode(ISD::AND, dl, VT,
4689                                DAG.getNode(ISD::SRL, dl, VT, Op,
4690                                            DAG.getConstant(1, dl, ShVT)),
4691                                Mask55));
4692   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
4693   Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
4694                    DAG.getNode(ISD::AND, dl, VT,
4695                                DAG.getNode(ISD::SRL, dl, VT, Op,
4696                                            DAG.getConstant(2, dl, ShVT)),
4697                                Mask33));
4698   // v = (v + (v >> 4)) & 0x0F0F0F0F...
4699   Op = DAG.getNode(ISD::AND, dl, VT,
4700                    DAG.getNode(ISD::ADD, dl, VT, Op,
4701                                DAG.getNode(ISD::SRL, dl, VT, Op,
4702                                            DAG.getConstant(4, dl, ShVT))),
4703                    Mask0F);
4704   // v = (v * 0x01010101...) >> (Len - 8)
4705   if (Len > 8)
4706     Op =
4707         DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
4708                     DAG.getConstant(Len - 8, dl, ShVT));
4709 
4710   Result = Op;
4711   return true;
4712 }
4713 
4714 bool TargetLowering::expandCTLZ(SDNode *Node, SDValue &Result,
4715                                 SelectionDAG &DAG) const {
4716   SDLoc dl(Node);
4717   EVT VT = Node->getValueType(0);
4718   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
4719   SDValue Op = Node->getOperand(0);
4720   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
4721 
4722   // If the non-ZERO_UNDEF version is supported we can use that instead.
4723   if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF &&
4724       isOperationLegalOrCustom(ISD::CTLZ, VT)) {
4725     Result = DAG.getNode(ISD::CTLZ, dl, VT, Op);
4726     return true;
4727   }
4728 
4729   // If the ZERO_UNDEF version is supported use that and handle the zero case.
4730   if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) {
4731     EVT SetCCVT =
4732         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
4733     SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op);
4734     SDValue Zero = DAG.getConstant(0, dl, VT);
4735     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
4736     Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero,
4737                          DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
4738     return true;
4739   }
4740 
4741   // Only expand vector types if we have the appropriate vector bit operations.
4742   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
4743                         !isOperationLegalOrCustom(ISD::CTPOP, VT) ||
4744                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
4745                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
4746     return false;
4747 
4748   // for now, we do this:
4749   // x = x | (x >> 1);
4750   // x = x | (x >> 2);
4751   // ...
4752   // x = x | (x >>16);
4753   // x = x | (x >>32); // for 64-bit input
4754   // return popcount(~x);
4755   //
4756   // Ref: "Hacker's Delight" by Henry Warren
4757   for (unsigned i = 0; (1U << i) <= (NumBitsPerElt / 2); ++i) {
4758     SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
4759     Op = DAG.getNode(ISD::OR, dl, VT, Op,
4760                      DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
4761   }
4762   Op = DAG.getNOT(dl, Op, VT);
4763   Result = DAG.getNode(ISD::CTPOP, dl, VT, Op);
4764   return true;
4765 }
4766 
4767 bool TargetLowering::expandCTTZ(SDNode *Node, SDValue &Result,
4768                                 SelectionDAG &DAG) const {
4769   SDLoc dl(Node);
4770   EVT VT = Node->getValueType(0);
4771   SDValue Op = Node->getOperand(0);
4772   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
4773 
4774   // If the non-ZERO_UNDEF version is supported we can use that instead.
4775   if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
4776       isOperationLegalOrCustom(ISD::CTTZ, VT)) {
4777     Result = DAG.getNode(ISD::CTTZ, dl, VT, Op);
4778     return true;
4779   }
4780 
4781   // If the ZERO_UNDEF version is supported use that and handle the zero case.
4782   if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) {
4783     EVT SetCCVT =
4784         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
4785     SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op);
4786     SDValue Zero = DAG.getConstant(0, dl, VT);
4787     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
4788     Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero,
4789                          DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
4790     return true;
4791   }
4792 
4793   // Only expand vector types if we have the appropriate vector bit operations.
4794   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
4795                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
4796                          !isOperationLegalOrCustom(ISD::CTLZ, VT)) ||
4797                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
4798                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT) ||
4799                         !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
4800     return false;
4801 
4802   // for now, we use: { return popcount(~x & (x - 1)); }
4803   // unless the target has ctlz but not ctpop, in which case we use:
4804   // { return 32 - nlz(~x & (x-1)); }
4805   // Ref: "Hacker's Delight" by Henry Warren
4806   SDValue Tmp = DAG.getNode(
4807       ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
4808       DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
4809 
4810   // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
4811   if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) {
4812     Result =
4813         DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
4814                     DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
4815     return true;
4816   }
4817 
4818   Result = DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
4819   return true;
4820 }
4821 
4822 bool TargetLowering::expandABS(SDNode *N, SDValue &Result,
4823                                SelectionDAG &DAG) const {
4824   SDLoc dl(N);
4825   EVT VT = N->getValueType(0);
4826   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
4827   SDValue Op = N->getOperand(0);
4828 
4829   // Only expand vector types if we have the appropriate vector operations.
4830   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SRA, VT) ||
4831                         !isOperationLegalOrCustom(ISD::ADD, VT) ||
4832                         !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
4833     return false;
4834 
4835   SDValue Shift =
4836       DAG.getNode(ISD::SRA, dl, VT, Op,
4837                   DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT));
4838   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, Op, Shift);
4839   Result = DAG.getNode(ISD::XOR, dl, VT, Add, Shift);
4840   return true;
4841 }
4842 
4843 SDValue TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
4844                                             SelectionDAG &DAG) const {
4845   SDLoc SL(LD);
4846   SDValue Chain = LD->getChain();
4847   SDValue BasePTR = LD->getBasePtr();
4848   EVT SrcVT = LD->getMemoryVT();
4849   ISD::LoadExtType ExtType = LD->getExtensionType();
4850 
4851   unsigned NumElem = SrcVT.getVectorNumElements();
4852 
4853   EVT SrcEltVT = SrcVT.getScalarType();
4854   EVT DstEltVT = LD->getValueType(0).getScalarType();
4855 
4856   unsigned Stride = SrcEltVT.getSizeInBits() / 8;
4857   assert(SrcEltVT.isByteSized());
4858 
4859   SmallVector<SDValue, 8> Vals;
4860   SmallVector<SDValue, 8> LoadChains;
4861 
4862   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
4863     SDValue ScalarLoad =
4864         DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
4865                        LD->getPointerInfo().getWithOffset(Idx * Stride),
4866                        SrcEltVT, MinAlign(LD->getAlignment(), Idx * Stride),
4867                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
4868 
4869     BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, Stride);
4870 
4871     Vals.push_back(ScalarLoad.getValue(0));
4872     LoadChains.push_back(ScalarLoad.getValue(1));
4873   }
4874 
4875   SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
4876   SDValue Value = DAG.getBuildVector(LD->getValueType(0), SL, Vals);
4877 
4878   return DAG.getMergeValues({Value, NewChain}, SL);
4879 }
4880 
4881 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
4882                                              SelectionDAG &DAG) const {
4883   SDLoc SL(ST);
4884 
4885   SDValue Chain = ST->getChain();
4886   SDValue BasePtr = ST->getBasePtr();
4887   SDValue Value = ST->getValue();
4888   EVT StVT = ST->getMemoryVT();
4889 
4890   // The type of the data we want to save
4891   EVT RegVT = Value.getValueType();
4892   EVT RegSclVT = RegVT.getScalarType();
4893 
4894   // The type of data as saved in memory.
4895   EVT MemSclVT = StVT.getScalarType();
4896 
4897   EVT IdxVT = getVectorIdxTy(DAG.getDataLayout());
4898   unsigned NumElem = StVT.getVectorNumElements();
4899 
4900   // A vector must always be stored in memory as-is, i.e. without any padding
4901   // between the elements, since various code depend on it, e.g. in the
4902   // handling of a bitcast of a vector type to int, which may be done with a
4903   // vector store followed by an integer load. A vector that does not have
4904   // elements that are byte-sized must therefore be stored as an integer
4905   // built out of the extracted vector elements.
4906   if (!MemSclVT.isByteSized()) {
4907     unsigned NumBits = StVT.getSizeInBits();
4908     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
4909 
4910     SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
4911 
4912     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
4913       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
4914                                 DAG.getConstant(Idx, SL, IdxVT));
4915       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
4916       SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
4917       unsigned ShiftIntoIdx =
4918           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
4919       SDValue ShiftAmount =
4920           DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
4921       SDValue ShiftedElt =
4922           DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
4923       CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
4924     }
4925 
4926     return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
4927                         ST->getAlignment(), ST->getMemOperand()->getFlags(),
4928                         ST->getAAInfo());
4929   }
4930 
4931   // Store Stride in bytes
4932   unsigned Stride = MemSclVT.getSizeInBits() / 8;
4933   assert(Stride && "Zero stride!");
4934   // Extract each of the elements from the original vector and save them into
4935   // memory individually.
4936   SmallVector<SDValue, 8> Stores;
4937   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
4938     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
4939                               DAG.getConstant(Idx, SL, IdxVT));
4940 
4941     SDValue Ptr = DAG.getObjectPtrOffset(SL, BasePtr, Idx * Stride);
4942 
4943     // This scalar TruncStore may be illegal, but we legalize it later.
4944     SDValue Store = DAG.getTruncStore(
4945         Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
4946         MemSclVT, MinAlign(ST->getAlignment(), Idx * Stride),
4947         ST->getMemOperand()->getFlags(), ST->getAAInfo());
4948 
4949     Stores.push_back(Store);
4950   }
4951 
4952   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
4953 }
4954 
4955 std::pair<SDValue, SDValue>
4956 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
4957   assert(LD->getAddressingMode() == ISD::UNINDEXED &&
4958          "unaligned indexed loads not implemented!");
4959   SDValue Chain = LD->getChain();
4960   SDValue Ptr = LD->getBasePtr();
4961   EVT VT = LD->getValueType(0);
4962   EVT LoadedVT = LD->getMemoryVT();
4963   SDLoc dl(LD);
4964   auto &MF = DAG.getMachineFunction();
4965 
4966   if (VT.isFloatingPoint() || VT.isVector()) {
4967     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
4968     if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
4969       if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
4970           LoadedVT.isVector()) {
4971         // Scalarize the load and let the individual components be handled.
4972         SDValue Scalarized = scalarizeVectorLoad(LD, DAG);
4973         if (Scalarized->getOpcode() == ISD::MERGE_VALUES)
4974           return std::make_pair(Scalarized.getOperand(0), Scalarized.getOperand(1));
4975         return std::make_pair(Scalarized.getValue(0), Scalarized.getValue(1));
4976       }
4977 
4978       // Expand to a (misaligned) integer load of the same size,
4979       // then bitconvert to floating point or vector.
4980       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
4981                                     LD->getMemOperand());
4982       SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
4983       if (LoadedVT != VT)
4984         Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
4985                              ISD::ANY_EXTEND, dl, VT, Result);
4986 
4987       return std::make_pair(Result, newLoad.getValue(1));
4988     }
4989 
4990     // Copy the value to a (aligned) stack slot using (unaligned) integer
4991     // loads and stores, then do a (aligned) load from the stack slot.
4992     MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
4993     unsigned LoadedBytes = LoadedVT.getStoreSize();
4994     unsigned RegBytes = RegVT.getSizeInBits() / 8;
4995     unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
4996 
4997     // Make sure the stack slot is also aligned for the register type.
4998     SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
4999     auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
5000     SmallVector<SDValue, 8> Stores;
5001     SDValue StackPtr = StackBase;
5002     unsigned Offset = 0;
5003 
5004     EVT PtrVT = Ptr.getValueType();
5005     EVT StackPtrVT = StackPtr.getValueType();
5006 
5007     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
5008     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
5009 
5010     // Do all but one copies using the full register width.
5011     for (unsigned i = 1; i < NumRegs; i++) {
5012       // Load one integer register's worth from the original location.
5013       SDValue Load = DAG.getLoad(
5014           RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
5015           MinAlign(LD->getAlignment(), Offset), LD->getMemOperand()->getFlags(),
5016           LD->getAAInfo());
5017       // Follow the load with a store to the stack slot.  Remember the store.
5018       Stores.push_back(DAG.getStore(
5019           Load.getValue(1), dl, Load, StackPtr,
5020           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
5021       // Increment the pointers.
5022       Offset += RegBytes;
5023 
5024       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
5025       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
5026     }
5027 
5028     // The last copy may be partial.  Do an extending load.
5029     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
5030                                   8 * (LoadedBytes - Offset));
5031     SDValue Load =
5032         DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
5033                        LD->getPointerInfo().getWithOffset(Offset), MemVT,
5034                        MinAlign(LD->getAlignment(), Offset),
5035                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
5036     // Follow the load with a store to the stack slot.  Remember the store.
5037     // On big-endian machines this requires a truncating store to ensure
5038     // that the bits end up in the right place.
5039     Stores.push_back(DAG.getTruncStore(
5040         Load.getValue(1), dl, Load, StackPtr,
5041         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
5042 
5043     // The order of the stores doesn't matter - say it with a TokenFactor.
5044     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
5045 
5046     // Finally, perform the original load only redirected to the stack slot.
5047     Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
5048                           MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
5049                           LoadedVT);
5050 
5051     // Callers expect a MERGE_VALUES node.
5052     return std::make_pair(Load, TF);
5053   }
5054 
5055   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
5056          "Unaligned load of unsupported type.");
5057 
5058   // Compute the new VT that is half the size of the old one.  This is an
5059   // integer MVT.
5060   unsigned NumBits = LoadedVT.getSizeInBits();
5061   EVT NewLoadedVT;
5062   NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
5063   NumBits >>= 1;
5064 
5065   unsigned Alignment = LD->getAlignment();
5066   unsigned IncrementSize = NumBits / 8;
5067   ISD::LoadExtType HiExtType = LD->getExtensionType();
5068 
5069   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
5070   if (HiExtType == ISD::NON_EXTLOAD)
5071     HiExtType = ISD::ZEXTLOAD;
5072 
5073   // Load the value in two parts
5074   SDValue Lo, Hi;
5075   if (DAG.getDataLayout().isLittleEndian()) {
5076     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
5077                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
5078                         LD->getAAInfo());
5079 
5080     Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
5081     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
5082                         LD->getPointerInfo().getWithOffset(IncrementSize),
5083                         NewLoadedVT, MinAlign(Alignment, IncrementSize),
5084                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
5085   } else {
5086     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
5087                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
5088                         LD->getAAInfo());
5089 
5090     Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
5091     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
5092                         LD->getPointerInfo().getWithOffset(IncrementSize),
5093                         NewLoadedVT, MinAlign(Alignment, IncrementSize),
5094                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
5095   }
5096 
5097   // aggregate the two parts
5098   SDValue ShiftAmount =
5099       DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
5100                                                     DAG.getDataLayout()));
5101   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
5102   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
5103 
5104   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
5105                              Hi.getValue(1));
5106 
5107   return std::make_pair(Result, TF);
5108 }
5109 
5110 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
5111                                              SelectionDAG &DAG) const {
5112   assert(ST->getAddressingMode() == ISD::UNINDEXED &&
5113          "unaligned indexed stores not implemented!");
5114   SDValue Chain = ST->getChain();
5115   SDValue Ptr = ST->getBasePtr();
5116   SDValue Val = ST->getValue();
5117   EVT VT = Val.getValueType();
5118   int Alignment = ST->getAlignment();
5119   auto &MF = DAG.getMachineFunction();
5120   EVT MemVT = ST->getMemoryVT();
5121 
5122   SDLoc dl(ST);
5123   if (MemVT.isFloatingPoint() || MemVT.isVector()) {
5124     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
5125     if (isTypeLegal(intVT)) {
5126       if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
5127           MemVT.isVector()) {
5128         // Scalarize the store and let the individual components be handled.
5129         SDValue Result = scalarizeVectorStore(ST, DAG);
5130 
5131         return Result;
5132       }
5133       // Expand to a bitconvert of the value to the integer type of the
5134       // same size, then a (misaligned) int store.
5135       // FIXME: Does not handle truncating floating point stores!
5136       SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
5137       Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
5138                             Alignment, ST->getMemOperand()->getFlags());
5139       return Result;
5140     }
5141     // Do a (aligned) store to a stack slot, then copy from the stack slot
5142     // to the final destination using (unaligned) integer loads and stores.
5143     EVT StoredVT = ST->getMemoryVT();
5144     MVT RegVT =
5145       getRegisterType(*DAG.getContext(),
5146                       EVT::getIntegerVT(*DAG.getContext(),
5147                                         StoredVT.getSizeInBits()));
5148     EVT PtrVT = Ptr.getValueType();
5149     unsigned StoredBytes = StoredVT.getStoreSize();
5150     unsigned RegBytes = RegVT.getSizeInBits() / 8;
5151     unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
5152 
5153     // Make sure the stack slot is also aligned for the register type.
5154     SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
5155     auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
5156 
5157     // Perform the original store, only redirected to the stack slot.
5158     SDValue Store = DAG.getTruncStore(
5159         Chain, dl, Val, StackPtr,
5160         MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoredVT);
5161 
5162     EVT StackPtrVT = StackPtr.getValueType();
5163 
5164     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
5165     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
5166     SmallVector<SDValue, 8> Stores;
5167     unsigned Offset = 0;
5168 
5169     // Do all but one copies using the full register width.
5170     for (unsigned i = 1; i < NumRegs; i++) {
5171       // Load one integer register's worth from the stack slot.
5172       SDValue Load = DAG.getLoad(
5173           RegVT, dl, Store, StackPtr,
5174           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
5175       // Store it to the final location.  Remember the store.
5176       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
5177                                     ST->getPointerInfo().getWithOffset(Offset),
5178                                     MinAlign(ST->getAlignment(), Offset),
5179                                     ST->getMemOperand()->getFlags()));
5180       // Increment the pointers.
5181       Offset += RegBytes;
5182       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
5183       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
5184     }
5185 
5186     // The last store may be partial.  Do a truncating store.  On big-endian
5187     // machines this requires an extending load from the stack slot to ensure
5188     // that the bits are in the right place.
5189     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
5190                                   8 * (StoredBytes - Offset));
5191 
5192     // Load from the stack slot.
5193     SDValue Load = DAG.getExtLoad(
5194         ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
5195         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT);
5196 
5197     Stores.push_back(
5198         DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
5199                           ST->getPointerInfo().getWithOffset(Offset), MemVT,
5200                           MinAlign(ST->getAlignment(), Offset),
5201                           ST->getMemOperand()->getFlags(), ST->getAAInfo()));
5202     // The order of the stores doesn't matter - say it with a TokenFactor.
5203     SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
5204     return Result;
5205   }
5206 
5207   assert(ST->getMemoryVT().isInteger() &&
5208          !ST->getMemoryVT().isVector() &&
5209          "Unaligned store of unknown type.");
5210   // Get the half-size VT
5211   EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
5212   int NumBits = NewStoredVT.getSizeInBits();
5213   int IncrementSize = NumBits / 8;
5214 
5215   // Divide the stored value in two parts.
5216   SDValue ShiftAmount =
5217       DAG.getConstant(NumBits, dl, getShiftAmountTy(Val.getValueType(),
5218                                                     DAG.getDataLayout()));
5219   SDValue Lo = Val;
5220   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
5221 
5222   // Store the two parts
5223   SDValue Store1, Store2;
5224   Store1 = DAG.getTruncStore(Chain, dl,
5225                              DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
5226                              Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
5227                              ST->getMemOperand()->getFlags());
5228 
5229   Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
5230   Alignment = MinAlign(Alignment, IncrementSize);
5231   Store2 = DAG.getTruncStore(
5232       Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
5233       ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
5234       ST->getMemOperand()->getFlags(), ST->getAAInfo());
5235 
5236   SDValue Result =
5237     DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
5238   return Result;
5239 }
5240 
5241 SDValue
5242 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask,
5243                                        const SDLoc &DL, EVT DataVT,
5244                                        SelectionDAG &DAG,
5245                                        bool IsCompressedMemory) const {
5246   SDValue Increment;
5247   EVT AddrVT = Addr.getValueType();
5248   EVT MaskVT = Mask.getValueType();
5249   assert(DataVT.getVectorNumElements() == MaskVT.getVectorNumElements() &&
5250          "Incompatible types of Data and Mask");
5251   if (IsCompressedMemory) {
5252     // Incrementing the pointer according to number of '1's in the mask.
5253     EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
5254     SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
5255     if (MaskIntVT.getSizeInBits() < 32) {
5256       MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
5257       MaskIntVT = MVT::i32;
5258     }
5259 
5260     // Count '1's with POPCNT.
5261     Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
5262     Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
5263     // Scale is an element size in bytes.
5264     SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
5265                                     AddrVT);
5266     Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
5267   } else
5268     Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT);
5269 
5270   return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
5271 }
5272 
5273 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG,
5274                                        SDValue Idx,
5275                                        EVT VecVT,
5276                                        const SDLoc &dl) {
5277   if (isa<ConstantSDNode>(Idx))
5278     return Idx;
5279 
5280   EVT IdxVT = Idx.getValueType();
5281   unsigned NElts = VecVT.getVectorNumElements();
5282   if (isPowerOf2_32(NElts)) {
5283     APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(),
5284                                      Log2_32(NElts));
5285     return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
5286                        DAG.getConstant(Imm, dl, IdxVT));
5287   }
5288 
5289   return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
5290                      DAG.getConstant(NElts - 1, dl, IdxVT));
5291 }
5292 
5293 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG,
5294                                                 SDValue VecPtr, EVT VecVT,
5295                                                 SDValue Index) const {
5296   SDLoc dl(Index);
5297   // Make sure the index type is big enough to compute in.
5298   Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
5299 
5300   EVT EltVT = VecVT.getVectorElementType();
5301 
5302   // Calculate the element offset and add it to the pointer.
5303   unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
5304   assert(EltSize * 8 == EltVT.getSizeInBits() &&
5305          "Converting bits to bytes lost precision");
5306 
5307   Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl);
5308 
5309   EVT IdxVT = Index.getValueType();
5310 
5311   Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
5312                       DAG.getConstant(EltSize, dl, IdxVT));
5313   return DAG.getNode(ISD::ADD, dl, IdxVT, VecPtr, Index);
5314 }
5315 
5316 //===----------------------------------------------------------------------===//
5317 // Implementation of Emulated TLS Model
5318 //===----------------------------------------------------------------------===//
5319 
5320 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
5321                                                 SelectionDAG &DAG) const {
5322   // Access to address of TLS varialbe xyz is lowered to a function call:
5323   //   __emutls_get_address( address of global variable named "__emutls_v.xyz" )
5324   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5325   PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
5326   SDLoc dl(GA);
5327 
5328   ArgListTy Args;
5329   ArgListEntry Entry;
5330   std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
5331   Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
5332   StringRef EmuTlsVarName(NameString);
5333   GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
5334   assert(EmuTlsVar && "Cannot find EmuTlsVar ");
5335   Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
5336   Entry.Ty = VoidPtrType;
5337   Args.push_back(Entry);
5338 
5339   SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
5340 
5341   TargetLowering::CallLoweringInfo CLI(DAG);
5342   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
5343   CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
5344   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
5345 
5346   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5347   // At last for X86 targets, maybe good for other targets too?
5348   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5349   MFI.setAdjustsStack(true); // Is this only for X86 target?
5350   MFI.setHasCalls(true);
5351 
5352   assert((GA->getOffset() == 0) &&
5353          "Emulated TLS must have zero offset in GlobalAddressSDNode");
5354   return CallResult.first;
5355 }
5356 
5357 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
5358                                                 SelectionDAG &DAG) const {
5359   assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
5360   if (!isCtlzFast())
5361     return SDValue();
5362   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5363   SDLoc dl(Op);
5364   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
5365     if (C->isNullValue() && CC == ISD::SETEQ) {
5366       EVT VT = Op.getOperand(0).getValueType();
5367       SDValue Zext = Op.getOperand(0);
5368       if (VT.bitsLT(MVT::i32)) {
5369         VT = MVT::i32;
5370         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
5371       }
5372       unsigned Log2b = Log2_32(VT.getSizeInBits());
5373       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
5374       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
5375                                 DAG.getConstant(Log2b, dl, MVT::i32));
5376       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
5377     }
5378   }
5379   return SDValue();
5380 }
5381 
5382 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const {
5383   unsigned Opcode = Node->getOpcode();
5384   SDValue LHS = Node->getOperand(0);
5385   SDValue RHS = Node->getOperand(1);
5386   EVT VT = LHS.getValueType();
5387   SDLoc dl(Node);
5388 
5389   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
5390   assert(VT.isInteger() && "Expected operands to be integers");
5391 
5392   // usub.sat(a, b) -> umax(a, b) - b
5393   if (Opcode == ISD::USUBSAT && isOperationLegalOrCustom(ISD::UMAX, VT)) {
5394     SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
5395     return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
5396   }
5397 
5398   if (Opcode == ISD::UADDSAT && isOperationLegalOrCustom(ISD::UMIN, VT)) {
5399     SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
5400     SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
5401     return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
5402   }
5403 
5404   unsigned OverflowOp;
5405   switch (Opcode) {
5406   case ISD::SADDSAT:
5407     OverflowOp = ISD::SADDO;
5408     break;
5409   case ISD::UADDSAT:
5410     OverflowOp = ISD::UADDO;
5411     break;
5412   case ISD::SSUBSAT:
5413     OverflowOp = ISD::SSUBO;
5414     break;
5415   case ISD::USUBSAT:
5416     OverflowOp = ISD::USUBO;
5417     break;
5418   default:
5419     llvm_unreachable("Expected method to receive signed or unsigned saturation "
5420                      "addition or subtraction node.");
5421   }
5422 
5423   unsigned BitWidth = LHS.getScalarValueSizeInBits();
5424   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
5425   SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT),
5426                                LHS, RHS);
5427   SDValue SumDiff = Result.getValue(0);
5428   SDValue Overflow = Result.getValue(1);
5429   SDValue Zero = DAG.getConstant(0, dl, VT);
5430   SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
5431 
5432   if (Opcode == ISD::UADDSAT) {
5433     // Overflow ? 0xffff.... : (LHS + RHS)
5434     return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
5435   } else if (Opcode == ISD::USUBSAT) {
5436     // Overflow ? 0 : (LHS - RHS)
5437     return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
5438   } else {
5439     // SatMax -> Overflow && SumDiff < 0
5440     // SatMin -> Overflow && SumDiff >= 0
5441     APInt MinVal = APInt::getSignedMinValue(BitWidth);
5442     APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
5443     SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
5444     SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
5445     SDValue SumNeg = DAG.getSetCC(dl, BoolVT, SumDiff, Zero, ISD::SETLT);
5446     Result = DAG.getSelect(dl, VT, SumNeg, SatMax, SatMin);
5447     return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
5448   }
5449 }
5450 
5451 SDValue
5452 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const {
5453   assert((Node->getOpcode() == ISD::SMULFIX ||
5454           Node->getOpcode() == ISD::UMULFIX) &&
5455          "Expected opcode to be SMULFIX or UMULFIX.");
5456 
5457   SDLoc dl(Node);
5458   SDValue LHS = Node->getOperand(0);
5459   SDValue RHS = Node->getOperand(1);
5460   EVT VT = LHS.getValueType();
5461   unsigned Scale = Node->getConstantOperandVal(2);
5462 
5463   // [us]mul.fix(a, b, 0) -> mul(a, b)
5464   if (!Scale) {
5465     if (VT.isVector() && !isOperationLegalOrCustom(ISD::MUL, VT))
5466       return SDValue();
5467     return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
5468   }
5469 
5470   unsigned VTSize = VT.getScalarSizeInBits();
5471   bool Signed = Node->getOpcode() == ISD::SMULFIX;
5472 
5473   assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
5474          "Expected scale to be less than the number of bits if signed or at "
5475          "most the number of bits if unsigned.");
5476   assert(LHS.getValueType() == RHS.getValueType() &&
5477          "Expected both operands to be the same type");
5478 
5479   // Get the upper and lower bits of the result.
5480   SDValue Lo, Hi;
5481   unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
5482   unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
5483   if (isOperationLegalOrCustom(LoHiOp, VT)) {
5484     SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
5485     Lo = Result.getValue(0);
5486     Hi = Result.getValue(1);
5487   } else if (isOperationLegalOrCustom(HiOp, VT)) {
5488     Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
5489     Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
5490   } else if (VT.isVector()) {
5491     return SDValue();
5492   } else {
5493     report_fatal_error("Unable to expand fixed point multiplication.");
5494   }
5495 
5496   if (Scale == VTSize)
5497     // Result is just the top half since we'd be shifting by the width of the
5498     // operand.
5499     return Hi;
5500 
5501   // The result will need to be shifted right by the scale since both operands
5502   // are scaled. The result is given to us in 2 halves, so we only want part of
5503   // both in the result.
5504   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
5505   return DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
5506                      DAG.getConstant(Scale, dl, ShiftTy));
5507 }
5508 
5509 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result,
5510                                 SDValue &Overflow, SelectionDAG &DAG) const {
5511   SDLoc dl(Node);
5512   EVT VT = Node->getValueType(0);
5513   EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2);
5514   if (VT.isVector())
5515     WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT,
5516                               VT.getVectorNumElements());
5517 
5518   SDValue LHS = Node->getOperand(0);
5519   SDValue RHS = Node->getOperand(1);
5520   SDValue BottomHalf;
5521   SDValue TopHalf;
5522   static const unsigned Ops[2][3] =
5523       { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
5524         { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
5525   bool isSigned = Node->getOpcode() == ISD::SMULO;
5526   if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
5527     BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
5528     TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
5529   } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
5530     BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
5531                              RHS);
5532     TopHalf = BottomHalf.getValue(1);
5533   } else if (isTypeLegal(WideVT)) {
5534     LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
5535     RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
5536     SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
5537     BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
5538     SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl,
5539         getShiftAmountTy(WideVT, DAG.getDataLayout()));
5540     TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
5541                           DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
5542   } else {
5543     if (VT.isVector())
5544       return false;
5545 
5546     // We can fall back to a libcall with an illegal type for the MUL if we
5547     // have a libcall big enough.
5548     // Also, we can fall back to a division in some cases, but that's a big
5549     // performance hit in the general case.
5550     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
5551     if (WideVT == MVT::i16)
5552       LC = RTLIB::MUL_I16;
5553     else if (WideVT == MVT::i32)
5554       LC = RTLIB::MUL_I32;
5555     else if (WideVT == MVT::i64)
5556       LC = RTLIB::MUL_I64;
5557     else if (WideVT == MVT::i128)
5558       LC = RTLIB::MUL_I128;
5559     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
5560 
5561     SDValue HiLHS;
5562     SDValue HiRHS;
5563     if (isSigned) {
5564       // The high part is obtained by SRA'ing all but one of the bits of low
5565       // part.
5566       unsigned LoSize = VT.getSizeInBits();
5567       HiLHS =
5568           DAG.getNode(ISD::SRA, dl, VT, LHS,
5569                       DAG.getConstant(LoSize - 1, dl,
5570                                       getPointerTy(DAG.getDataLayout())));
5571       HiRHS =
5572           DAG.getNode(ISD::SRA, dl, VT, RHS,
5573                       DAG.getConstant(LoSize - 1, dl,
5574                                       getPointerTy(DAG.getDataLayout())));
5575     } else {
5576         HiLHS = DAG.getConstant(0, dl, VT);
5577         HiRHS = DAG.getConstant(0, dl, VT);
5578     }
5579 
5580     // Here we're passing the 2 arguments explicitly as 4 arguments that are
5581     // pre-lowered to the correct types. This all depends upon WideVT not
5582     // being a legal type for the architecture and thus has to be split to
5583     // two arguments.
5584     SDValue Ret;
5585     if (DAG.getDataLayout().isLittleEndian()) {
5586       // Halves of WideVT are packed into registers in different order
5587       // depending on platform endianness. This is usually handled by
5588       // the C calling convention, but we can't defer to it in
5589       // the legalizer.
5590       SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
5591       Ret = makeLibCall(DAG, LC, WideVT, Args, isSigned, dl,
5592           /* doesNotReturn */ false, /* isReturnValueUsed */ true,
5593           /* isPostTypeLegalization */ true).first;
5594     } else {
5595       SDValue Args[] = { HiLHS, LHS, HiRHS, RHS };
5596       Ret = makeLibCall(DAG, LC, WideVT, Args, isSigned, dl,
5597           /* doesNotReturn */ false, /* isReturnValueUsed */ true,
5598           /* isPostTypeLegalization */ true).first;
5599     }
5600     assert(Ret.getOpcode() == ISD::MERGE_VALUES &&
5601            "Ret value is a collection of constituent nodes holding result.");
5602     if (DAG.getDataLayout().isLittleEndian()) {
5603       // Same as above.
5604       BottomHalf = Ret.getOperand(0);
5605       TopHalf = Ret.getOperand(1);
5606     } else {
5607       BottomHalf = Ret.getOperand(1);
5608       TopHalf = Ret.getOperand(0);
5609     }
5610   }
5611 
5612   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
5613   Result = BottomHalf;
5614   if (isSigned) {
5615     SDValue ShiftAmt = DAG.getConstant(
5616         VT.getScalarSizeInBits() - 1, dl,
5617         getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout()));
5618     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
5619     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
5620   } else {
5621     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
5622                             DAG.getConstant(0, dl, VT), ISD::SETNE);
5623   }
5624 
5625   // Truncate the result if SetCC returns a larger type than needed.
5626   EVT RType = Node->getValueType(1);
5627   if (RType.getSizeInBits() < Overflow.getValueSizeInBits())
5628     Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
5629 
5630   assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
5631          "Unexpected result type for S/UMULO legalization");
5632   return true;
5633 }
5634