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