1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Target/TargetLowering.h"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/CodeGen/CallingConvLower.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineJumpTableInfo.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Target/TargetLoweringObjectFile.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/Target/TargetSubtargetInfo.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 because it doesn't affect the call sequence.
58   AttributeSet CallerAttrs = F->getAttributes();
59   if (AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex)
60       .removeAttribute(Attribute::NoAlias).hasAttributes())
61     return false;
62 
63   // It's not safe to eliminate the sign / zero extension of the return value.
64   if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
65       CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
66     return false;
67 
68   // Check if the only use is a function return node.
69   return isUsedByReturnOnly(Node, Chain);
70 }
71 
72 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI,
73     const uint32_t *CallerPreservedMask,
74     const SmallVectorImpl<CCValAssign> &ArgLocs,
75     const SmallVectorImpl<SDValue> &OutVals) const {
76   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
77     const CCValAssign &ArgLoc = ArgLocs[I];
78     if (!ArgLoc.isRegLoc())
79       continue;
80     unsigned Reg = ArgLoc.getLocReg();
81     // Only look at callee saved registers.
82     if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
83       continue;
84     // Check that we pass the value used for the caller.
85     // (We look for a CopyFromReg reading a virtual register that is used
86     //  for the function live-in value of register Reg)
87     SDValue Value = OutVals[I];
88     if (Value->getOpcode() != ISD::CopyFromReg)
89       return false;
90     unsigned ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
91     if (MRI.getLiveInPhysReg(ArgReg) != Reg)
92       return false;
93   }
94   return true;
95 }
96 
97 /// \brief Set CallLoweringInfo attribute flags based on a call instruction
98 /// and called function attributes.
99 void TargetLowering::ArgListEntry::setAttributes(ImmutableCallSite *CS,
100                                                  unsigned AttrIdx) {
101   isSExt     = CS->paramHasAttr(AttrIdx, Attribute::SExt);
102   isZExt     = CS->paramHasAttr(AttrIdx, Attribute::ZExt);
103   isInReg    = CS->paramHasAttr(AttrIdx, Attribute::InReg);
104   isSRet     = CS->paramHasAttr(AttrIdx, Attribute::StructRet);
105   isNest     = CS->paramHasAttr(AttrIdx, Attribute::Nest);
106   isByVal    = CS->paramHasAttr(AttrIdx, Attribute::ByVal);
107   isInAlloca = CS->paramHasAttr(AttrIdx, Attribute::InAlloca);
108   isReturned = CS->paramHasAttr(AttrIdx, Attribute::Returned);
109   isSwiftSelf = CS->paramHasAttr(AttrIdx, Attribute::SwiftSelf);
110   isSwiftError = CS->paramHasAttr(AttrIdx, Attribute::SwiftError);
111   Alignment  = CS->getParamAlignment(AttrIdx);
112 }
113 
114 /// Generate a libcall taking the given operands as arguments and returning a
115 /// result of type RetVT.
116 std::pair<SDValue, SDValue>
117 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
118                             ArrayRef<SDValue> Ops, bool isSigned,
119                             const SDLoc &dl, bool doesNotReturn,
120                             bool isReturnValueUsed) const {
121   TargetLowering::ArgListTy Args;
122   Args.reserve(Ops.size());
123 
124   TargetLowering::ArgListEntry Entry;
125   for (SDValue Op : Ops) {
126     Entry.Node = Op;
127     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
128     Entry.isSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
129     Entry.isZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
130     Args.push_back(Entry);
131   }
132 
133   if (LC == RTLIB::UNKNOWN_LIBCALL)
134     report_fatal_error("Unsupported library call operation!");
135   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
136                                          getPointerTy(DAG.getDataLayout()));
137 
138   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
139   TargetLowering::CallLoweringInfo CLI(DAG);
140   bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned);
141   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
142     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
143     .setNoReturn(doesNotReturn).setDiscardResult(!isReturnValueUsed)
144     .setSExtResult(signExtend).setZExtResult(!signExtend);
145   return LowerCallTo(CLI);
146 }
147 
148 /// Soften the operands of a comparison. This code is shared among BR_CC,
149 /// SELECT_CC, and SETCC handlers.
150 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
151                                          SDValue &NewLHS, SDValue &NewRHS,
152                                          ISD::CondCode &CCCode,
153                                          const SDLoc &dl) const {
154   assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
155          && "Unsupported setcc type!");
156 
157   // Expand into one or more soft-fp libcall(s).
158   RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
159   bool ShouldInvertCC = false;
160   switch (CCCode) {
161   case ISD::SETEQ:
162   case ISD::SETOEQ:
163     LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
164           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
165           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
166     break;
167   case ISD::SETNE:
168   case ISD::SETUNE:
169     LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
170           (VT == MVT::f64) ? RTLIB::UNE_F64 :
171           (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
172     break;
173   case ISD::SETGE:
174   case ISD::SETOGE:
175     LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
176           (VT == MVT::f64) ? RTLIB::OGE_F64 :
177           (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
178     break;
179   case ISD::SETLT:
180   case ISD::SETOLT:
181     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
182           (VT == MVT::f64) ? RTLIB::OLT_F64 :
183           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
184     break;
185   case ISD::SETLE:
186   case ISD::SETOLE:
187     LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
188           (VT == MVT::f64) ? RTLIB::OLE_F64 :
189           (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
190     break;
191   case ISD::SETGT:
192   case ISD::SETOGT:
193     LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
194           (VT == MVT::f64) ? RTLIB::OGT_F64 :
195           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
196     break;
197   case ISD::SETUO:
198     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
199           (VT == MVT::f64) ? RTLIB::UO_F64 :
200           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
201     break;
202   case ISD::SETO:
203     LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
204           (VT == MVT::f64) ? RTLIB::O_F64 :
205           (VT == MVT::f128) ? RTLIB::O_F128 : RTLIB::O_PPCF128;
206     break;
207   case ISD::SETONE:
208     // SETONE = SETOLT | SETOGT
209     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
210           (VT == MVT::f64) ? RTLIB::OLT_F64 :
211           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
212     LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
213           (VT == MVT::f64) ? RTLIB::OGT_F64 :
214           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
215     break;
216   case ISD::SETUEQ:
217     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
218           (VT == MVT::f64) ? RTLIB::UO_F64 :
219           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
220     LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
221           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
222           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
223     break;
224   default:
225     // Invert CC for unordered comparisons
226     ShouldInvertCC = true;
227     switch (CCCode) {
228     case ISD::SETULT:
229       LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
230             (VT == MVT::f64) ? RTLIB::OGE_F64 :
231             (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
232       break;
233     case ISD::SETULE:
234       LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
235             (VT == MVT::f64) ? RTLIB::OGT_F64 :
236             (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
237       break;
238     case ISD::SETUGT:
239       LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
240             (VT == MVT::f64) ? RTLIB::OLE_F64 :
241             (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
242       break;
243     case ISD::SETUGE:
244       LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
245             (VT == MVT::f64) ? RTLIB::OLT_F64 :
246             (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
247       break;
248     default: llvm_unreachable("Do not know how to soften this setcc!");
249     }
250   }
251 
252   // Use the target specific return value for comparions lib calls.
253   EVT RetVT = getCmpLibcallReturnType();
254   SDValue Ops[2] = {NewLHS, NewRHS};
255   NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, false /*sign irrelevant*/,
256                        dl).first;
257   NewRHS = DAG.getConstant(0, dl, RetVT);
258 
259   CCCode = getCmpLibcallCC(LC1);
260   if (ShouldInvertCC)
261     CCCode = getSetCCInverse(CCCode, /*isInteger=*/true);
262 
263   if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
264     SDValue Tmp = DAG.getNode(
265         ISD::SETCC, dl,
266         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
267         NewLHS, NewRHS, DAG.getCondCode(CCCode));
268     NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, false/*sign irrelevant*/,
269                          dl).first;
270     NewLHS = DAG.getNode(
271         ISD::SETCC, dl,
272         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
273         NewLHS, NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
274     NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
275     NewRHS = SDValue();
276   }
277 }
278 
279 /// Return the entry encoding for a jump table in the current function. The
280 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
281 unsigned TargetLowering::getJumpTableEncoding() const {
282   // In non-pic modes, just use the address of a block.
283   if (!isPositionIndependent())
284     return MachineJumpTableInfo::EK_BlockAddress;
285 
286   // In PIC mode, if the target supports a GPRel32 directive, use it.
287   if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
288     return MachineJumpTableInfo::EK_GPRel32BlockAddress;
289 
290   // Otherwise, use a label difference.
291   return MachineJumpTableInfo::EK_LabelDifference32;
292 }
293 
294 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
295                                                  SelectionDAG &DAG) const {
296   // If our PIC model is GP relative, use the global offset table as the base.
297   unsigned JTEncoding = getJumpTableEncoding();
298 
299   if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
300       (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
301     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
302 
303   return Table;
304 }
305 
306 /// This returns the relocation base for the given PIC jumptable, the same as
307 /// getPICJumpTableRelocBase, but as an MCExpr.
308 const MCExpr *
309 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
310                                              unsigned JTI,MCContext &Ctx) const{
311   // The normal PIC reloc base is the label at the start of the jump table.
312   return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
313 }
314 
315 bool
316 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
317   const TargetMachine &TM = getTargetMachine();
318   const GlobalValue *GV = GA->getGlobal();
319 
320   // If the address is not even local to this DSO we will have to load it from
321   // a got and then add the offset.
322   if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
323     return false;
324 
325   // If the code is position independent we will have to add a base register.
326   if (isPositionIndependent())
327     return false;
328 
329   // Otherwise we can do it.
330   return true;
331 }
332 
333 //===----------------------------------------------------------------------===//
334 //  Optimization Methods
335 //===----------------------------------------------------------------------===//
336 
337 /// If the specified instruction has a constant integer operand and there are
338 /// bits set in that constant that are not demanded, then clear those bits and
339 /// return true.
340 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(
341     SDValue Op, const APInt &Demanded) {
342   SDLoc DL(Op);
343   unsigned Opcode = Op.getOpcode();
344 
345   // FIXME: ISD::SELECT, ISD::SELECT_CC
346   switch (Opcode) {
347   default:
348     break;
349   case ISD::XOR:
350   case ISD::AND:
351   case ISD::OR: {
352     auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
353     if (!Op1C)
354       return false;
355 
356     // If this is a 'not' op, don't touch it because that's a canonical form.
357     const APInt &C = Op1C->getAPIntValue();
358     if (Opcode == ISD::XOR && (C | ~Demanded).isAllOnesValue())
359       return false;
360 
361     if (C.intersects(~Demanded)) {
362       EVT VT = Op.getValueType();
363       SDValue NewC = DAG.getConstant(Demanded & C, DL, VT);
364       SDValue NewOp = DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC);
365       return CombineTo(Op, NewOp);
366     }
367 
368     break;
369   }
370   }
371 
372   return false;
373 }
374 
375 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
376 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
377 /// generalized for targets with other types of implicit widening casts.
378 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op,
379                                                          unsigned BitWidth,
380                                                          const APInt &Demanded,
381                                                          const SDLoc &dl) {
382   assert(Op.getNumOperands() == 2 &&
383          "ShrinkDemandedOp only supports binary operators!");
384   assert(Op.getNode()->getNumValues() == 1 &&
385          "ShrinkDemandedOp only supports nodes with one result!");
386 
387   // Early return, as this function cannot handle vector types.
388   if (Op.getValueType().isVector())
389     return false;
390 
391   // Don't do this if the node has another user, which may require the
392   // full value.
393   if (!Op.getNode()->hasOneUse())
394     return false;
395 
396   // Search for the smallest integer type with free casts to and from
397   // Op's type. For expedience, just check power-of-2 integer types.
398   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
399   unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros();
400   unsigned SmallVTBits = DemandedSize;
401   if (!isPowerOf2_32(SmallVTBits))
402     SmallVTBits = NextPowerOf2(SmallVTBits);
403   for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
404     EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
405     if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
406         TLI.isZExtFree(SmallVT, Op.getValueType())) {
407       // We found a type with free casts.
408       SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
409                               DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
410                                           Op.getNode()->getOperand(0)),
411                               DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
412                                           Op.getNode()->getOperand(1)));
413       bool NeedZext = DemandedSize > SmallVTBits;
414       SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND,
415                               dl, Op.getValueType(), X);
416       return CombineTo(Op, Z);
417     }
418   }
419   return false;
420 }
421 
422 bool
423 TargetLowering::TargetLoweringOpt::SimplifyDemandedBits(SDNode *User,
424                                                         unsigned OpIdx,
425                                                         const APInt &Demanded,
426                                                         DAGCombinerInfo &DCI) {
427   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
428   SDValue Op = User->getOperand(OpIdx);
429   APInt KnownZero, KnownOne;
430 
431   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne,
432                                 *this, 0, true))
433     return false;
434 
435 
436   // Old will not always be the same as Op.  For example:
437   //
438   // Demanded = 0xffffff
439   // Op = i64 truncate (i32 and x, 0xffffff)
440   // In this case simplify demand bits will want to replace the 'and' node
441   // with the value 'x', which will give us:
442   // Old = i32 and x, 0xffffff
443   // New = x
444   if (Old.hasOneUse()) {
445     // For the one use case, we just commit the change.
446     DCI.CommitTargetLoweringOpt(*this);
447     return true;
448   }
449 
450   // If Old has more than one use then it must be Op, because the
451   // AssumeSingleUse flag is not propogated to recursive calls of
452   // SimplifyDemanded bits, so the only node with multiple use that
453   // it will attempt to combine will be opt.
454   assert(Old == Op);
455 
456   SmallVector <SDValue, 4> NewOps;
457   for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
458     if (i == OpIdx) {
459       NewOps.push_back(New);
460       continue;
461     }
462     NewOps.push_back(User->getOperand(i));
463   }
464   DAG.UpdateNodeOperands(User, NewOps);
465   // Op has less users now, so we may be able to perform additional combines
466   // with it.
467   DCI.AddToWorklist(Op.getNode());
468   // User's operands have been updated, so we may be able to do new combines
469   // with it.
470   DCI.AddToWorklist(User);
471   return true;
472 }
473 
474 bool TargetLowering::SimplifyDemandedBits(SDValue Op, APInt &DemandedMask,
475                                           DAGCombinerInfo &DCI) const {
476 
477   SelectionDAG &DAG = DCI.DAG;
478   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
479                         !DCI.isBeforeLegalizeOps());
480   APInt KnownZero, KnownOne;
481 
482   bool Simplified = SimplifyDemandedBits(Op, DemandedMask, KnownZero, KnownOne,
483                                          TLO);
484   if (Simplified)
485     DCI.CommitTargetLoweringOpt(TLO);
486   return Simplified;
487 }
488 
489 /// Look at Op. At this point, we know that only the DemandedMask bits of the
490 /// result of Op are ever used downstream. If we can use this information to
491 /// simplify Op, create a new simplified DAG node and return true, returning the
492 /// original and new nodes in Old and New. Otherwise, analyze the expression and
493 /// return a mask of KnownOne and KnownZero bits for the expression (used to
494 /// simplify the caller).  The KnownZero/One bits may only be accurate for those
495 /// bits in the DemandedMask.
496 bool TargetLowering::SimplifyDemandedBits(SDValue Op,
497                                           const APInt &DemandedMask,
498                                           APInt &KnownZero,
499                                           APInt &KnownOne,
500                                           TargetLoweringOpt &TLO,
501                                           unsigned Depth,
502                                           bool AssumeSingleUse) const {
503   unsigned BitWidth = DemandedMask.getBitWidth();
504   assert(Op.getScalarValueSizeInBits() == BitWidth &&
505          "Mask size mismatches value type size!");
506   APInt NewMask = DemandedMask;
507   SDLoc dl(Op);
508   auto &DL = TLO.DAG.getDataLayout();
509 
510   // Don't know anything.
511   KnownZero = KnownOne = APInt(BitWidth, 0);
512 
513   // Other users may use these bits.
514   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) {
515     if (Depth != 0) {
516       // If not at the root, Just compute the KnownZero/KnownOne bits to
517       // simplify things downstream.
518       TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
519       return false;
520     }
521     // If this is the root being simplified, allow it to have multiple uses,
522     // just set the NewMask to all bits.
523     NewMask = APInt::getAllOnesValue(BitWidth);
524   } else if (DemandedMask == 0) {
525     // Not demanding any bits from Op.
526     if (!Op.isUndef())
527       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
528     return false;
529   } else if (Depth == 6) {        // Limit search depth.
530     return false;
531   }
532 
533   APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
534   switch (Op.getOpcode()) {
535   case ISD::Constant:
536     // We know all of the bits for a constant!
537     KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
538     KnownZero = ~KnownOne;
539     return false;   // Don't fall through, will infinitely loop.
540   case ISD::BUILD_VECTOR:
541     // Collect the known bits that are shared by every constant vector element.
542     KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
543     for (SDValue SrcOp : Op->ops()) {
544       if (!isa<ConstantSDNode>(SrcOp)) {
545         // We can only handle all constant values - bail out with no known bits.
546         KnownZero = KnownOne = APInt(BitWidth, 0);
547         return false;
548       }
549       KnownOne2 = cast<ConstantSDNode>(SrcOp)->getAPIntValue();
550       KnownZero2 = ~KnownOne2;
551 
552       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
553       if (KnownOne2.getBitWidth() != BitWidth) {
554         assert(KnownOne2.getBitWidth() > BitWidth &&
555                KnownZero2.getBitWidth() > BitWidth &&
556                "Expected BUILD_VECTOR implicit truncation");
557         KnownOne2 = KnownOne2.trunc(BitWidth);
558         KnownZero2 = KnownZero2.trunc(BitWidth);
559       }
560 
561       // Known bits are the values that are shared by every element.
562       // TODO: support per-element known bits.
563       KnownOne &= KnownOne2;
564       KnownZero &= KnownZero2;
565     }
566     return false;   // Don't fall through, will infinitely loop.
567   case ISD::AND:
568     // If the RHS is a constant, check to see if the LHS would be zero without
569     // using the bits from the RHS.  Below, we use knowledge about the RHS to
570     // simplify the LHS, here we're using information from the LHS to simplify
571     // the RHS.
572     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
573       SDValue Op0 = Op.getOperand(0);
574       APInt LHSZero, LHSOne;
575       // Do not increment Depth here; that can cause an infinite loop.
576       TLO.DAG.computeKnownBits(Op0, LHSZero, LHSOne, Depth);
577       // If the LHS already has zeros where RHSC does, this and is dead.
578       if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
579         return TLO.CombineTo(Op, Op0);
580 
581       // If any of the set bits in the RHS are known zero on the LHS, shrink
582       // the constant.
583       if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
584         return true;
585 
586       // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
587       // constant, but if this 'and' is only clearing bits that were just set by
588       // the xor, then this 'and' can be eliminated by shrinking the mask of
589       // the xor. For example, for a 32-bit X:
590       // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
591       if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
592           LHSOne == ~RHSC->getAPIntValue()) {
593         SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, Op.getValueType(),
594                                       Op0.getOperand(0), Op.getOperand(1));
595         return TLO.CombineTo(Op, Xor);
596       }
597     }
598 
599     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
600                              KnownOne, TLO, Depth+1))
601       return true;
602     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
603     if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
604                              KnownZero2, KnownOne2, TLO, Depth+1))
605       return true;
606     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
607 
608     // If all of the demanded bits are known one on one side, return the other.
609     // These bits cannot contribute to the result of the 'and'.
610     if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
611       return TLO.CombineTo(Op, Op.getOperand(0));
612     if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
613       return TLO.CombineTo(Op, Op.getOperand(1));
614     // If all of the demanded bits in the inputs are known zeros, return zero.
615     if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
616       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, Op.getValueType()));
617     // If the RHS is a constant, see if we can simplify it.
618     if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
619       return true;
620     // If the operation can be done in a smaller type, do so.
621     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
622       return true;
623 
624     // Output known-1 bits are only known if set in both the LHS & RHS.
625     KnownOne &= KnownOne2;
626     // Output known-0 are known to be clear if zero in either the LHS | RHS.
627     KnownZero |= KnownZero2;
628     break;
629   case ISD::OR:
630     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
631                              KnownOne, TLO, Depth+1))
632       return true;
633     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
634     if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
635                              KnownZero2, KnownOne2, TLO, Depth+1))
636       return true;
637     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
638 
639     // If all of the demanded bits are known zero on one side, return the other.
640     // These bits cannot contribute to the result of the 'or'.
641     if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
642       return TLO.CombineTo(Op, Op.getOperand(0));
643     if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
644       return TLO.CombineTo(Op, Op.getOperand(1));
645     // If all of the potentially set bits on one side are known to be set on
646     // the other side, just use the 'other' side.
647     if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
648       return TLO.CombineTo(Op, Op.getOperand(0));
649     if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
650       return TLO.CombineTo(Op, Op.getOperand(1));
651     // If the RHS is a constant, see if we can simplify it.
652     if (TLO.ShrinkDemandedConstant(Op, NewMask))
653       return true;
654     // If the operation can be done in a smaller type, do so.
655     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
656       return true;
657 
658     // Output known-0 bits are only known if clear in both the LHS & RHS.
659     KnownZero &= KnownZero2;
660     // Output known-1 are known to be set if set in either the LHS | RHS.
661     KnownOne |= KnownOne2;
662     break;
663   case ISD::XOR:
664     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
665                              KnownOne, TLO, Depth+1))
666       return true;
667     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
668     if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
669                              KnownOne2, TLO, Depth+1))
670       return true;
671     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
672 
673     // If all of the demanded bits are known zero on one side, return the other.
674     // These bits cannot contribute to the result of the 'xor'.
675     if ((KnownZero & NewMask) == NewMask)
676       return TLO.CombineTo(Op, Op.getOperand(0));
677     if ((KnownZero2 & NewMask) == NewMask)
678       return TLO.CombineTo(Op, Op.getOperand(1));
679     // If the operation can be done in a smaller type, do so.
680     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
681       return true;
682 
683     // If all of the unknown bits are known to be zero on one side or the other
684     // (but not both) turn this into an *inclusive* or.
685     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
686     if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
687       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
688                                                Op.getOperand(0),
689                                                Op.getOperand(1)));
690 
691     // Output known-0 bits are known if clear or set in both the LHS & RHS.
692     KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
693     // Output known-1 are known to be set if set in only one of the LHS, RHS.
694     KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
695 
696     // If all of the demanded bits on one side are known, and all of the set
697     // bits on that side are also known to be set on the other side, turn this
698     // into an AND, as we know the bits will be cleared.
699     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
700     // NB: it is okay if more bits are known than are requested
701     if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side
702       if (KnownOne == KnownOne2) { // set bits are the same on both sides
703         EVT VT = Op.getValueType();
704         SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, dl, VT);
705         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
706                                                  Op.getOperand(0), ANDC));
707       }
708     }
709 
710     // If the RHS is a constant, see if we can simplify it.
711     // for XOR, we prefer to force bits to 1 if they will make a -1.
712     // If we can't force bits, try to shrink the constant.
713     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
714       APInt Expanded = C->getAPIntValue() | (~NewMask);
715       // If we can expand it to have all bits set, do it.
716       if (Expanded.isAllOnesValue()) {
717         if (Expanded != C->getAPIntValue()) {
718           EVT VT = Op.getValueType();
719           SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
720                                         TLO.DAG.getConstant(Expanded, dl, VT));
721           return TLO.CombineTo(Op, New);
722         }
723         // If it already has all the bits set, nothing to change
724         // but don't shrink either!
725       } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
726         return true;
727       }
728     }
729 
730     KnownZero = KnownZeroOut;
731     KnownOne  = KnownOneOut;
732     break;
733   case ISD::SELECT:
734     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
735                              KnownOne, TLO, Depth+1))
736       return true;
737     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
738                              KnownOne2, TLO, Depth+1))
739       return true;
740     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
741     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
742 
743     // If the operands are constants, see if we can simplify them.
744     if (TLO.ShrinkDemandedConstant(Op, NewMask))
745       return true;
746 
747     // Only known if known in both the LHS and RHS.
748     KnownOne &= KnownOne2;
749     KnownZero &= KnownZero2;
750     break;
751   case ISD::SELECT_CC:
752     if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
753                              KnownOne, TLO, Depth+1))
754       return true;
755     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
756                              KnownOne2, TLO, Depth+1))
757       return true;
758     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
759     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
760 
761     // If the operands are constants, see if we can simplify them.
762     if (TLO.ShrinkDemandedConstant(Op, NewMask))
763       return true;
764 
765     // Only known if known in both the LHS and RHS.
766     KnownOne &= KnownOne2;
767     KnownZero &= KnownZero2;
768     break;
769   case ISD::SETCC: {
770     SDValue Op0 = Op.getOperand(0);
771     SDValue Op1 = Op.getOperand(1);
772     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
773     // If (1) we only need the sign-bit, (2) the setcc operands are the same
774     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
775     // -1, we may be able to bypass the setcc.
776     if (NewMask.isSignBit() && Op0.getScalarValueSizeInBits() == BitWidth &&
777         getBooleanContents(Op.getValueType()) ==
778             BooleanContent::ZeroOrNegativeOneBooleanContent) {
779       // If we're testing X < 0, then this compare isn't needed - just use X!
780       // FIXME: We're limiting to integer types here, but this should also work
781       // if we don't care about FP signed-zero. The use of SETLT with FP means
782       // that we don't care about NaNs.
783       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
784           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
785         return TLO.CombineTo(Op, Op0);
786 
787       // TODO: Should we check for other forms of sign-bit comparisons?
788       // Examples: X <= -1, X >= 0
789     }
790     break;
791   }
792   case ISD::SHL:
793     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
794       unsigned ShAmt = SA->getZExtValue();
795       SDValue InOp = Op.getOperand(0);
796 
797       // If the shift count is an invalid immediate, don't do anything.
798       if (ShAmt >= BitWidth)
799         break;
800 
801       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
802       // single shift.  We can do this if the bottom bits (which are shifted
803       // out) are never demanded.
804       if (InOp.getOpcode() == ISD::SRL &&
805           isa<ConstantSDNode>(InOp.getOperand(1))) {
806         if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
807           unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
808           unsigned Opc = ISD::SHL;
809           int Diff = ShAmt-C1;
810           if (Diff < 0) {
811             Diff = -Diff;
812             Opc = ISD::SRL;
813           }
814 
815           SDValue NewSA =
816             TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
817           EVT VT = Op.getValueType();
818           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
819                                                    InOp.getOperand(0), NewSA));
820         }
821       }
822 
823       if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt),
824                                KnownZero, KnownOne, TLO, Depth+1))
825         return true;
826 
827       // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
828       // are not demanded. This will likely allow the anyext to be folded away.
829       if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
830         SDValue InnerOp = InOp.getNode()->getOperand(0);
831         EVT InnerVT = InnerOp.getValueType();
832         unsigned InnerBits = InnerVT.getSizeInBits();
833         if (ShAmt < InnerBits && NewMask.lshr(InnerBits) == 0 &&
834             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
835           EVT ShTy = getShiftAmountTy(InnerVT, DL);
836           if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
837             ShTy = InnerVT;
838           SDValue NarrowShl =
839             TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
840                             TLO.DAG.getConstant(ShAmt, dl, ShTy));
841           return
842             TLO.CombineTo(Op,
843                           TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(),
844                                           NarrowShl));
845         }
846         // Repeat the SHL optimization above in cases where an extension
847         // intervenes: (shl (anyext (shr x, c1)), c2) to
848         // (shl (anyext x), c2-c1).  This requires that the bottom c1 bits
849         // aren't demanded (as above) and that the shifted upper c1 bits of
850         // x aren't demanded.
851         if (InOp.hasOneUse() &&
852             InnerOp.getOpcode() == ISD::SRL &&
853             InnerOp.hasOneUse() &&
854             isa<ConstantSDNode>(InnerOp.getOperand(1))) {
855           uint64_t InnerShAmt = cast<ConstantSDNode>(InnerOp.getOperand(1))
856             ->getZExtValue();
857           if (InnerShAmt < ShAmt &&
858               InnerShAmt < InnerBits &&
859               NewMask.lshr(InnerBits - InnerShAmt + ShAmt) == 0 &&
860               NewMask.trunc(ShAmt) == 0) {
861             SDValue NewSA =
862               TLO.DAG.getConstant(ShAmt - InnerShAmt, dl,
863                                   Op.getOperand(1).getValueType());
864             EVT VT = Op.getValueType();
865             SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
866                                              InnerOp.getOperand(0));
867             return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT,
868                                                      NewExt, NewSA));
869           }
870         }
871       }
872 
873       KnownZero <<= SA->getZExtValue();
874       KnownOne  <<= SA->getZExtValue();
875       // low bits known zero.
876       KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue());
877     }
878     break;
879   case ISD::SRL:
880     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
881       EVT VT = Op.getValueType();
882       unsigned ShAmt = SA->getZExtValue();
883       unsigned VTSize = VT.getSizeInBits();
884       SDValue InOp = Op.getOperand(0);
885 
886       // If the shift count is an invalid immediate, don't do anything.
887       if (ShAmt >= BitWidth)
888         break;
889 
890       APInt InDemandedMask = (NewMask << ShAmt);
891 
892       // If the shift is exact, then it does demand the low bits (and knows that
893       // they are zero).
894       if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
895         InDemandedMask |= APInt::getLowBitsSet(BitWidth, ShAmt);
896 
897       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
898       // single shift.  We can do this if the top bits (which are shifted out)
899       // are never demanded.
900       if (InOp.getOpcode() == ISD::SHL &&
901           isa<ConstantSDNode>(InOp.getOperand(1))) {
902         if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
903           unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
904           unsigned Opc = ISD::SRL;
905           int Diff = ShAmt-C1;
906           if (Diff < 0) {
907             Diff = -Diff;
908             Opc = ISD::SHL;
909           }
910 
911           SDValue NewSA =
912             TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
913           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
914                                                    InOp.getOperand(0), NewSA));
915         }
916       }
917 
918       // Compute the new bits that are at the top now.
919       if (SimplifyDemandedBits(InOp, InDemandedMask,
920                                KnownZero, KnownOne, TLO, Depth+1))
921         return true;
922       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
923       KnownZero = KnownZero.lshr(ShAmt);
924       KnownOne  = KnownOne.lshr(ShAmt);
925 
926       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
927       KnownZero |= HighBits;  // High bits known zero.
928     }
929     break;
930   case ISD::SRA:
931     // If this is an arithmetic shift right and only the low-bit is set, we can
932     // always convert this into a logical shr, even if the shift amount is
933     // variable.  The low bit of the shift cannot be an input sign bit unless
934     // the shift amount is >= the size of the datatype, which is undefined.
935     if (NewMask == 1)
936       return TLO.CombineTo(Op,
937                            TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
938                                            Op.getOperand(0), Op.getOperand(1)));
939 
940     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
941       EVT VT = Op.getValueType();
942       unsigned ShAmt = SA->getZExtValue();
943 
944       // If the shift count is an invalid immediate, don't do anything.
945       if (ShAmt >= BitWidth)
946         break;
947 
948       APInt InDemandedMask = (NewMask << ShAmt);
949 
950       // If the shift is exact, then it does demand the low bits (and knows that
951       // they are zero).
952       if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
953         InDemandedMask |= APInt::getLowBitsSet(BitWidth, ShAmt);
954 
955       // If any of the demanded bits are produced by the sign extension, we also
956       // demand the input sign bit.
957       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
958       if (HighBits.intersects(NewMask))
959         InDemandedMask |= APInt::getSignBit(VT.getScalarSizeInBits());
960 
961       if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
962                                KnownZero, KnownOne, TLO, Depth+1))
963         return true;
964       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
965       KnownZero = KnownZero.lshr(ShAmt);
966       KnownOne  = KnownOne.lshr(ShAmt);
967 
968       // Handle the sign bit, adjusted to where it is now in the mask.
969       APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
970 
971       // If the input sign bit is known to be zero, or if none of the top bits
972       // are demanded, turn this into an unsigned shift right.
973       if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) {
974         SDNodeFlags Flags;
975         Flags.setExact(cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact());
976         return TLO.CombineTo(Op,
977                              TLO.DAG.getNode(ISD::SRL, dl, VT, Op.getOperand(0),
978                                              Op.getOperand(1), &Flags));
979       }
980 
981       int Log2 = NewMask.exactLogBase2();
982       if (Log2 >= 0) {
983         // The bit must come from the sign.
984         SDValue NewSA =
985           TLO.DAG.getConstant(BitWidth - 1 - Log2, dl,
986                               Op.getOperand(1).getValueType());
987         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
988                                                  Op.getOperand(0), NewSA));
989       }
990 
991       if (KnownOne.intersects(SignBit))
992         // New bits are known one.
993         KnownOne |= HighBits;
994     }
995     break;
996   case ISD::SIGN_EXTEND_INREG: {
997     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
998 
999     APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1);
1000     // If we only care about the highest bit, don't bother shifting right.
1001     if (MsbMask == NewMask) {
1002       unsigned ShAmt = ExVT.getScalarSizeInBits();
1003       SDValue InOp = Op.getOperand(0);
1004       unsigned VTBits = Op->getValueType(0).getScalarSizeInBits();
1005       bool AlreadySignExtended =
1006         TLO.DAG.ComputeNumSignBits(InOp) >= VTBits-ShAmt+1;
1007       // However if the input is already sign extended we expect the sign
1008       // extension to be dropped altogether later and do not simplify.
1009       if (!AlreadySignExtended) {
1010         // Compute the correct shift amount type, which must be getShiftAmountTy
1011         // for scalar types after legalization.
1012         EVT ShiftAmtTy = Op.getValueType();
1013         if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
1014           ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL);
1015 
1016         SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, dl,
1017                                                ShiftAmtTy);
1018         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1019                                                  Op.getValueType(), InOp,
1020                                                  ShiftAmt));
1021       }
1022     }
1023 
1024     // Sign extension.  Compute the demanded bits in the result that are not
1025     // present in the input.
1026     APInt NewBits =
1027       APInt::getHighBitsSet(BitWidth,
1028                             BitWidth - ExVT.getScalarSizeInBits());
1029 
1030     // If none of the extended bits are demanded, eliminate the sextinreg.
1031     if ((NewBits & NewMask) == 0)
1032       return TLO.CombineTo(Op, Op.getOperand(0));
1033 
1034     APInt InSignBit =
1035       APInt::getSignBit(ExVT.getScalarSizeInBits()).zext(BitWidth);
1036     APInt InputDemandedBits =
1037       APInt::getLowBitsSet(BitWidth,
1038                            ExVT.getScalarSizeInBits()) &
1039       NewMask;
1040 
1041     // Since the sign extended bits are demanded, we know that the sign
1042     // bit is demanded.
1043     InputDemandedBits |= InSignBit;
1044 
1045     if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
1046                              KnownZero, KnownOne, TLO, Depth+1))
1047       return true;
1048     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1049 
1050     // If the sign bit of the input is known set or clear, then we know the
1051     // top bits of the result.
1052 
1053     // If the input sign bit is known zero, convert this into a zero extension.
1054     if (KnownZero.intersects(InSignBit))
1055       return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(
1056                                    Op.getOperand(0), dl, ExVT.getScalarType()));
1057 
1058     if (KnownOne.intersects(InSignBit)) {    // Input sign bit known set
1059       KnownOne |= NewBits;
1060       KnownZero &= ~NewBits;
1061     } else {                       // Input sign bit unknown
1062       KnownZero &= ~NewBits;
1063       KnownOne &= ~NewBits;
1064     }
1065     break;
1066   }
1067   case ISD::BUILD_PAIR: {
1068     EVT HalfVT = Op.getOperand(0).getValueType();
1069     unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
1070 
1071     APInt MaskLo = NewMask.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
1072     APInt MaskHi = NewMask.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
1073 
1074     APInt KnownZeroLo, KnownOneLo;
1075     APInt KnownZeroHi, KnownOneHi;
1076 
1077     if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownZeroLo,
1078                              KnownOneLo, TLO, Depth + 1))
1079       return true;
1080 
1081     if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownZeroHi,
1082                              KnownOneHi, TLO, Depth + 1))
1083       return true;
1084 
1085     KnownZero = KnownZeroLo.zext(BitWidth) |
1086                 KnownZeroHi.zext(BitWidth).shl(HalfBitWidth);
1087 
1088     KnownOne = KnownOneLo.zext(BitWidth) |
1089                KnownOneHi.zext(BitWidth).shl(HalfBitWidth);
1090     break;
1091   }
1092   case ISD::ZERO_EXTEND: {
1093     unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
1094     APInt InMask = NewMask.trunc(OperandBitWidth);
1095 
1096     // If none of the top bits are demanded, convert this into an any_extend.
1097     APInt NewBits =
1098       APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
1099     if (!NewBits.intersects(NewMask))
1100       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
1101                                                Op.getValueType(),
1102                                                Op.getOperand(0)));
1103 
1104     if (SimplifyDemandedBits(Op.getOperand(0), InMask,
1105                              KnownZero, KnownOne, TLO, Depth+1))
1106       return true;
1107     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1108     KnownZero = KnownZero.zext(BitWidth);
1109     KnownOne = KnownOne.zext(BitWidth);
1110     KnownZero |= NewBits;
1111     break;
1112   }
1113   case ISD::SIGN_EXTEND: {
1114     EVT InVT = Op.getOperand(0).getValueType();
1115     unsigned InBits = InVT.getScalarSizeInBits();
1116     APInt InMask    = APInt::getLowBitsSet(BitWidth, InBits);
1117     APInt InSignBit = APInt::getOneBitSet(BitWidth, InBits - 1);
1118     APInt NewBits   = ~InMask & NewMask;
1119 
1120     // If none of the top bits are demanded, convert this into an any_extend.
1121     if (NewBits == 0)
1122       return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
1123                                               Op.getValueType(),
1124                                               Op.getOperand(0)));
1125 
1126     // Since some of the sign extended bits are demanded, we know that the sign
1127     // bit is demanded.
1128     APInt InDemandedBits = InMask & NewMask;
1129     InDemandedBits |= InSignBit;
1130     InDemandedBits = InDemandedBits.trunc(InBits);
1131 
1132     if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
1133                              KnownOne, TLO, Depth+1))
1134       return true;
1135     KnownZero = KnownZero.zext(BitWidth);
1136     KnownOne = KnownOne.zext(BitWidth);
1137 
1138     // If the sign bit is known zero, convert this to a zero extend.
1139     if (KnownZero.intersects(InSignBit))
1140       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
1141                                                Op.getValueType(),
1142                                                Op.getOperand(0)));
1143 
1144     // If the sign bit is known one, the top bits match.
1145     if (KnownOne.intersects(InSignBit)) {
1146       KnownOne |= NewBits;
1147       assert((KnownZero & NewBits) == 0);
1148     } else {   // Otherwise, top bits aren't known.
1149       assert((KnownOne & NewBits) == 0);
1150       assert((KnownZero & NewBits) == 0);
1151     }
1152     break;
1153   }
1154   case ISD::ANY_EXTEND: {
1155     unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
1156     APInt InMask = NewMask.trunc(OperandBitWidth);
1157     if (SimplifyDemandedBits(Op.getOperand(0), InMask,
1158                              KnownZero, KnownOne, TLO, Depth+1))
1159       return true;
1160     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1161     KnownZero = KnownZero.zext(BitWidth);
1162     KnownOne = KnownOne.zext(BitWidth);
1163     break;
1164   }
1165   case ISD::TRUNCATE: {
1166     // Simplify the input, using demanded bit information, and compute the known
1167     // zero/one bits live out.
1168     unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
1169     APInt TruncMask = NewMask.zext(OperandBitWidth);
1170     if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
1171                              KnownZero, KnownOne, TLO, Depth+1))
1172       return true;
1173     KnownZero = KnownZero.trunc(BitWidth);
1174     KnownOne = KnownOne.trunc(BitWidth);
1175 
1176     // If the input is only used by this truncate, see if we can shrink it based
1177     // on the known demanded bits.
1178     if (Op.getOperand(0).getNode()->hasOneUse()) {
1179       SDValue In = Op.getOperand(0);
1180       switch (In.getOpcode()) {
1181       default: break;
1182       case ISD::SRL:
1183         // Shrink SRL by a constant if none of the high bits shifted in are
1184         // demanded.
1185         if (TLO.LegalTypes() &&
1186             !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
1187           // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1188           // undesirable.
1189           break;
1190         ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
1191         if (!ShAmt)
1192           break;
1193         SDValue Shift = In.getOperand(1);
1194         if (TLO.LegalTypes()) {
1195           uint64_t ShVal = ShAmt->getZExtValue();
1196           Shift = TLO.DAG.getConstant(ShVal, dl,
1197                                       getShiftAmountTy(Op.getValueType(), DL));
1198         }
1199 
1200         APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
1201                                                OperandBitWidth - BitWidth);
1202         HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth);
1203 
1204         if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) {
1205           // None of the shifted in bits are needed.  Add a truncate of the
1206           // shift input, then shift it.
1207           SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
1208                                              Op.getValueType(),
1209                                              In.getOperand(0));
1210           return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
1211                                                    Op.getValueType(),
1212                                                    NewTrunc,
1213                                                    Shift));
1214         }
1215         break;
1216       }
1217     }
1218 
1219     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1220     break;
1221   }
1222   case ISD::AssertZext: {
1223     // AssertZext demands all of the high bits, plus any of the low bits
1224     // demanded by its users.
1225     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1226     APInt InMask = APInt::getLowBitsSet(BitWidth,
1227                                         VT.getSizeInBits());
1228     if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
1229                              KnownZero, KnownOne, TLO, Depth+1))
1230       return true;
1231     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1232 
1233     KnownZero |= ~InMask & NewMask;
1234     break;
1235   }
1236   case ISD::BITCAST:
1237     // If this is an FP->Int bitcast and if the sign bit is the only
1238     // thing demanded, turn this into a FGETSIGN.
1239     if (!TLO.LegalOperations() &&
1240         !Op.getValueType().isVector() &&
1241         !Op.getOperand(0).getValueType().isVector() &&
1242         NewMask == APInt::getSignBit(Op.getValueSizeInBits()) &&
1243         Op.getOperand(0).getValueType().isFloatingPoint()) {
1244       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
1245       bool i32Legal  = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
1246       if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple() &&
1247            Op.getOperand(0).getValueType() != MVT::f128) {
1248         // Cannot eliminate/lower SHL for f128 yet.
1249         EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
1250         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1251         // place.  We expect the SHL to be eliminated by other optimizations.
1252         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
1253         unsigned OpVTSizeInBits = Op.getValueSizeInBits();
1254         if (!OpVTLegal && OpVTSizeInBits > 32)
1255           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
1256         unsigned ShVal = Op.getValueSizeInBits() - 1;
1257         SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, Op.getValueType());
1258         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1259                                                  Op.getValueType(),
1260                                                  Sign, ShAmt));
1261       }
1262     }
1263     break;
1264   case ISD::ADD:
1265   case ISD::MUL:
1266   case ISD::SUB: {
1267     // Add, Sub, and Mul don't demand any bits in positions beyond that
1268     // of the highest bit demanded of them.
1269     APInt LoMask = APInt::getLowBitsSet(BitWidth,
1270                                         BitWidth - NewMask.countLeadingZeros());
1271     if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
1272                              KnownOne2, TLO, Depth+1) ||
1273         SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
1274                              KnownOne2, TLO, Depth+1) ||
1275         // See if the operation should be performed at a smaller bit width.
1276         TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl)) {
1277       const SDNodeFlags *Flags = Op.getNode()->getFlags();
1278       if (Flags->hasNoSignedWrap() || Flags->hasNoUnsignedWrap()) {
1279         // Disable the nsw and nuw flags. We can no longer guarantee that we
1280         // won't wrap after simplification.
1281         SDNodeFlags NewFlags = *Flags;
1282         NewFlags.setNoSignedWrap(false);
1283         NewFlags.setNoUnsignedWrap(false);
1284         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, Op.getValueType(),
1285                                         Op.getOperand(0), Op.getOperand(1),
1286                                         &NewFlags);
1287         return TLO.CombineTo(Op, NewOp);
1288       }
1289       return true;
1290     }
1291     LLVM_FALLTHROUGH;
1292   }
1293   default:
1294     // Just use computeKnownBits to compute output bits.
1295     TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
1296     break;
1297   }
1298 
1299   // If we know the value of all of the demanded bits, return this as a
1300   // constant.
1301   if ((NewMask & (KnownZero|KnownOne)) == NewMask) {
1302     // Avoid folding to a constant if any OpaqueConstant is involved.
1303     const SDNode *N = Op.getNode();
1304     for (SDNodeIterator I = SDNodeIterator::begin(N),
1305          E = SDNodeIterator::end(N); I != E; ++I) {
1306       SDNode *Op = *I;
1307       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
1308         if (C->isOpaque())
1309           return false;
1310     }
1311     return TLO.CombineTo(Op,
1312                          TLO.DAG.getConstant(KnownOne, dl, Op.getValueType()));
1313   }
1314 
1315   return false;
1316 }
1317 
1318 /// Determine which of the bits specified in Mask are known to be either zero or
1319 /// one and return them in the KnownZero/KnownOne bitsets.
1320 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1321                                                    APInt &KnownZero,
1322                                                    APInt &KnownOne,
1323                                                    const SelectionDAG &DAG,
1324                                                    unsigned Depth) const {
1325   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1326           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1327           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1328           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1329          "Should use MaskedValueIsZero if you don't know whether Op"
1330          " is a target node!");
1331   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
1332 }
1333 
1334 /// This method can be implemented by targets that want to expose additional
1335 /// information about sign bits to the DAG Combiner.
1336 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
1337                                                          const SelectionDAG &,
1338                                                          unsigned Depth) const {
1339   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1340           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1341           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1342           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1343          "Should use ComputeNumSignBits if you don't know whether Op"
1344          " is a target node!");
1345   return 1;
1346 }
1347 
1348 bool TargetLowering::isConstTrueVal(const SDNode *N) const {
1349   if (!N)
1350     return false;
1351 
1352   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
1353   if (!CN) {
1354     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1355     if (!BV)
1356       return false;
1357 
1358     // Only interested in constant splats, we don't care about undef
1359     // elements in identifying boolean constants and getConstantSplatNode
1360     // returns NULL if all ops are undef;
1361     CN = BV->getConstantSplatNode();
1362     if (!CN)
1363       return false;
1364   }
1365 
1366   switch (getBooleanContents(N->getValueType(0))) {
1367   case UndefinedBooleanContent:
1368     return CN->getAPIntValue()[0];
1369   case ZeroOrOneBooleanContent:
1370     return CN->isOne();
1371   case ZeroOrNegativeOneBooleanContent:
1372     return CN->isAllOnesValue();
1373   }
1374 
1375   llvm_unreachable("Invalid boolean contents");
1376 }
1377 
1378 SDValue TargetLowering::getConstTrueVal(SelectionDAG &DAG, EVT VT,
1379                                         const SDLoc &DL) const {
1380   unsigned ElementWidth = VT.getScalarSizeInBits();
1381   APInt TrueInt =
1382       getBooleanContents(VT) == TargetLowering::ZeroOrOneBooleanContent
1383           ? APInt(ElementWidth, 1)
1384           : APInt::getAllOnesValue(ElementWidth);
1385   return DAG.getConstant(TrueInt, DL, VT);
1386 }
1387 
1388 bool TargetLowering::isConstFalseVal(const SDNode *N) const {
1389   if (!N)
1390     return false;
1391 
1392   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
1393   if (!CN) {
1394     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1395     if (!BV)
1396       return false;
1397 
1398     // Only interested in constant splats, we don't care about undef
1399     // elements in identifying boolean constants and getConstantSplatNode
1400     // returns NULL if all ops are undef;
1401     CN = BV->getConstantSplatNode();
1402     if (!CN)
1403       return false;
1404   }
1405 
1406   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
1407     return !CN->getAPIntValue()[0];
1408 
1409   return CN->isNullValue();
1410 }
1411 
1412 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
1413                                        bool SExt) const {
1414   if (VT == MVT::i1)
1415     return N->isOne();
1416 
1417   TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
1418   switch (Cnt) {
1419   case TargetLowering::ZeroOrOneBooleanContent:
1420     // An extended value of 1 is always true, unless its original type is i1,
1421     // in which case it will be sign extended to -1.
1422     return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
1423   case TargetLowering::UndefinedBooleanContent:
1424   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1425     return N->isAllOnesValue() && SExt;
1426   }
1427   llvm_unreachable("Unexpected enumeration.");
1428 }
1429 
1430 /// This helper function of SimplifySetCC tries to optimize the comparison when
1431 /// either operand of the SetCC node is a bitwise-and instruction.
1432 SDValue TargetLowering::simplifySetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
1433                                              ISD::CondCode Cond,
1434                                              DAGCombinerInfo &DCI,
1435                                              const SDLoc &DL) const {
1436   // Match these patterns in any of their permutations:
1437   // (X & Y) == Y
1438   // (X & Y) != Y
1439   if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
1440     std::swap(N0, N1);
1441 
1442   EVT OpVT = N0.getValueType();
1443   if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
1444       (Cond != ISD::SETEQ && Cond != ISD::SETNE))
1445     return SDValue();
1446 
1447   SDValue X, Y;
1448   if (N0.getOperand(0) == N1) {
1449     X = N0.getOperand(1);
1450     Y = N0.getOperand(0);
1451   } else if (N0.getOperand(1) == N1) {
1452     X = N0.getOperand(0);
1453     Y = N0.getOperand(1);
1454   } else {
1455     return SDValue();
1456   }
1457 
1458   SelectionDAG &DAG = DCI.DAG;
1459   SDValue Zero = DAG.getConstant(0, DL, OpVT);
1460   if (DAG.isKnownToBeAPowerOfTwo(Y)) {
1461     // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
1462     // Note that where Y is variable and is known to have at most one bit set
1463     // (for example, if it is Z & 1) we cannot do this; the expressions are not
1464     // equivalent when Y == 0.
1465     Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
1466     if (DCI.isBeforeLegalizeOps() ||
1467         isCondCodeLegal(Cond, N0.getSimpleValueType()))
1468       return DAG.getSetCC(DL, VT, N0, Zero, Cond);
1469   } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
1470     // If the target supports an 'and-not' or 'and-complement' logic operation,
1471     // try to use that to make a comparison operation more efficient.
1472     // But don't do this transform if the mask is a single bit because there are
1473     // more efficient ways to deal with that case (for example, 'bt' on x86 or
1474     // 'rlwinm' on PPC).
1475 
1476     // Bail out if the compare operand that we want to turn into a zero is
1477     // already a zero (otherwise, infinite loop).
1478     auto *YConst = dyn_cast<ConstantSDNode>(Y);
1479     if (YConst && YConst->isNullValue())
1480       return SDValue();
1481 
1482     // Transform this into: ~X & Y == 0.
1483     SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
1484     SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
1485     return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
1486   }
1487 
1488   return SDValue();
1489 }
1490 
1491 /// Try to simplify a setcc built with the specified operands and cc. If it is
1492 /// unable to simplify it, return a null SDValue.
1493 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1494                                       ISD::CondCode Cond, bool foldBooleans,
1495                                       DAGCombinerInfo &DCI,
1496                                       const SDLoc &dl) const {
1497   SelectionDAG &DAG = DCI.DAG;
1498 
1499   // These setcc operations always fold.
1500   switch (Cond) {
1501   default: break;
1502   case ISD::SETFALSE:
1503   case ISD::SETFALSE2: return DAG.getConstant(0, dl, VT);
1504   case ISD::SETTRUE:
1505   case ISD::SETTRUE2: {
1506     TargetLowering::BooleanContent Cnt =
1507         getBooleanContents(N0->getValueType(0));
1508     return DAG.getConstant(
1509         Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
1510         VT);
1511   }
1512   }
1513 
1514   // Ensure that the constant occurs on the RHS, and fold constant
1515   // comparisons.
1516   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
1517   if (isa<ConstantSDNode>(N0.getNode()) &&
1518       (DCI.isBeforeLegalizeOps() ||
1519        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
1520     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
1521 
1522   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1523     const APInt &C1 = N1C->getAPIntValue();
1524 
1525     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1526     // equality comparison, then we're just comparing whether X itself is
1527     // zero.
1528     if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1529         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1530         N0.getOperand(1).getOpcode() == ISD::Constant) {
1531       const APInt &ShAmt
1532         = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1533       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1534           ShAmt == Log2_32(N0.getValueSizeInBits())) {
1535         if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1536           // (srl (ctlz x), 5) == 0  -> X != 0
1537           // (srl (ctlz x), 5) != 1  -> X != 0
1538           Cond = ISD::SETNE;
1539         } else {
1540           // (srl (ctlz x), 5) != 0  -> X == 0
1541           // (srl (ctlz x), 5) == 1  -> X == 0
1542           Cond = ISD::SETEQ;
1543         }
1544         SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
1545         return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
1546                             Zero, Cond);
1547       }
1548     }
1549 
1550     SDValue CTPOP = N0;
1551     // Look through truncs that don't change the value of a ctpop.
1552     if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
1553       CTPOP = N0.getOperand(0);
1554 
1555     if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
1556         (N0 == CTPOP ||
1557          N0.getValueSizeInBits() > Log2_32_Ceil(CTPOP.getValueSizeInBits()))) {
1558       EVT CTVT = CTPOP.getValueType();
1559       SDValue CTOp = CTPOP.getOperand(0);
1560 
1561       // (ctpop x) u< 2 -> (x & x-1) == 0
1562       // (ctpop x) u> 1 -> (x & x-1) != 0
1563       if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
1564         SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
1565                                   DAG.getConstant(1, dl, CTVT));
1566         SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
1567         ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
1568         return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC);
1569       }
1570 
1571       // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
1572     }
1573 
1574     // (zext x) == C --> x == (trunc C)
1575     // (sext x) == C --> x == (trunc C)
1576     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1577         DCI.isBeforeLegalize() && N0->hasOneUse()) {
1578       unsigned MinBits = N0.getValueSizeInBits();
1579       SDValue PreExt;
1580       bool Signed = false;
1581       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
1582         // ZExt
1583         MinBits = N0->getOperand(0).getValueSizeInBits();
1584         PreExt = N0->getOperand(0);
1585       } else if (N0->getOpcode() == ISD::AND) {
1586         // DAGCombine turns costly ZExts into ANDs
1587         if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
1588           if ((C->getAPIntValue()+1).isPowerOf2()) {
1589             MinBits = C->getAPIntValue().countTrailingOnes();
1590             PreExt = N0->getOperand(0);
1591           }
1592       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
1593         // SExt
1594         MinBits = N0->getOperand(0).getValueSizeInBits();
1595         PreExt = N0->getOperand(0);
1596         Signed = true;
1597       } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
1598         // ZEXTLOAD / SEXTLOAD
1599         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
1600           MinBits = LN0->getMemoryVT().getSizeInBits();
1601           PreExt = N0;
1602         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
1603           Signed = true;
1604           MinBits = LN0->getMemoryVT().getSizeInBits();
1605           PreExt = N0;
1606         }
1607       }
1608 
1609       // Figure out how many bits we need to preserve this constant.
1610       unsigned ReqdBits = Signed ?
1611         C1.getBitWidth() - C1.getNumSignBits() + 1 :
1612         C1.getActiveBits();
1613 
1614       // Make sure we're not losing bits from the constant.
1615       if (MinBits > 0 &&
1616           MinBits < C1.getBitWidth() &&
1617           MinBits >= ReqdBits) {
1618         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
1619         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
1620           // Will get folded away.
1621           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
1622           if (MinBits == 1 && C1 == 1)
1623             // Invert the condition.
1624             return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
1625                                 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1626           SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
1627           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
1628         }
1629 
1630         // If truncating the setcc operands is not desirable, we can still
1631         // simplify the expression in some cases:
1632         // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
1633         // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
1634         // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
1635         // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
1636         // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
1637         // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
1638         SDValue TopSetCC = N0->getOperand(0);
1639         unsigned N0Opc = N0->getOpcode();
1640         bool SExt = (N0Opc == ISD::SIGN_EXTEND);
1641         if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
1642             TopSetCC.getOpcode() == ISD::SETCC &&
1643             (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
1644             (isConstFalseVal(N1C) ||
1645              isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
1646 
1647           bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) ||
1648                          (!N1C->isNullValue() && Cond == ISD::SETNE);
1649 
1650           if (!Inverse)
1651             return TopSetCC;
1652 
1653           ISD::CondCode InvCond = ISD::getSetCCInverse(
1654               cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
1655               TopSetCC.getOperand(0).getValueType().isInteger());
1656           return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
1657                                       TopSetCC.getOperand(1),
1658                                       InvCond);
1659 
1660         }
1661       }
1662     }
1663 
1664     // If the LHS is '(and load, const)', the RHS is 0,
1665     // the test is for equality or unsigned, and all 1 bits of the const are
1666     // in the same partial word, see if we can shorten the load.
1667     if (DCI.isBeforeLegalize() &&
1668         !ISD::isSignedIntSetCC(Cond) &&
1669         N0.getOpcode() == ISD::AND && C1 == 0 &&
1670         N0.getNode()->hasOneUse() &&
1671         isa<LoadSDNode>(N0.getOperand(0)) &&
1672         N0.getOperand(0).getNode()->hasOneUse() &&
1673         isa<ConstantSDNode>(N0.getOperand(1))) {
1674       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
1675       APInt bestMask;
1676       unsigned bestWidth = 0, bestOffset = 0;
1677       if (!Lod->isVolatile() && Lod->isUnindexed()) {
1678         unsigned origWidth = N0.getValueSizeInBits();
1679         unsigned maskWidth = origWidth;
1680         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
1681         // 8 bits, but have to be careful...
1682         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
1683           origWidth = Lod->getMemoryVT().getSizeInBits();
1684         const APInt &Mask =
1685           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1686         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
1687           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
1688           for (unsigned offset=0; offset<origWidth/width; offset++) {
1689             if ((newMask & Mask) == Mask) {
1690               if (!DAG.getDataLayout().isLittleEndian())
1691                 bestOffset = (origWidth/width - offset - 1) * (width/8);
1692               else
1693                 bestOffset = (uint64_t)offset * (width/8);
1694               bestMask = Mask.lshr(offset * (width/8) * 8);
1695               bestWidth = width;
1696               break;
1697             }
1698             newMask = newMask << width;
1699           }
1700         }
1701       }
1702       if (bestWidth) {
1703         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
1704         if (newVT.isRound()) {
1705           EVT PtrType = Lod->getOperand(1).getValueType();
1706           SDValue Ptr = Lod->getBasePtr();
1707           if (bestOffset != 0)
1708             Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
1709                               DAG.getConstant(bestOffset, dl, PtrType));
1710           unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
1711           SDValue NewLoad = DAG.getLoad(
1712               newVT, dl, Lod->getChain(), Ptr,
1713               Lod->getPointerInfo().getWithOffset(bestOffset), NewAlign);
1714           return DAG.getSetCC(dl, VT,
1715                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
1716                                       DAG.getConstant(bestMask.trunc(bestWidth),
1717                                                       dl, newVT)),
1718                               DAG.getConstant(0LL, dl, newVT), Cond);
1719         }
1720       }
1721     }
1722 
1723     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1724     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1725       unsigned InSize = N0.getOperand(0).getValueSizeInBits();
1726 
1727       // If the comparison constant has bits in the upper part, the
1728       // zero-extended value could never match.
1729       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
1730                                               C1.getBitWidth() - InSize))) {
1731         switch (Cond) {
1732         case ISD::SETUGT:
1733         case ISD::SETUGE:
1734         case ISD::SETEQ: return DAG.getConstant(0, dl, VT);
1735         case ISD::SETULT:
1736         case ISD::SETULE:
1737         case ISD::SETNE: return DAG.getConstant(1, dl, VT);
1738         case ISD::SETGT:
1739         case ISD::SETGE:
1740           // True if the sign bit of C1 is set.
1741           return DAG.getConstant(C1.isNegative(), dl, VT);
1742         case ISD::SETLT:
1743         case ISD::SETLE:
1744           // True if the sign bit of C1 isn't set.
1745           return DAG.getConstant(C1.isNonNegative(), dl, VT);
1746         default:
1747           break;
1748         }
1749       }
1750 
1751       // Otherwise, we can perform the comparison with the low bits.
1752       switch (Cond) {
1753       case ISD::SETEQ:
1754       case ISD::SETNE:
1755       case ISD::SETUGT:
1756       case ISD::SETUGE:
1757       case ISD::SETULT:
1758       case ISD::SETULE: {
1759         EVT newVT = N0.getOperand(0).getValueType();
1760         if (DCI.isBeforeLegalizeOps() ||
1761             (isOperationLegal(ISD::SETCC, newVT) &&
1762              getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) {
1763           EVT NewSetCCVT =
1764               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT);
1765           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
1766 
1767           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
1768                                           NewConst, Cond);
1769           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
1770         }
1771         break;
1772       }
1773       default:
1774         break;   // todo, be more careful with signed comparisons
1775       }
1776     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1777                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1778       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
1779       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
1780       EVT ExtDstTy = N0.getValueType();
1781       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
1782 
1783       // If the constant doesn't fit into the number of bits for the source of
1784       // the sign extension, it is impossible for both sides to be equal.
1785       if (C1.getMinSignedBits() > ExtSrcTyBits)
1786         return DAG.getConstant(Cond == ISD::SETNE, dl, VT);
1787 
1788       SDValue ZextOp;
1789       EVT Op0Ty = N0.getOperand(0).getValueType();
1790       if (Op0Ty == ExtSrcTy) {
1791         ZextOp = N0.getOperand(0);
1792       } else {
1793         APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
1794         ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
1795                               DAG.getConstant(Imm, dl, Op0Ty));
1796       }
1797       if (!DCI.isCalledByLegalizer())
1798         DCI.AddToWorklist(ZextOp.getNode());
1799       // Otherwise, make this a use of a zext.
1800       return DAG.getSetCC(dl, VT, ZextOp,
1801                           DAG.getConstant(C1 & APInt::getLowBitsSet(
1802                                                               ExtDstTyBits,
1803                                                               ExtSrcTyBits),
1804                                           dl, ExtDstTy),
1805                           Cond);
1806     } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
1807                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1808       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
1809       if (N0.getOpcode() == ISD::SETCC &&
1810           isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
1811         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
1812         if (TrueWhenTrue)
1813           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
1814         // Invert the condition.
1815         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
1816         CC = ISD::getSetCCInverse(CC,
1817                                   N0.getOperand(0).getValueType().isInteger());
1818         if (DCI.isBeforeLegalizeOps() ||
1819             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
1820           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
1821       }
1822 
1823       if ((N0.getOpcode() == ISD::XOR ||
1824            (N0.getOpcode() == ISD::AND &&
1825             N0.getOperand(0).getOpcode() == ISD::XOR &&
1826             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1827           isa<ConstantSDNode>(N0.getOperand(1)) &&
1828           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
1829         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
1830         // can only do this if the top bits are known zero.
1831         unsigned BitWidth = N0.getValueSizeInBits();
1832         if (DAG.MaskedValueIsZero(N0,
1833                                   APInt::getHighBitsSet(BitWidth,
1834                                                         BitWidth-1))) {
1835           // Okay, get the un-inverted input value.
1836           SDValue Val;
1837           if (N0.getOpcode() == ISD::XOR)
1838             Val = N0.getOperand(0);
1839           else {
1840             assert(N0.getOpcode() == ISD::AND &&
1841                     N0.getOperand(0).getOpcode() == ISD::XOR);
1842             // ((X^1)&1)^1 -> X & 1
1843             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
1844                               N0.getOperand(0).getOperand(0),
1845                               N0.getOperand(1));
1846           }
1847 
1848           return DAG.getSetCC(dl, VT, Val, N1,
1849                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1850         }
1851       } else if (N1C->getAPIntValue() == 1 &&
1852                  (VT == MVT::i1 ||
1853                   getBooleanContents(N0->getValueType(0)) ==
1854                       ZeroOrOneBooleanContent)) {
1855         SDValue Op0 = N0;
1856         if (Op0.getOpcode() == ISD::TRUNCATE)
1857           Op0 = Op0.getOperand(0);
1858 
1859         if ((Op0.getOpcode() == ISD::XOR) &&
1860             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
1861             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
1862           // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
1863           Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
1864           return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
1865                               Cond);
1866         }
1867         if (Op0.getOpcode() == ISD::AND &&
1868             isa<ConstantSDNode>(Op0.getOperand(1)) &&
1869             cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
1870           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
1871           if (Op0.getValueType().bitsGT(VT))
1872             Op0 = DAG.getNode(ISD::AND, dl, VT,
1873                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
1874                           DAG.getConstant(1, dl, VT));
1875           else if (Op0.getValueType().bitsLT(VT))
1876             Op0 = DAG.getNode(ISD::AND, dl, VT,
1877                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
1878                         DAG.getConstant(1, dl, VT));
1879 
1880           return DAG.getSetCC(dl, VT, Op0,
1881                               DAG.getConstant(0, dl, Op0.getValueType()),
1882                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1883         }
1884         if (Op0.getOpcode() == ISD::AssertZext &&
1885             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
1886           return DAG.getSetCC(dl, VT, Op0,
1887                               DAG.getConstant(0, dl, Op0.getValueType()),
1888                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1889       }
1890     }
1891 
1892     APInt MinVal, MaxVal;
1893     unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
1894     if (ISD::isSignedIntSetCC(Cond)) {
1895       MinVal = APInt::getSignedMinValue(OperandBitSize);
1896       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
1897     } else {
1898       MinVal = APInt::getMinValue(OperandBitSize);
1899       MaxVal = APInt::getMaxValue(OperandBitSize);
1900     }
1901 
1902     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1903     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
1904       if (C1 == MinVal) return DAG.getConstant(1, dl, VT);  // X >= MIN --> true
1905       // X >= C0 --> X > (C0 - 1)
1906       APInt C = C1 - 1;
1907       ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
1908       if ((DCI.isBeforeLegalizeOps() ||
1909            isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1910           (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1911                                 isLegalICmpImmediate(C.getSExtValue())))) {
1912         return DAG.getSetCC(dl, VT, N0,
1913                             DAG.getConstant(C, dl, N1.getValueType()),
1914                             NewCC);
1915       }
1916     }
1917 
1918     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
1919       if (C1 == MaxVal) return DAG.getConstant(1, dl, VT);  // X <= MAX --> true
1920       // X <= C0 --> X < (C0 + 1)
1921       APInt C = C1 + 1;
1922       ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
1923       if ((DCI.isBeforeLegalizeOps() ||
1924            isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1925           (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1926                                 isLegalICmpImmediate(C.getSExtValue())))) {
1927         return DAG.getSetCC(dl, VT, N0,
1928                             DAG.getConstant(C, dl, N1.getValueType()),
1929                             NewCC);
1930       }
1931     }
1932 
1933     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
1934       return DAG.getConstant(0, dl, VT);      // X < MIN --> false
1935     if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
1936       return DAG.getConstant(1, dl, VT);      // X >= MIN --> true
1937     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
1938       return DAG.getConstant(0, dl, VT);      // X > MAX --> false
1939     if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
1940       return DAG.getConstant(1, dl, VT);      // X <= MAX --> true
1941 
1942     // Canonicalize setgt X, Min --> setne X, Min
1943     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1944       return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1945     // Canonicalize setlt X, Max --> setne X, Max
1946     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1947       return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1948 
1949     // If we have setult X, 1, turn it into seteq X, 0
1950     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
1951       return DAG.getSetCC(dl, VT, N0,
1952                           DAG.getConstant(MinVal, dl, N0.getValueType()),
1953                           ISD::SETEQ);
1954     // If we have setugt X, Max-1, turn it into seteq X, Max
1955     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
1956       return DAG.getSetCC(dl, VT, N0,
1957                           DAG.getConstant(MaxVal, dl, N0.getValueType()),
1958                           ISD::SETEQ);
1959 
1960     // If we have "setcc X, C0", check to see if we can shrink the immediate
1961     // by changing cc.
1962 
1963     // SETUGT X, SINTMAX  -> SETLT X, 0
1964     if (Cond == ISD::SETUGT &&
1965         C1 == APInt::getSignedMaxValue(OperandBitSize))
1966       return DAG.getSetCC(dl, VT, N0,
1967                           DAG.getConstant(0, dl, N1.getValueType()),
1968                           ISD::SETLT);
1969 
1970     // SETULT X, SINTMIN  -> SETGT X, -1
1971     if (Cond == ISD::SETULT &&
1972         C1 == APInt::getSignedMinValue(OperandBitSize)) {
1973       SDValue ConstMinusOne =
1974           DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl,
1975                           N1.getValueType());
1976       return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
1977     }
1978 
1979     // Fold bit comparisons when we can.
1980     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1981         (VT == N0.getValueType() ||
1982          (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
1983         N0.getOpcode() == ISD::AND) {
1984       auto &DL = DAG.getDataLayout();
1985       if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1986         EVT ShiftTy = DCI.isBeforeLegalize()
1987                           ? getPointerTy(DL)
1988                           : getShiftAmountTy(N0.getValueType(), DL);
1989         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
1990           // Perform the xform if the AND RHS is a single bit.
1991           if (AndRHS->getAPIntValue().isPowerOf2()) {
1992             return DAG.getNode(ISD::TRUNCATE, dl, VT,
1993                               DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
1994                    DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl,
1995                                    ShiftTy)));
1996           }
1997         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
1998           // (X & 8) == 8  -->  (X & 8) >> 3
1999           // Perform the xform if C1 is a single bit.
2000           if (C1.isPowerOf2()) {
2001             return DAG.getNode(ISD::TRUNCATE, dl, VT,
2002                                DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
2003                                       DAG.getConstant(C1.logBase2(), dl,
2004                                                       ShiftTy)));
2005           }
2006         }
2007       }
2008     }
2009 
2010     if (C1.getMinSignedBits() <= 64 &&
2011         !isLegalICmpImmediate(C1.getSExtValue())) {
2012       // (X & -256) == 256 -> (X >> 8) == 1
2013       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2014           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
2015         if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2016           const APInt &AndRHSC = AndRHS->getAPIntValue();
2017           if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
2018             unsigned ShiftBits = AndRHSC.countTrailingZeros();
2019             auto &DL = DAG.getDataLayout();
2020             EVT ShiftTy = DCI.isBeforeLegalize()
2021                               ? getPointerTy(DL)
2022                               : getShiftAmountTy(N0.getValueType(), DL);
2023             EVT CmpTy = N0.getValueType();
2024             SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
2025                                         DAG.getConstant(ShiftBits, dl,
2026                                                         ShiftTy));
2027             SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy);
2028             return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
2029           }
2030         }
2031       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
2032                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
2033         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
2034         // X <  0x100000000 -> (X >> 32) <  1
2035         // X >= 0x100000000 -> (X >> 32) >= 1
2036         // X <= 0x0ffffffff -> (X >> 32) <  1
2037         // X >  0x0ffffffff -> (X >> 32) >= 1
2038         unsigned ShiftBits;
2039         APInt NewC = C1;
2040         ISD::CondCode NewCond = Cond;
2041         if (AdjOne) {
2042           ShiftBits = C1.countTrailingOnes();
2043           NewC = NewC + 1;
2044           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2045         } else {
2046           ShiftBits = C1.countTrailingZeros();
2047         }
2048         NewC = NewC.lshr(ShiftBits);
2049         if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
2050           isLegalICmpImmediate(NewC.getSExtValue())) {
2051           auto &DL = DAG.getDataLayout();
2052           EVT ShiftTy = DCI.isBeforeLegalize()
2053                             ? getPointerTy(DL)
2054                             : getShiftAmountTy(N0.getValueType(), DL);
2055           EVT CmpTy = N0.getValueType();
2056           SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
2057                                       DAG.getConstant(ShiftBits, dl, ShiftTy));
2058           SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy);
2059           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
2060         }
2061       }
2062     }
2063   }
2064 
2065   if (isa<ConstantFPSDNode>(N0.getNode())) {
2066     // Constant fold or commute setcc.
2067     SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
2068     if (O.getNode()) return O;
2069   } else if (auto *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
2070     // If the RHS of an FP comparison is a constant, simplify it away in
2071     // some cases.
2072     if (CFP->getValueAPF().isNaN()) {
2073       // If an operand is known to be a nan, we can fold it.
2074       switch (ISD::getUnorderedFlavor(Cond)) {
2075       default: llvm_unreachable("Unknown flavor!");
2076       case 0:  // Known false.
2077         return DAG.getConstant(0, dl, VT);
2078       case 1:  // Known true.
2079         return DAG.getConstant(1, dl, VT);
2080       case 2:  // Undefined.
2081         return DAG.getUNDEF(VT);
2082       }
2083     }
2084 
2085     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
2086     // constant if knowing that the operand is non-nan is enough.  We prefer to
2087     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
2088     // materialize 0.0.
2089     if (Cond == ISD::SETO || Cond == ISD::SETUO)
2090       return DAG.getSetCC(dl, VT, N0, N0, Cond);
2091 
2092     // setcc (fneg x), C -> setcc swap(pred) x, -C
2093     if (N0.getOpcode() == ISD::FNEG) {
2094       ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond);
2095       if (DCI.isBeforeLegalizeOps() ||
2096           isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
2097         SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
2098         return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
2099       }
2100     }
2101 
2102     // If the condition is not legal, see if we can find an equivalent one
2103     // which is legal.
2104     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
2105       // If the comparison was an awkward floating-point == or != and one of
2106       // the comparison operands is infinity or negative infinity, convert the
2107       // condition to a less-awkward <= or >=.
2108       if (CFP->getValueAPF().isInfinity()) {
2109         if (CFP->getValueAPF().isNegative()) {
2110           if (Cond == ISD::SETOEQ &&
2111               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
2112             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
2113           if (Cond == ISD::SETUEQ &&
2114               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
2115             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
2116           if (Cond == ISD::SETUNE &&
2117               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
2118             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
2119           if (Cond == ISD::SETONE &&
2120               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
2121             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
2122         } else {
2123           if (Cond == ISD::SETOEQ &&
2124               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
2125             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
2126           if (Cond == ISD::SETUEQ &&
2127               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
2128             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
2129           if (Cond == ISD::SETUNE &&
2130               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
2131             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
2132           if (Cond == ISD::SETONE &&
2133               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
2134             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
2135         }
2136       }
2137     }
2138   }
2139 
2140   if (N0 == N1) {
2141     // The sext(setcc()) => setcc() optimization relies on the appropriate
2142     // constant being emitted.
2143     uint64_t EqVal = 0;
2144     switch (getBooleanContents(N0.getValueType())) {
2145     case UndefinedBooleanContent:
2146     case ZeroOrOneBooleanContent:
2147       EqVal = ISD::isTrueWhenEqual(Cond);
2148       break;
2149     case ZeroOrNegativeOneBooleanContent:
2150       EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0;
2151       break;
2152     }
2153 
2154     // We can always fold X == X for integer setcc's.
2155     if (N0.getValueType().isInteger()) {
2156       return DAG.getConstant(EqVal, dl, VT);
2157     }
2158     unsigned UOF = ISD::getUnorderedFlavor(Cond);
2159     if (UOF == 2)   // FP operators that are undefined on NaNs.
2160       return DAG.getConstant(EqVal, dl, VT);
2161     if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
2162       return DAG.getConstant(EqVal, dl, VT);
2163     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
2164     // if it is not already.
2165     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
2166     if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
2167           getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
2168       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
2169   }
2170 
2171   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2172       N0.getValueType().isInteger()) {
2173     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
2174         N0.getOpcode() == ISD::XOR) {
2175       // Simplify (X+Y) == (X+Z) -->  Y == Z
2176       if (N0.getOpcode() == N1.getOpcode()) {
2177         if (N0.getOperand(0) == N1.getOperand(0))
2178           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
2179         if (N0.getOperand(1) == N1.getOperand(1))
2180           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
2181         if (DAG.isCommutativeBinOp(N0.getOpcode())) {
2182           // If X op Y == Y op X, try other combinations.
2183           if (N0.getOperand(0) == N1.getOperand(1))
2184             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
2185                                 Cond);
2186           if (N0.getOperand(1) == N1.getOperand(0))
2187             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
2188                                 Cond);
2189         }
2190       }
2191 
2192       // If RHS is a legal immediate value for a compare instruction, we need
2193       // to be careful about increasing register pressure needlessly.
2194       bool LegalRHSImm = false;
2195 
2196       if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
2197         if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2198           // Turn (X+C1) == C2 --> X == C2-C1
2199           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
2200             return DAG.getSetCC(dl, VT, N0.getOperand(0),
2201                                 DAG.getConstant(RHSC->getAPIntValue()-
2202                                                 LHSR->getAPIntValue(),
2203                                 dl, N0.getValueType()), Cond);
2204           }
2205 
2206           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
2207           if (N0.getOpcode() == ISD::XOR)
2208             // If we know that all of the inverted bits are zero, don't bother
2209             // performing the inversion.
2210             if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
2211               return
2212                 DAG.getSetCC(dl, VT, N0.getOperand(0),
2213                              DAG.getConstant(LHSR->getAPIntValue() ^
2214                                                RHSC->getAPIntValue(),
2215                                              dl, N0.getValueType()),
2216                              Cond);
2217         }
2218 
2219         // Turn (C1-X) == C2 --> X == C1-C2
2220         if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
2221           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
2222             return
2223               DAG.getSetCC(dl, VT, N0.getOperand(1),
2224                            DAG.getConstant(SUBC->getAPIntValue() -
2225                                              RHSC->getAPIntValue(),
2226                                            dl, N0.getValueType()),
2227                            Cond);
2228           }
2229         }
2230 
2231         // Could RHSC fold directly into a compare?
2232         if (RHSC->getValueType(0).getSizeInBits() <= 64)
2233           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
2234       }
2235 
2236       // Simplify (X+Z) == X -->  Z == 0
2237       // Don't do this if X is an immediate that can fold into a cmp
2238       // instruction and X+Z has other uses. It could be an induction variable
2239       // chain, and the transform would increase register pressure.
2240       if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
2241         if (N0.getOperand(0) == N1)
2242           return DAG.getSetCC(dl, VT, N0.getOperand(1),
2243                               DAG.getConstant(0, dl, N0.getValueType()), Cond);
2244         if (N0.getOperand(1) == N1) {
2245           if (DAG.isCommutativeBinOp(N0.getOpcode()))
2246             return DAG.getSetCC(dl, VT, N0.getOperand(0),
2247                                 DAG.getConstant(0, dl, N0.getValueType()),
2248                                 Cond);
2249           if (N0.getNode()->hasOneUse()) {
2250             assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
2251             auto &DL = DAG.getDataLayout();
2252             // (Z-X) == X  --> Z == X<<1
2253             SDValue SH = DAG.getNode(
2254                 ISD::SHL, dl, N1.getValueType(), N1,
2255                 DAG.getConstant(1, dl,
2256                                 getShiftAmountTy(N1.getValueType(), DL)));
2257             if (!DCI.isCalledByLegalizer())
2258               DCI.AddToWorklist(SH.getNode());
2259             return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
2260           }
2261         }
2262       }
2263     }
2264 
2265     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
2266         N1.getOpcode() == ISD::XOR) {
2267       // Simplify  X == (X+Z) -->  Z == 0
2268       if (N1.getOperand(0) == N0)
2269         return DAG.getSetCC(dl, VT, N1.getOperand(1),
2270                         DAG.getConstant(0, dl, N1.getValueType()), Cond);
2271       if (N1.getOperand(1) == N0) {
2272         if (DAG.isCommutativeBinOp(N1.getOpcode()))
2273           return DAG.getSetCC(dl, VT, N1.getOperand(0),
2274                           DAG.getConstant(0, dl, N1.getValueType()), Cond);
2275         if (N1.getNode()->hasOneUse()) {
2276           assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
2277           auto &DL = DAG.getDataLayout();
2278           // X == (Z-X)  --> X<<1 == Z
2279           SDValue SH = DAG.getNode(
2280               ISD::SHL, dl, N1.getValueType(), N0,
2281               DAG.getConstant(1, dl, getShiftAmountTy(N0.getValueType(), DL)));
2282           if (!DCI.isCalledByLegalizer())
2283             DCI.AddToWorklist(SH.getNode());
2284           return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
2285         }
2286       }
2287     }
2288 
2289     if (SDValue V = simplifySetCCWithAnd(VT, N0, N1, Cond, DCI, dl))
2290       return V;
2291   }
2292 
2293   // Fold away ALL boolean setcc's.
2294   SDValue Temp;
2295   if (N0.getValueType() == MVT::i1 && foldBooleans) {
2296     switch (Cond) {
2297     default: llvm_unreachable("Unknown integer setcc!");
2298     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
2299       Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2300       N0 = DAG.getNOT(dl, Temp, MVT::i1);
2301       if (!DCI.isCalledByLegalizer())
2302         DCI.AddToWorklist(Temp.getNode());
2303       break;
2304     case ISD::SETNE:  // X != Y   -->  (X^Y)
2305       N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2306       break;
2307     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
2308     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
2309       Temp = DAG.getNOT(dl, N0, MVT::i1);
2310       N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
2311       if (!DCI.isCalledByLegalizer())
2312         DCI.AddToWorklist(Temp.getNode());
2313       break;
2314     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
2315     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
2316       Temp = DAG.getNOT(dl, N1, MVT::i1);
2317       N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
2318       if (!DCI.isCalledByLegalizer())
2319         DCI.AddToWorklist(Temp.getNode());
2320       break;
2321     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
2322     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
2323       Temp = DAG.getNOT(dl, N0, MVT::i1);
2324       N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
2325       if (!DCI.isCalledByLegalizer())
2326         DCI.AddToWorklist(Temp.getNode());
2327       break;
2328     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
2329     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
2330       Temp = DAG.getNOT(dl, N1, MVT::i1);
2331       N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
2332       break;
2333     }
2334     if (VT != MVT::i1) {
2335       if (!DCI.isCalledByLegalizer())
2336         DCI.AddToWorklist(N0.getNode());
2337       // FIXME: If running after legalize, we probably can't do this.
2338       N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
2339     }
2340     return N0;
2341   }
2342 
2343   // Could not fold it.
2344   return SDValue();
2345 }
2346 
2347 /// Returns true (and the GlobalValue and the offset) if the node is a
2348 /// GlobalAddress + offset.
2349 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
2350                                     int64_t &Offset) const {
2351   if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
2352     GA = GASD->getGlobal();
2353     Offset += GASD->getOffset();
2354     return true;
2355   }
2356 
2357   if (N->getOpcode() == ISD::ADD) {
2358     SDValue N1 = N->getOperand(0);
2359     SDValue N2 = N->getOperand(1);
2360     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
2361       if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
2362         Offset += V->getSExtValue();
2363         return true;
2364       }
2365     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
2366       if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
2367         Offset += V->getSExtValue();
2368         return true;
2369       }
2370     }
2371   }
2372 
2373   return false;
2374 }
2375 
2376 SDValue TargetLowering::PerformDAGCombine(SDNode *N,
2377                                           DAGCombinerInfo &DCI) const {
2378   // Default implementation: no optimization.
2379   return SDValue();
2380 }
2381 
2382 //===----------------------------------------------------------------------===//
2383 //  Inline Assembler Implementation Methods
2384 //===----------------------------------------------------------------------===//
2385 
2386 TargetLowering::ConstraintType
2387 TargetLowering::getConstraintType(StringRef Constraint) const {
2388   unsigned S = Constraint.size();
2389 
2390   if (S == 1) {
2391     switch (Constraint[0]) {
2392     default: break;
2393     case 'r': return C_RegisterClass;
2394     case 'm':    // memory
2395     case 'o':    // offsetable
2396     case 'V':    // not offsetable
2397       return C_Memory;
2398     case 'i':    // Simple Integer or Relocatable Constant
2399     case 'n':    // Simple Integer
2400     case 'E':    // Floating Point Constant
2401     case 'F':    // Floating Point Constant
2402     case 's':    // Relocatable Constant
2403     case 'p':    // Address.
2404     case 'X':    // Allow ANY value.
2405     case 'I':    // Target registers.
2406     case 'J':
2407     case 'K':
2408     case 'L':
2409     case 'M':
2410     case 'N':
2411     case 'O':
2412     case 'P':
2413     case '<':
2414     case '>':
2415       return C_Other;
2416     }
2417   }
2418 
2419   if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') {
2420     if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
2421       return C_Memory;
2422     return C_Register;
2423   }
2424   return C_Unknown;
2425 }
2426 
2427 /// Try to replace an X constraint, which matches anything, with another that
2428 /// has more specific requirements based on the type of the corresponding
2429 /// operand.
2430 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
2431   if (ConstraintVT.isInteger())
2432     return "r";
2433   if (ConstraintVT.isFloatingPoint())
2434     return "f";      // works for many targets
2435   return nullptr;
2436 }
2437 
2438 /// Lower the specified operand into the Ops vector.
2439 /// If it is invalid, don't add anything to Ops.
2440 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2441                                                   std::string &Constraint,
2442                                                   std::vector<SDValue> &Ops,
2443                                                   SelectionDAG &DAG) const {
2444 
2445   if (Constraint.length() > 1) return;
2446 
2447   char ConstraintLetter = Constraint[0];
2448   switch (ConstraintLetter) {
2449   default: break;
2450   case 'X':     // Allows any operand; labels (basic block) use this.
2451     if (Op.getOpcode() == ISD::BasicBlock) {
2452       Ops.push_back(Op);
2453       return;
2454     }
2455     LLVM_FALLTHROUGH;
2456   case 'i':    // Simple Integer or Relocatable Constant
2457   case 'n':    // Simple Integer
2458   case 's': {  // Relocatable Constant
2459     // These operands are interested in values of the form (GV+C), where C may
2460     // be folded in as an offset of GV, or it may be explicitly added.  Also, it
2461     // is possible and fine if either GV or C are missing.
2462     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2463     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2464 
2465     // If we have "(add GV, C)", pull out GV/C
2466     if (Op.getOpcode() == ISD::ADD) {
2467       C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2468       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
2469       if (!C || !GA) {
2470         C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
2471         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
2472       }
2473       if (!C || !GA) {
2474         C = nullptr;
2475         GA = nullptr;
2476       }
2477     }
2478 
2479     // If we find a valid operand, map to the TargetXXX version so that the
2480     // value itself doesn't get selected.
2481     if (GA) {   // Either &GV   or   &GV+C
2482       if (ConstraintLetter != 'n') {
2483         int64_t Offs = GA->getOffset();
2484         if (C) Offs += C->getZExtValue();
2485         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
2486                                                  C ? SDLoc(C) : SDLoc(),
2487                                                  Op.getValueType(), Offs));
2488       }
2489       return;
2490     }
2491     if (C) {   // just C, no GV.
2492       // Simple constants are not allowed for 's'.
2493       if (ConstraintLetter != 's') {
2494         // gcc prints these as sign extended.  Sign extend value to 64 bits
2495         // now; without this it would get ZExt'd later in
2496         // ScheduleDAGSDNodes::EmitNode, which is very generic.
2497         Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
2498                                             SDLoc(C), MVT::i64));
2499       }
2500       return;
2501     }
2502     break;
2503   }
2504   }
2505 }
2506 
2507 std::pair<unsigned, const TargetRegisterClass *>
2508 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
2509                                              StringRef Constraint,
2510                                              MVT VT) const {
2511   if (Constraint.empty() || Constraint[0] != '{')
2512     return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr));
2513   assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
2514 
2515   // Remove the braces from around the name.
2516   StringRef RegName(Constraint.data()+1, Constraint.size()-2);
2517 
2518   std::pair<unsigned, const TargetRegisterClass*> R =
2519     std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr));
2520 
2521   // Figure out which register class contains this reg.
2522   for (const TargetRegisterClass *RC : RI->regclasses()) {
2523     // If none of the value types for this register class are valid, we
2524     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
2525     if (!isLegalRC(RC))
2526       continue;
2527 
2528     for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
2529          I != E; ++I) {
2530       if (RegName.equals_lower(RI->getRegAsmName(*I))) {
2531         std::pair<unsigned, const TargetRegisterClass*> S =
2532           std::make_pair(*I, RC);
2533 
2534         // If this register class has the requested value type, return it,
2535         // otherwise keep searching and return the first class found
2536         // if no other is found which explicitly has the requested type.
2537         if (RC->hasType(VT))
2538           return S;
2539         else if (!R.second)
2540           R = S;
2541       }
2542     }
2543   }
2544 
2545   return R;
2546 }
2547 
2548 //===----------------------------------------------------------------------===//
2549 // Constraint Selection.
2550 
2551 /// Return true of this is an input operand that is a matching constraint like
2552 /// "4".
2553 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
2554   assert(!ConstraintCode.empty() && "No known constraint!");
2555   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
2556 }
2557 
2558 /// If this is an input matching constraint, this method returns the output
2559 /// operand it matches.
2560 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
2561   assert(!ConstraintCode.empty() && "No known constraint!");
2562   return atoi(ConstraintCode.c_str());
2563 }
2564 
2565 /// Split up the constraint string from the inline assembly value into the
2566 /// specific constraints and their prefixes, and also tie in the associated
2567 /// operand values.
2568 /// If this returns an empty vector, and if the constraint string itself
2569 /// isn't empty, there was an error parsing.
2570 TargetLowering::AsmOperandInfoVector
2571 TargetLowering::ParseConstraints(const DataLayout &DL,
2572                                  const TargetRegisterInfo *TRI,
2573                                  ImmutableCallSite CS) const {
2574   /// Information about all of the constraints.
2575   AsmOperandInfoVector ConstraintOperands;
2576   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
2577   unsigned maCount = 0; // Largest number of multiple alternative constraints.
2578 
2579   // Do a prepass over the constraints, canonicalizing them, and building up the
2580   // ConstraintOperands list.
2581   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
2582   unsigned ResNo = 0;   // ResNo - The result number of the next output.
2583 
2584   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2585     ConstraintOperands.emplace_back(std::move(CI));
2586     AsmOperandInfo &OpInfo = ConstraintOperands.back();
2587 
2588     // Update multiple alternative constraint count.
2589     if (OpInfo.multipleAlternatives.size() > maCount)
2590       maCount = OpInfo.multipleAlternatives.size();
2591 
2592     OpInfo.ConstraintVT = MVT::Other;
2593 
2594     // Compute the value type for each operand.
2595     switch (OpInfo.Type) {
2596     case InlineAsm::isOutput:
2597       // Indirect outputs just consume an argument.
2598       if (OpInfo.isIndirect) {
2599         OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2600         break;
2601       }
2602 
2603       // The return value of the call is this value.  As such, there is no
2604       // corresponding argument.
2605       assert(!CS.getType()->isVoidTy() &&
2606              "Bad inline asm!");
2607       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
2608         OpInfo.ConstraintVT =
2609             getSimpleValueType(DL, STy->getElementType(ResNo));
2610       } else {
2611         assert(ResNo == 0 && "Asm only has one result!");
2612         OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType());
2613       }
2614       ++ResNo;
2615       break;
2616     case InlineAsm::isInput:
2617       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2618       break;
2619     case InlineAsm::isClobber:
2620       // Nothing to do.
2621       break;
2622     }
2623 
2624     if (OpInfo.CallOperandVal) {
2625       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
2626       if (OpInfo.isIndirect) {
2627         llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
2628         if (!PtrTy)
2629           report_fatal_error("Indirect operand for inline asm not a pointer!");
2630         OpTy = PtrTy->getElementType();
2631       }
2632 
2633       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
2634       if (StructType *STy = dyn_cast<StructType>(OpTy))
2635         if (STy->getNumElements() == 1)
2636           OpTy = STy->getElementType(0);
2637 
2638       // If OpTy is not a single value, it may be a struct/union that we
2639       // can tile with integers.
2640       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
2641         unsigned BitSize = DL.getTypeSizeInBits(OpTy);
2642         switch (BitSize) {
2643         default: break;
2644         case 1:
2645         case 8:
2646         case 16:
2647         case 32:
2648         case 64:
2649         case 128:
2650           OpInfo.ConstraintVT =
2651             MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
2652           break;
2653         }
2654       } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
2655         unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
2656         OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
2657       } else {
2658         OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
2659       }
2660     }
2661   }
2662 
2663   // If we have multiple alternative constraints, select the best alternative.
2664   if (!ConstraintOperands.empty()) {
2665     if (maCount) {
2666       unsigned bestMAIndex = 0;
2667       int bestWeight = -1;
2668       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
2669       int weight = -1;
2670       unsigned maIndex;
2671       // Compute the sums of the weights for each alternative, keeping track
2672       // of the best (highest weight) one so far.
2673       for (maIndex = 0; maIndex < maCount; ++maIndex) {
2674         int weightSum = 0;
2675         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2676             cIndex != eIndex; ++cIndex) {
2677           AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2678           if (OpInfo.Type == InlineAsm::isClobber)
2679             continue;
2680 
2681           // If this is an output operand with a matching input operand,
2682           // look up the matching input. If their types mismatch, e.g. one
2683           // is an integer, the other is floating point, or their sizes are
2684           // different, flag it as an maCantMatch.
2685           if (OpInfo.hasMatchingInput()) {
2686             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2687             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2688               if ((OpInfo.ConstraintVT.isInteger() !=
2689                    Input.ConstraintVT.isInteger()) ||
2690                   (OpInfo.ConstraintVT.getSizeInBits() !=
2691                    Input.ConstraintVT.getSizeInBits())) {
2692                 weightSum = -1;  // Can't match.
2693                 break;
2694               }
2695             }
2696           }
2697           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
2698           if (weight == -1) {
2699             weightSum = -1;
2700             break;
2701           }
2702           weightSum += weight;
2703         }
2704         // Update best.
2705         if (weightSum > bestWeight) {
2706           bestWeight = weightSum;
2707           bestMAIndex = maIndex;
2708         }
2709       }
2710 
2711       // Now select chosen alternative in each constraint.
2712       for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2713           cIndex != eIndex; ++cIndex) {
2714         AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
2715         if (cInfo.Type == InlineAsm::isClobber)
2716           continue;
2717         cInfo.selectAlternative(bestMAIndex);
2718       }
2719     }
2720   }
2721 
2722   // Check and hook up tied operands, choose constraint code to use.
2723   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2724       cIndex != eIndex; ++cIndex) {
2725     AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2726 
2727     // If this is an output operand with a matching input operand, look up the
2728     // matching input. If their types mismatch, e.g. one is an integer, the
2729     // other is floating point, or their sizes are different, flag it as an
2730     // error.
2731     if (OpInfo.hasMatchingInput()) {
2732       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2733 
2734       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2735         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
2736             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
2737                                          OpInfo.ConstraintVT);
2738         std::pair<unsigned, const TargetRegisterClass *> InputRC =
2739             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
2740                                          Input.ConstraintVT);
2741         if ((OpInfo.ConstraintVT.isInteger() !=
2742              Input.ConstraintVT.isInteger()) ||
2743             (MatchRC.second != InputRC.second)) {
2744           report_fatal_error("Unsupported asm: input constraint"
2745                              " with a matching output constraint of"
2746                              " incompatible type!");
2747         }
2748       }
2749     }
2750   }
2751 
2752   return ConstraintOperands;
2753 }
2754 
2755 /// Return an integer indicating how general CT is.
2756 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2757   switch (CT) {
2758   case TargetLowering::C_Other:
2759   case TargetLowering::C_Unknown:
2760     return 0;
2761   case TargetLowering::C_Register:
2762     return 1;
2763   case TargetLowering::C_RegisterClass:
2764     return 2;
2765   case TargetLowering::C_Memory:
2766     return 3;
2767   }
2768   llvm_unreachable("Invalid constraint type");
2769 }
2770 
2771 /// Examine constraint type and operand type and determine a weight value.
2772 /// This object must already have been set up with the operand type
2773 /// and the current alternative constraint selected.
2774 TargetLowering::ConstraintWeight
2775   TargetLowering::getMultipleConstraintMatchWeight(
2776     AsmOperandInfo &info, int maIndex) const {
2777   InlineAsm::ConstraintCodeVector *rCodes;
2778   if (maIndex >= (int)info.multipleAlternatives.size())
2779     rCodes = &info.Codes;
2780   else
2781     rCodes = &info.multipleAlternatives[maIndex].Codes;
2782   ConstraintWeight BestWeight = CW_Invalid;
2783 
2784   // Loop over the options, keeping track of the most general one.
2785   for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
2786     ConstraintWeight weight =
2787       getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
2788     if (weight > BestWeight)
2789       BestWeight = weight;
2790   }
2791 
2792   return BestWeight;
2793 }
2794 
2795 /// Examine constraint type and operand type and determine a weight value.
2796 /// This object must already have been set up with the operand type
2797 /// and the current alternative constraint selected.
2798 TargetLowering::ConstraintWeight
2799   TargetLowering::getSingleConstraintMatchWeight(
2800     AsmOperandInfo &info, const char *constraint) const {
2801   ConstraintWeight weight = CW_Invalid;
2802   Value *CallOperandVal = info.CallOperandVal;
2803     // If we don't have a value, we can't do a match,
2804     // but allow it at the lowest weight.
2805   if (!CallOperandVal)
2806     return CW_Default;
2807   // Look at the constraint type.
2808   switch (*constraint) {
2809     case 'i': // immediate integer.
2810     case 'n': // immediate integer with a known value.
2811       if (isa<ConstantInt>(CallOperandVal))
2812         weight = CW_Constant;
2813       break;
2814     case 's': // non-explicit intregal immediate.
2815       if (isa<GlobalValue>(CallOperandVal))
2816         weight = CW_Constant;
2817       break;
2818     case 'E': // immediate float if host format.
2819     case 'F': // immediate float.
2820       if (isa<ConstantFP>(CallOperandVal))
2821         weight = CW_Constant;
2822       break;
2823     case '<': // memory operand with autodecrement.
2824     case '>': // memory operand with autoincrement.
2825     case 'm': // memory operand.
2826     case 'o': // offsettable memory operand
2827     case 'V': // non-offsettable memory operand
2828       weight = CW_Memory;
2829       break;
2830     case 'r': // general register.
2831     case 'g': // general register, memory operand or immediate integer.
2832               // note: Clang converts "g" to "imr".
2833       if (CallOperandVal->getType()->isIntegerTy())
2834         weight = CW_Register;
2835       break;
2836     case 'X': // any operand.
2837     default:
2838       weight = CW_Default;
2839       break;
2840   }
2841   return weight;
2842 }
2843 
2844 /// If there are multiple different constraints that we could pick for this
2845 /// operand (e.g. "imr") try to pick the 'best' one.
2846 /// This is somewhat tricky: constraints fall into four classes:
2847 ///    Other         -> immediates and magic values
2848 ///    Register      -> one specific register
2849 ///    RegisterClass -> a group of regs
2850 ///    Memory        -> memory
2851 /// Ideally, we would pick the most specific constraint possible: if we have
2852 /// something that fits into a register, we would pick it.  The problem here
2853 /// is that if we have something that could either be in a register or in
2854 /// memory that use of the register could cause selection of *other*
2855 /// operands to fail: they might only succeed if we pick memory.  Because of
2856 /// this the heuristic we use is:
2857 ///
2858 ///  1) If there is an 'other' constraint, and if the operand is valid for
2859 ///     that constraint, use it.  This makes us take advantage of 'i'
2860 ///     constraints when available.
2861 ///  2) Otherwise, pick the most general constraint present.  This prefers
2862 ///     'm' over 'r', for example.
2863 ///
2864 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
2865                              const TargetLowering &TLI,
2866                              SDValue Op, SelectionDAG *DAG) {
2867   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
2868   unsigned BestIdx = 0;
2869   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
2870   int BestGenerality = -1;
2871 
2872   // Loop over the options, keeping track of the most general one.
2873   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
2874     TargetLowering::ConstraintType CType =
2875       TLI.getConstraintType(OpInfo.Codes[i]);
2876 
2877     // If this is an 'other' constraint, see if the operand is valid for it.
2878     // For example, on X86 we might have an 'rI' constraint.  If the operand
2879     // is an integer in the range [0..31] we want to use I (saving a load
2880     // of a register), otherwise we must use 'r'.
2881     if (CType == TargetLowering::C_Other && Op.getNode()) {
2882       assert(OpInfo.Codes[i].size() == 1 &&
2883              "Unhandled multi-letter 'other' constraint");
2884       std::vector<SDValue> ResultOps;
2885       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
2886                                        ResultOps, *DAG);
2887       if (!ResultOps.empty()) {
2888         BestType = CType;
2889         BestIdx = i;
2890         break;
2891       }
2892     }
2893 
2894     // Things with matching constraints can only be registers, per gcc
2895     // documentation.  This mainly affects "g" constraints.
2896     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
2897       continue;
2898 
2899     // This constraint letter is more general than the previous one, use it.
2900     int Generality = getConstraintGenerality(CType);
2901     if (Generality > BestGenerality) {
2902       BestType = CType;
2903       BestIdx = i;
2904       BestGenerality = Generality;
2905     }
2906   }
2907 
2908   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
2909   OpInfo.ConstraintType = BestType;
2910 }
2911 
2912 /// Determines the constraint code and constraint type to use for the specific
2913 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
2914 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
2915                                             SDValue Op,
2916                                             SelectionDAG *DAG) const {
2917   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
2918 
2919   // Single-letter constraints ('r') are very common.
2920   if (OpInfo.Codes.size() == 1) {
2921     OpInfo.ConstraintCode = OpInfo.Codes[0];
2922     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2923   } else {
2924     ChooseConstraint(OpInfo, *this, Op, DAG);
2925   }
2926 
2927   // 'X' matches anything.
2928   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
2929     // Labels and constants are handled elsewhere ('X' is the only thing
2930     // that matches labels).  For Functions, the type here is the type of
2931     // the result, which is not what we want to look at; leave them alone.
2932     Value *v = OpInfo.CallOperandVal;
2933     if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
2934       OpInfo.CallOperandVal = v;
2935       return;
2936     }
2937 
2938     // Otherwise, try to resolve it to something we know about by looking at
2939     // the actual operand type.
2940     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
2941       OpInfo.ConstraintCode = Repl;
2942       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2943     }
2944   }
2945 }
2946 
2947 /// \brief Given an exact SDIV by a constant, create a multiplication
2948 /// with the multiplicative inverse of the constant.
2949 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDValue Op1, APInt d,
2950                               const SDLoc &dl, SelectionDAG &DAG,
2951                               std::vector<SDNode *> &Created) {
2952   assert(d != 0 && "Division by zero!");
2953 
2954   // Shift the value upfront if it is even, so the LSB is one.
2955   unsigned ShAmt = d.countTrailingZeros();
2956   if (ShAmt) {
2957     // TODO: For UDIV use SRL instead of SRA.
2958     SDValue Amt =
2959         DAG.getConstant(ShAmt, dl, TLI.getShiftAmountTy(Op1.getValueType(),
2960                                                         DAG.getDataLayout()));
2961     SDNodeFlags Flags;
2962     Flags.setExact(true);
2963     Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, &Flags);
2964     Created.push_back(Op1.getNode());
2965     d = d.ashr(ShAmt);
2966   }
2967 
2968   // Calculate the multiplicative inverse, using Newton's method.
2969   APInt t, xn = d;
2970   while ((t = d*xn) != 1)
2971     xn *= APInt(d.getBitWidth(), 2) - t;
2972 
2973   SDValue Op2 = DAG.getConstant(xn, dl, Op1.getValueType());
2974   SDValue Mul = DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
2975   Created.push_back(Mul.getNode());
2976   return Mul;
2977 }
2978 
2979 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
2980                                       SelectionDAG &DAG,
2981                                       std::vector<SDNode *> *Created) const {
2982   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2983   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2984   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
2985     return SDValue(N,0); // Lower SDIV as SDIV
2986   return SDValue();
2987 }
2988 
2989 /// \brief Given an ISD::SDIV node expressing a divide by constant,
2990 /// return a DAG expression to select that will generate the same value by
2991 /// multiplying by a magic number.
2992 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
2993 SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor,
2994                                   SelectionDAG &DAG, bool IsAfterLegalization,
2995                                   std::vector<SDNode *> *Created) const {
2996   assert(Created && "No vector to hold sdiv ops.");
2997 
2998   EVT VT = N->getValueType(0);
2999   SDLoc dl(N);
3000 
3001   // Check to see if we can do this.
3002   // FIXME: We should be more aggressive here.
3003   if (!isTypeLegal(VT))
3004     return SDValue();
3005 
3006   // If the sdiv has an 'exact' bit we can use a simpler lowering.
3007   if (cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact())
3008     return BuildExactSDIV(*this, N->getOperand(0), Divisor, dl, DAG, *Created);
3009 
3010   APInt::ms magics = Divisor.magic();
3011 
3012   // Multiply the numerator (operand 0) by the magic value
3013   // FIXME: We should support doing a MUL in a wider type
3014   SDValue Q;
3015   if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
3016                             isOperationLegalOrCustom(ISD::MULHS, VT))
3017     Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
3018                     DAG.getConstant(magics.m, dl, VT));
3019   else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
3020                                  isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
3021     Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
3022                               N->getOperand(0),
3023                               DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
3024   else
3025     return SDValue();       // No mulhs or equvialent
3026   // If d > 0 and m < 0, add the numerator
3027   if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
3028     Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
3029     Created->push_back(Q.getNode());
3030   }
3031   // If d < 0 and m > 0, subtract the numerator.
3032   if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
3033     Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
3034     Created->push_back(Q.getNode());
3035   }
3036   auto &DL = DAG.getDataLayout();
3037   // Shift right algebraic if shift value is nonzero
3038   if (magics.s > 0) {
3039     Q = DAG.getNode(
3040         ISD::SRA, dl, VT, Q,
3041         DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
3042     Created->push_back(Q.getNode());
3043   }
3044   // Extract the sign bit and add it to the quotient
3045   SDValue T =
3046       DAG.getNode(ISD::SRL, dl, VT, Q,
3047                   DAG.getConstant(VT.getScalarSizeInBits() - 1, dl,
3048                                   getShiftAmountTy(Q.getValueType(), DL)));
3049   Created->push_back(T.getNode());
3050   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
3051 }
3052 
3053 /// \brief Given an ISD::UDIV node expressing a divide by constant,
3054 /// return a DAG expression to select that will generate the same value by
3055 /// multiplying by a magic number.
3056 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
3057 SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor,
3058                                   SelectionDAG &DAG, bool IsAfterLegalization,
3059                                   std::vector<SDNode *> *Created) const {
3060   assert(Created && "No vector to hold udiv ops.");
3061 
3062   EVT VT = N->getValueType(0);
3063   SDLoc dl(N);
3064   auto &DL = DAG.getDataLayout();
3065 
3066   // Check to see if we can do this.
3067   // FIXME: We should be more aggressive here.
3068   if (!isTypeLegal(VT))
3069     return SDValue();
3070 
3071   // FIXME: We should use a narrower constant when the upper
3072   // bits are known to be zero.
3073   APInt::mu magics = Divisor.magicu();
3074 
3075   SDValue Q = N->getOperand(0);
3076 
3077   // If the divisor is even, we can avoid using the expensive fixup by shifting
3078   // the divided value upfront.
3079   if (magics.a != 0 && !Divisor[0]) {
3080     unsigned Shift = Divisor.countTrailingZeros();
3081     Q = DAG.getNode(
3082         ISD::SRL, dl, VT, Q,
3083         DAG.getConstant(Shift, dl, getShiftAmountTy(Q.getValueType(), DL)));
3084     Created->push_back(Q.getNode());
3085 
3086     // Get magic number for the shifted divisor.
3087     magics = Divisor.lshr(Shift).magicu(Shift);
3088     assert(magics.a == 0 && "Should use cheap fixup now");
3089   }
3090 
3091   // Multiply the numerator (operand 0) by the magic value
3092   // FIXME: We should support doing a MUL in a wider type
3093   if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
3094                             isOperationLegalOrCustom(ISD::MULHU, VT))
3095     Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, dl, VT));
3096   else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
3097                                  isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
3098     Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
3099                             DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
3100   else
3101     return SDValue();       // No mulhu or equivalent
3102 
3103   Created->push_back(Q.getNode());
3104 
3105   if (magics.a == 0) {
3106     assert(magics.s < Divisor.getBitWidth() &&
3107            "We shouldn't generate an undefined shift!");
3108     return DAG.getNode(
3109         ISD::SRL, dl, VT, Q,
3110         DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
3111   } else {
3112     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
3113     Created->push_back(NPQ.getNode());
3114     NPQ = DAG.getNode(
3115         ISD::SRL, dl, VT, NPQ,
3116         DAG.getConstant(1, dl, getShiftAmountTy(NPQ.getValueType(), DL)));
3117     Created->push_back(NPQ.getNode());
3118     NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
3119     Created->push_back(NPQ.getNode());
3120     return DAG.getNode(
3121         ISD::SRL, dl, VT, NPQ,
3122         DAG.getConstant(magics.s - 1, dl,
3123                         getShiftAmountTy(NPQ.getValueType(), DL)));
3124   }
3125 }
3126 
3127 bool TargetLowering::
3128 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
3129   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
3130     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
3131                                 "be a constant integer");
3132     return true;
3133   }
3134 
3135   return false;
3136 }
3137 
3138 //===----------------------------------------------------------------------===//
3139 // Legalization Utilities
3140 //===----------------------------------------------------------------------===//
3141 
3142 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl,
3143                                     SDValue LHS, SDValue RHS,
3144                                     SmallVectorImpl<SDValue> &Result,
3145                                     EVT HiLoVT, SelectionDAG &DAG,
3146                                     MulExpansionKind Kind, SDValue LL,
3147                                     SDValue LH, SDValue RL, SDValue RH) const {
3148   assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
3149          Opcode == ISD::SMUL_LOHI);
3150 
3151   bool HasMULHS = (Kind == MulExpansionKind::Always) ||
3152                   isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
3153   bool HasMULHU = (Kind == MulExpansionKind::Always) ||
3154                   isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
3155   bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
3156                       isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
3157   bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
3158                       isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
3159 
3160   if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
3161     return false;
3162 
3163   unsigned OuterBitSize = VT.getScalarSizeInBits();
3164   unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
3165   unsigned LHSSB = DAG.ComputeNumSignBits(LHS);
3166   unsigned RHSSB = DAG.ComputeNumSignBits(RHS);
3167 
3168   // LL, LH, RL, and RH must be either all NULL or all set to a value.
3169   assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
3170          (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
3171 
3172   SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
3173   auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
3174                           bool Signed) -> bool {
3175     if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
3176       Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
3177       Hi = SDValue(Lo.getNode(), 1);
3178       return true;
3179     }
3180     if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
3181       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
3182       Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
3183       return true;
3184     }
3185     return false;
3186   };
3187 
3188   SDValue Lo, Hi;
3189 
3190   if (!LL.getNode() && !RL.getNode() &&
3191       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
3192     LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
3193     RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
3194   }
3195 
3196   if (!LL.getNode())
3197     return false;
3198 
3199   APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
3200   if (DAG.MaskedValueIsZero(LHS, HighMask) &&
3201       DAG.MaskedValueIsZero(RHS, HighMask)) {
3202     // The inputs are both zero-extended.
3203     if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
3204       Result.push_back(Lo);
3205       Result.push_back(Hi);
3206       if (Opcode != ISD::MUL) {
3207         SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
3208         Result.push_back(Zero);
3209         Result.push_back(Zero);
3210       }
3211       return true;
3212     }
3213   }
3214 
3215   if (!VT.isVector() && Opcode == ISD::MUL && LHSSB > InnerBitSize &&
3216       RHSSB > InnerBitSize) {
3217     // The input values are both sign-extended.
3218     // TODO non-MUL case?
3219     if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
3220       Result.push_back(Lo);
3221       Result.push_back(Hi);
3222       return true;
3223     }
3224   }
3225 
3226   unsigned ShiftAmount = OuterBitSize - InnerBitSize;
3227   EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout());
3228   if (APInt::getMaxValue(ShiftAmountTy.getSizeInBits()).ult(ShiftAmount)) {
3229     // FIXME getShiftAmountTy does not always return a sensible result when VT
3230     // is an illegal type, and so the type may be too small to fit the shift
3231     // amount. Override it with i32. The shift will have to be legalized.
3232     ShiftAmountTy = MVT::i32;
3233   }
3234   SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy);
3235 
3236   if (!LH.getNode() && !RH.getNode() &&
3237       isOperationLegalOrCustom(ISD::SRL, VT) &&
3238       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
3239     LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
3240     LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
3241     RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
3242     RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
3243   }
3244 
3245   if (!LH.getNode())
3246     return false;
3247 
3248   if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
3249     return false;
3250 
3251   Result.push_back(Lo);
3252 
3253   if (Opcode == ISD::MUL) {
3254     RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
3255     LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
3256     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
3257     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
3258     Result.push_back(Hi);
3259     return true;
3260   }
3261 
3262   // Compute the full width result.
3263   auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
3264     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
3265     Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
3266     Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
3267     return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
3268   };
3269 
3270   SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
3271   if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
3272     return false;
3273 
3274   // This is effectively the add part of a multiply-add of half-sized operands,
3275   // so it cannot overflow.
3276   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
3277 
3278   if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
3279     return false;
3280 
3281   Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
3282                      Merge(Lo, Hi));
3283 
3284   SDValue Carry = Next.getValue(1);
3285   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
3286   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
3287 
3288   if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
3289     return false;
3290 
3291   SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
3292   Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
3293                    Carry);
3294   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
3295 
3296   if (Opcode == ISD::SMUL_LOHI) {
3297     SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
3298                                   DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
3299     Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
3300 
3301     NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
3302                           DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
3303     Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
3304   }
3305 
3306   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
3307   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
3308   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
3309   return true;
3310 }
3311 
3312 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
3313                                SelectionDAG &DAG, MulExpansionKind Kind,
3314                                SDValue LL, SDValue LH, SDValue RL,
3315                                SDValue RH) const {
3316   SmallVector<SDValue, 2> Result;
3317   bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), N,
3318                            N->getOperand(0), N->getOperand(1), Result, HiLoVT,
3319                            DAG, Kind, LL, LH, RL, RH);
3320   if (Ok) {
3321     assert(Result.size() == 2);
3322     Lo = Result[0];
3323     Hi = Result[1];
3324   }
3325   return Ok;
3326 }
3327 
3328 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
3329                                SelectionDAG &DAG) const {
3330   EVT VT = Node->getOperand(0).getValueType();
3331   EVT NVT = Node->getValueType(0);
3332   SDLoc dl(SDValue(Node, 0));
3333 
3334   // FIXME: Only f32 to i64 conversions are supported.
3335   if (VT != MVT::f32 || NVT != MVT::i64)
3336     return false;
3337 
3338   // Expand f32 -> i64 conversion
3339   // This algorithm comes from compiler-rt's implementation of fixsfdi:
3340   // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c
3341   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(),
3342                                 VT.getSizeInBits());
3343   SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
3344   SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
3345   SDValue Bias = DAG.getConstant(127, dl, IntVT);
3346   SDValue SignMask = DAG.getConstant(APInt::getSignBit(VT.getSizeInBits()), dl,
3347                                      IntVT);
3348   SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, dl, IntVT);
3349   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
3350 
3351   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0));
3352 
3353   auto &DL = DAG.getDataLayout();
3354   SDValue ExponentBits = DAG.getNode(
3355       ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
3356       DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT, DL)));
3357   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
3358 
3359   SDValue Sign = DAG.getNode(
3360       ISD::SRA, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
3361       DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT, DL)));
3362   Sign = DAG.getSExtOrTrunc(Sign, dl, NVT);
3363 
3364   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
3365       DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
3366       DAG.getConstant(0x00800000, dl, IntVT));
3367 
3368   R = DAG.getZExtOrTrunc(R, dl, NVT);
3369 
3370   R = DAG.getSelectCC(
3371       dl, Exponent, ExponentLoBit,
3372       DAG.getNode(ISD::SHL, dl, NVT, R,
3373                   DAG.getZExtOrTrunc(
3374                       DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
3375                       dl, getShiftAmountTy(IntVT, DL))),
3376       DAG.getNode(ISD::SRL, dl, NVT, R,
3377                   DAG.getZExtOrTrunc(
3378                       DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
3379                       dl, getShiftAmountTy(IntVT, DL))),
3380       ISD::SETGT);
3381 
3382   SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT,
3383       DAG.getNode(ISD::XOR, dl, NVT, R, Sign),
3384       Sign);
3385 
3386   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
3387       DAG.getConstant(0, dl, NVT), Ret, ISD::SETLT);
3388   return true;
3389 }
3390 
3391 SDValue TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
3392                                             SelectionDAG &DAG) const {
3393   SDLoc SL(LD);
3394   SDValue Chain = LD->getChain();
3395   SDValue BasePTR = LD->getBasePtr();
3396   EVT SrcVT = LD->getMemoryVT();
3397   ISD::LoadExtType ExtType = LD->getExtensionType();
3398 
3399   unsigned NumElem = SrcVT.getVectorNumElements();
3400 
3401   EVT SrcEltVT = SrcVT.getScalarType();
3402   EVT DstEltVT = LD->getValueType(0).getScalarType();
3403 
3404   unsigned Stride = SrcEltVT.getSizeInBits() / 8;
3405   assert(SrcEltVT.isByteSized());
3406 
3407   EVT PtrVT = BasePTR.getValueType();
3408 
3409   SmallVector<SDValue, 8> Vals;
3410   SmallVector<SDValue, 8> LoadChains;
3411 
3412   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
3413     SDValue ScalarLoad =
3414         DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
3415                        LD->getPointerInfo().getWithOffset(Idx * Stride),
3416                        SrcEltVT, MinAlign(LD->getAlignment(), Idx * Stride),
3417                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
3418 
3419     BasePTR = DAG.getNode(ISD::ADD, SL, PtrVT, BasePTR,
3420                           DAG.getConstant(Stride, SL, PtrVT));
3421 
3422     Vals.push_back(ScalarLoad.getValue(0));
3423     LoadChains.push_back(ScalarLoad.getValue(1));
3424   }
3425 
3426   SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
3427   SDValue Value = DAG.getBuildVector(LD->getValueType(0), SL, Vals);
3428 
3429   return DAG.getMergeValues({ Value, NewChain }, SL);
3430 }
3431 
3432 // FIXME: This relies on each element having a byte size, otherwise the stride
3433 // is 0 and just overwrites the same location. ExpandStore currently expects
3434 // this broken behavior.
3435 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
3436                                              SelectionDAG &DAG) const {
3437   SDLoc SL(ST);
3438 
3439   SDValue Chain = ST->getChain();
3440   SDValue BasePtr = ST->getBasePtr();
3441   SDValue Value = ST->getValue();
3442   EVT StVT = ST->getMemoryVT();
3443 
3444   // The type of the data we want to save
3445   EVT RegVT = Value.getValueType();
3446   EVT RegSclVT = RegVT.getScalarType();
3447 
3448   // The type of data as saved in memory.
3449   EVT MemSclVT = StVT.getScalarType();
3450 
3451   EVT PtrVT = BasePtr.getValueType();
3452 
3453   // Store Stride in bytes
3454   unsigned Stride = MemSclVT.getSizeInBits() / 8;
3455   EVT IdxVT = getVectorIdxTy(DAG.getDataLayout());
3456   unsigned NumElem = StVT.getVectorNumElements();
3457 
3458   // Extract each of the elements from the original vector and save them into
3459   // memory individually.
3460   SmallVector<SDValue, 8> Stores;
3461   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
3462     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
3463                               DAG.getConstant(Idx, SL, IdxVT));
3464 
3465     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
3466                               DAG.getConstant(Idx * Stride, SL, PtrVT));
3467 
3468     // This scalar TruncStore may be illegal, but we legalize it later.
3469     SDValue Store = DAG.getTruncStore(
3470         Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
3471         MemSclVT, MinAlign(ST->getAlignment(), Idx * Stride),
3472         ST->getMemOperand()->getFlags(), ST->getAAInfo());
3473 
3474     Stores.push_back(Store);
3475   }
3476 
3477   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
3478 }
3479 
3480 std::pair<SDValue, SDValue>
3481 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
3482   assert(LD->getAddressingMode() == ISD::UNINDEXED &&
3483          "unaligned indexed loads not implemented!");
3484   SDValue Chain = LD->getChain();
3485   SDValue Ptr = LD->getBasePtr();
3486   EVT VT = LD->getValueType(0);
3487   EVT LoadedVT = LD->getMemoryVT();
3488   SDLoc dl(LD);
3489   if (VT.isFloatingPoint() || VT.isVector()) {
3490     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
3491     if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
3492       if (!isOperationLegalOrCustom(ISD::LOAD, intVT)) {
3493         // Scalarize the load and let the individual components be handled.
3494         SDValue Scalarized = scalarizeVectorLoad(LD, DAG);
3495         return std::make_pair(Scalarized.getValue(0), Scalarized.getValue(1));
3496       }
3497 
3498       // Expand to a (misaligned) integer load of the same size,
3499       // then bitconvert to floating point or vector.
3500       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
3501                                     LD->getMemOperand());
3502       SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
3503       if (LoadedVT != VT)
3504         Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
3505                              ISD::ANY_EXTEND, dl, VT, Result);
3506 
3507       return std::make_pair(Result, newLoad.getValue(1));
3508     }
3509 
3510     // Copy the value to a (aligned) stack slot using (unaligned) integer
3511     // loads and stores, then do a (aligned) load from the stack slot.
3512     MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
3513     unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
3514     unsigned RegBytes = RegVT.getSizeInBits() / 8;
3515     unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
3516 
3517     // Make sure the stack slot is also aligned for the register type.
3518     SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
3519 
3520     SmallVector<SDValue, 8> Stores;
3521     SDValue StackPtr = StackBase;
3522     unsigned Offset = 0;
3523 
3524     EVT PtrVT = Ptr.getValueType();
3525     EVT StackPtrVT = StackPtr.getValueType();
3526 
3527     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
3528     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
3529 
3530     // Do all but one copies using the full register width.
3531     for (unsigned i = 1; i < NumRegs; i++) {
3532       // Load one integer register's worth from the original location.
3533       SDValue Load = DAG.getLoad(
3534           RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
3535           MinAlign(LD->getAlignment(), Offset), LD->getMemOperand()->getFlags(),
3536           LD->getAAInfo());
3537       // Follow the load with a store to the stack slot.  Remember the store.
3538       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
3539                                     MachinePointerInfo()));
3540       // Increment the pointers.
3541       Offset += RegBytes;
3542       Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement);
3543       StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT, StackPtr,
3544                              StackPtrIncrement);
3545     }
3546 
3547     // The last copy may be partial.  Do an extending load.
3548     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
3549                                   8 * (LoadedBytes - Offset));
3550     SDValue Load =
3551         DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
3552                        LD->getPointerInfo().getWithOffset(Offset), MemVT,
3553                        MinAlign(LD->getAlignment(), Offset),
3554                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
3555     // Follow the load with a store to the stack slot.  Remember the store.
3556     // On big-endian machines this requires a truncating store to ensure
3557     // that the bits end up in the right place.
3558     Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
3559                                        MachinePointerInfo(), MemVT));
3560 
3561     // The order of the stores doesn't matter - say it with a TokenFactor.
3562     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
3563 
3564     // Finally, perform the original load only redirected to the stack slot.
3565     Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
3566                           MachinePointerInfo(), LoadedVT);
3567 
3568     // Callers expect a MERGE_VALUES node.
3569     return std::make_pair(Load, TF);
3570   }
3571 
3572   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
3573          "Unaligned load of unsupported type.");
3574 
3575   // Compute the new VT that is half the size of the old one.  This is an
3576   // integer MVT.
3577   unsigned NumBits = LoadedVT.getSizeInBits();
3578   EVT NewLoadedVT;
3579   NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
3580   NumBits >>= 1;
3581 
3582   unsigned Alignment = LD->getAlignment();
3583   unsigned IncrementSize = NumBits / 8;
3584   ISD::LoadExtType HiExtType = LD->getExtensionType();
3585 
3586   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
3587   if (HiExtType == ISD::NON_EXTLOAD)
3588     HiExtType = ISD::ZEXTLOAD;
3589 
3590   // Load the value in two parts
3591   SDValue Lo, Hi;
3592   if (DAG.getDataLayout().isLittleEndian()) {
3593     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
3594                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
3595                         LD->getAAInfo());
3596     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3597                       DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3598     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
3599                         LD->getPointerInfo().getWithOffset(IncrementSize),
3600                         NewLoadedVT, MinAlign(Alignment, IncrementSize),
3601                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
3602   } else {
3603     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
3604                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
3605                         LD->getAAInfo());
3606     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3607                       DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3608     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
3609                         LD->getPointerInfo().getWithOffset(IncrementSize),
3610                         NewLoadedVT, MinAlign(Alignment, IncrementSize),
3611                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
3612   }
3613 
3614   // aggregate the two parts
3615   SDValue ShiftAmount =
3616       DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
3617                                                     DAG.getDataLayout()));
3618   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
3619   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
3620 
3621   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
3622                              Hi.getValue(1));
3623 
3624   return std::make_pair(Result, TF);
3625 }
3626 
3627 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
3628                                              SelectionDAG &DAG) const {
3629   assert(ST->getAddressingMode() == ISD::UNINDEXED &&
3630          "unaligned indexed stores not implemented!");
3631   SDValue Chain = ST->getChain();
3632   SDValue Ptr = ST->getBasePtr();
3633   SDValue Val = ST->getValue();
3634   EVT VT = Val.getValueType();
3635   int Alignment = ST->getAlignment();
3636 
3637   SDLoc dl(ST);
3638   if (ST->getMemoryVT().isFloatingPoint() ||
3639       ST->getMemoryVT().isVector()) {
3640     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
3641     if (isTypeLegal(intVT)) {
3642       if (!isOperationLegalOrCustom(ISD::STORE, intVT)) {
3643         // Scalarize the store and let the individual components be handled.
3644         SDValue Result = scalarizeVectorStore(ST, DAG);
3645 
3646         return Result;
3647       }
3648       // Expand to a bitconvert of the value to the integer type of the
3649       // same size, then a (misaligned) int store.
3650       // FIXME: Does not handle truncating floating point stores!
3651       SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
3652       Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
3653                             Alignment, ST->getMemOperand()->getFlags());
3654       return Result;
3655     }
3656     // Do a (aligned) store to a stack slot, then copy from the stack slot
3657     // to the final destination using (unaligned) integer loads and stores.
3658     EVT StoredVT = ST->getMemoryVT();
3659     MVT RegVT =
3660       getRegisterType(*DAG.getContext(),
3661                       EVT::getIntegerVT(*DAG.getContext(),
3662                                         StoredVT.getSizeInBits()));
3663     EVT PtrVT = Ptr.getValueType();
3664     unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
3665     unsigned RegBytes = RegVT.getSizeInBits() / 8;
3666     unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
3667 
3668     // Make sure the stack slot is also aligned for the register type.
3669     SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
3670 
3671     // Perform the original store, only redirected to the stack slot.
3672     SDValue Store = DAG.getTruncStore(Chain, dl, Val, StackPtr,
3673                                       MachinePointerInfo(), StoredVT);
3674 
3675     EVT StackPtrVT = StackPtr.getValueType();
3676 
3677     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
3678     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
3679     SmallVector<SDValue, 8> Stores;
3680     unsigned Offset = 0;
3681 
3682     // Do all but one copies using the full register width.
3683     for (unsigned i = 1; i < NumRegs; i++) {
3684       // Load one integer register's worth from the stack slot.
3685       SDValue Load =
3686           DAG.getLoad(RegVT, dl, Store, StackPtr, MachinePointerInfo());
3687       // Store it to the final location.  Remember the store.
3688       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
3689                                     ST->getPointerInfo().getWithOffset(Offset),
3690                                     MinAlign(ST->getAlignment(), Offset),
3691                                     ST->getMemOperand()->getFlags()));
3692       // Increment the pointers.
3693       Offset += RegBytes;
3694       StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT,
3695                              StackPtr, StackPtrIncrement);
3696       Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement);
3697     }
3698 
3699     // The last store may be partial.  Do a truncating store.  On big-endian
3700     // machines this requires an extending load from the stack slot to ensure
3701     // that the bits are in the right place.
3702     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
3703                                   8 * (StoredBytes - Offset));
3704 
3705     // Load from the stack slot.
3706     SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
3707                                   MachinePointerInfo(), MemVT);
3708 
3709     Stores.push_back(
3710         DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
3711                           ST->getPointerInfo().getWithOffset(Offset), MemVT,
3712                           MinAlign(ST->getAlignment(), Offset),
3713                           ST->getMemOperand()->getFlags(), ST->getAAInfo()));
3714     // The order of the stores doesn't matter - say it with a TokenFactor.
3715     SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
3716     return Result;
3717   }
3718 
3719   assert(ST->getMemoryVT().isInteger() &&
3720          !ST->getMemoryVT().isVector() &&
3721          "Unaligned store of unknown type.");
3722   // Get the half-size VT
3723   EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
3724   int NumBits = NewStoredVT.getSizeInBits();
3725   int IncrementSize = NumBits / 8;
3726 
3727   // Divide the stored value in two parts.
3728   SDValue ShiftAmount =
3729       DAG.getConstant(NumBits, dl, getShiftAmountTy(Val.getValueType(),
3730                                                     DAG.getDataLayout()));
3731   SDValue Lo = Val;
3732   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
3733 
3734   // Store the two parts
3735   SDValue Store1, Store2;
3736   Store1 = DAG.getTruncStore(Chain, dl,
3737                              DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
3738                              Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
3739                              ST->getMemOperand()->getFlags());
3740 
3741   EVT PtrVT = Ptr.getValueType();
3742   Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3743                     DAG.getConstant(IncrementSize, dl, PtrVT));
3744   Alignment = MinAlign(Alignment, IncrementSize);
3745   Store2 = DAG.getTruncStore(
3746       Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
3747       ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
3748       ST->getMemOperand()->getFlags(), ST->getAAInfo());
3749 
3750   SDValue Result =
3751     DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
3752   return Result;
3753 }
3754 
3755 SDValue
3756 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask,
3757                                        const SDLoc &DL, EVT DataVT,
3758                                        SelectionDAG &DAG,
3759                                        bool IsCompressedMemory) const {
3760   SDValue Increment;
3761   EVT AddrVT = Addr.getValueType();
3762   EVT MaskVT = Mask.getValueType();
3763   assert(DataVT.getVectorNumElements() == MaskVT.getVectorNumElements() &&
3764          "Incompatible types of Data and Mask");
3765   if (IsCompressedMemory) {
3766     // Incrementing the pointer according to number of '1's in the mask.
3767     EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
3768     SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
3769     if (MaskIntVT.getSizeInBits() < 32) {
3770       MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
3771       MaskIntVT = MVT::i32;
3772     }
3773 
3774     // Count '1's with POPCNT.
3775     Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
3776     Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
3777     // Scale is an element size in bytes.
3778     SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
3779                                     AddrVT);
3780     Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
3781   } else
3782     Increment = DAG.getConstant(DataVT.getSizeInBits() / 8, DL, AddrVT);
3783 
3784   return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
3785 }
3786 
3787 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG,
3788                                        SDValue Idx,
3789                                        EVT VecVT,
3790                                        const SDLoc &dl) {
3791   if (isa<ConstantSDNode>(Idx))
3792     return Idx;
3793 
3794   EVT IdxVT = Idx.getValueType();
3795   unsigned NElts = VecVT.getVectorNumElements();
3796   if (isPowerOf2_32(NElts)) {
3797     APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(),
3798                                      Log2_32(NElts));
3799     return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
3800                        DAG.getConstant(Imm, dl, IdxVT));
3801   }
3802 
3803   return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
3804                      DAG.getConstant(NElts - 1, dl, IdxVT));
3805 }
3806 
3807 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG,
3808                                                 SDValue VecPtr, EVT VecVT,
3809                                                 SDValue Index) const {
3810   SDLoc dl(Index);
3811   // Make sure the index type is big enough to compute in.
3812   Index = DAG.getZExtOrTrunc(Index, dl, getPointerTy(DAG.getDataLayout()));
3813 
3814   EVT EltVT = VecVT.getVectorElementType();
3815 
3816   // Calculate the element offset and add it to the pointer.
3817   unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
3818   assert(EltSize * 8 == EltVT.getSizeInBits() &&
3819          "Converting bits to bytes lost precision");
3820 
3821   Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl);
3822 
3823   EVT IdxVT = Index.getValueType();
3824 
3825   Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
3826                       DAG.getConstant(EltSize, dl, IdxVT));
3827   return DAG.getNode(ISD::ADD, dl, IdxVT, Index, VecPtr);
3828 }
3829 
3830 //===----------------------------------------------------------------------===//
3831 // Implementation of Emulated TLS Model
3832 //===----------------------------------------------------------------------===//
3833 
3834 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
3835                                                 SelectionDAG &DAG) const {
3836   // Access to address of TLS varialbe xyz is lowered to a function call:
3837   //   __emutls_get_address( address of global variable named "__emutls_v.xyz" )
3838   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3839   PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
3840   SDLoc dl(GA);
3841 
3842   ArgListTy Args;
3843   ArgListEntry Entry;
3844   std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
3845   Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
3846   StringRef EmuTlsVarName(NameString);
3847   GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
3848   assert(EmuTlsVar && "Cannot find EmuTlsVar ");
3849   Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
3850   Entry.Ty = VoidPtrType;
3851   Args.push_back(Entry);
3852 
3853   SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
3854 
3855   TargetLowering::CallLoweringInfo CLI(DAG);
3856   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
3857   CLI.setCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
3858   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3859 
3860   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
3861   // At last for X86 targets, maybe good for other targets too?
3862   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3863   MFI.setAdjustsStack(true);  // Is this only for X86 target?
3864   MFI.setHasCalls(true);
3865 
3866   assert((GA->getOffset() == 0) &&
3867          "Emulated TLS must have zero offset in GlobalAddressSDNode");
3868   return CallResult.first;
3869 }
3870 
3871 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
3872                                                 SelectionDAG &DAG) const {
3873   assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
3874   if (!isCtlzFast())
3875     return SDValue();
3876   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3877   SDLoc dl(Op);
3878   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3879     if (C->isNullValue() && CC == ISD::SETEQ) {
3880       EVT VT = Op.getOperand(0).getValueType();
3881       SDValue Zext = Op.getOperand(0);
3882       if (VT.bitsLT(MVT::i32)) {
3883         VT = MVT::i32;
3884         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
3885       }
3886       unsigned Log2b = Log2_32(VT.getSizeInBits());
3887       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
3888       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
3889                                 DAG.getConstant(Log2b, dl, MVT::i32));
3890       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
3891     }
3892   }
3893   return SDValue();
3894 }
3895