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