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