blob: 7010347f12a3d752db55bc41f4d5952f10262285 [file] [log] [blame]
Chris Lattner3a4d1b22005-01-07 07:44:53 +00001//===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
Misha Brukman10468d82005-04-21 22:55:34 +00002//
Chris Lattner3a4d1b22005-01-07 07:44:53 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman10468d82005-04-21 22:55:34 +00007//
Chris Lattner3a4d1b22005-01-07 07:44:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the TargetLowering class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Target/TargetLowering.h"
Jakob Stoklund Olesen75fbe902012-05-04 02:19:22 +000015#include "llvm/ADT/BitVector.h"
Owen Andersone2f23a32007-09-07 04:06:50 +000016#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/CodeGen/Analysis.h"
Matthias Braun46b0f032016-04-14 01:10:42 +000018#include "llvm/CodeGen/CallingConvLower.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/CodeGen/MachineFrameInfo.h"
20#include "llvm/CodeGen/MachineFunction.h"
21#include "llvm/CodeGen/MachineJumpTableInfo.h"
Matthias Braun46b0f032016-04-14 01:10:42 +000022#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/CodeGen/SelectionDAG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/GlobalVariable.h"
Bill Wendling908bf812014-01-06 00:43:20 +000027#include "llvm/IR/LLVMContext.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/MC/MCAsmInfo.h"
29#include "llvm/MC/MCExpr.h"
Torok Edwin56d06592009-07-11 20:10:48 +000030#include "llvm/Support/ErrorHandling.h"
Chris Lattnerf0b24d22006-01-30 04:09:27 +000031#include "llvm/Support/MathExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Target/TargetLoweringObjectFile.h"
33#include "llvm/Target/TargetMachine.h"
34#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000035#include "llvm/Target/TargetSubtargetInfo.h"
Nick Lewycky0de20af2010-12-19 20:43:38 +000036#include <cctype>
Chris Lattner3a4d1b22005-01-07 07:44:53 +000037using namespace llvm;
38
Aditya Nandakumar30531552014-11-13 21:29:21 +000039/// NOTE: The TargetMachine owns TLOF.
40TargetLowering::TargetLowering(const TargetMachine &tm)
41 : TargetLoweringBase(tm) {}
Chris Lattner6f809792005-01-16 07:28:11 +000042
Evan Cheng6af02632005-12-20 06:22:03 +000043const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
Craig Topperc0196b12014-04-14 00:51:57 +000044 return nullptr;
Evan Cheng6af02632005-12-20 06:22:03 +000045}
Evan Cheng9cdc16c2005-12-21 23:05:39 +000046
Tim Northoverf1450d82013-01-09 13:18:15 +000047/// Check whether a given call node is in tail position within its function. If
48/// so, it sets Chain to the input chain of the tail call.
49bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
50 SDValue &Chain) const {
51 const Function *F = DAG.getMachineFunction().getFunction();
52
53 // Conservatively require the attributes of the call to match those of
54 // the return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +000055 AttributeSet CallerAttrs = F->getAttributes();
56 if (AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex)
Tim Northoverf1450d82013-01-09 13:18:15 +000057 .removeAttribute(Attribute::NoAlias).hasAttributes())
58 return false;
59
60 // It's not safe to eliminate the sign / zero extension of the return value.
Bill Wendling658d24d2013-01-18 21:53:16 +000061 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
62 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Tim Northoverf1450d82013-01-09 13:18:15 +000063 return false;
64
65 // Check if the only use is a function return node.
66 return isUsedByReturnOnly(Node, Chain);
67}
68
Matthias Braun46b0f032016-04-14 01:10:42 +000069bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI,
70 const uint32_t *CallerPreservedMask,
71 const SmallVectorImpl<CCValAssign> &ArgLocs,
72 const SmallVectorImpl<SDValue> &OutVals) const {
73 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
74 const CCValAssign &ArgLoc = ArgLocs[I];
75 if (!ArgLoc.isRegLoc())
76 continue;
77 unsigned Reg = ArgLoc.getLocReg();
78 // Only look at callee saved registers.
79 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
80 continue;
81 // Check that we pass the value used for the caller.
82 // (We look for a CopyFromReg reading a virtual register that is used
83 // for the function live-in value of register Reg)
84 SDValue Value = OutVals[I];
85 if (Value->getOpcode() != ISD::CopyFromReg)
86 return false;
87 unsigned ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
88 if (MRI.getLiveInPhysReg(ArgReg) != Reg)
89 return false;
90 }
91 return true;
92}
93
Andrew Trick74f4c742013-10-31 17:18:24 +000094/// \brief Set CallLoweringInfo attribute flags based on a call instruction
95/// and called function attributes.
96void TargetLowering::ArgListEntry::setAttributes(ImmutableCallSite *CS,
97 unsigned AttrIdx) {
98 isSExt = CS->paramHasAttr(AttrIdx, Attribute::SExt);
99 isZExt = CS->paramHasAttr(AttrIdx, Attribute::ZExt);
100 isInReg = CS->paramHasAttr(AttrIdx, Attribute::InReg);
101 isSRet = CS->paramHasAttr(AttrIdx, Attribute::StructRet);
102 isNest = CS->paramHasAttr(AttrIdx, Attribute::Nest);
103 isByVal = CS->paramHasAttr(AttrIdx, Attribute::ByVal);
Reid Klecknerf5b76512014-01-31 23:50:57 +0000104 isInAlloca = CS->paramHasAttr(AttrIdx, Attribute::InAlloca);
Andrew Trick74f4c742013-10-31 17:18:24 +0000105 isReturned = CS->paramHasAttr(AttrIdx, Attribute::Returned);
Manman Renf46262e2016-03-29 17:37:21 +0000106 isSwiftSelf = CS->paramHasAttr(AttrIdx, Attribute::SwiftSelf);
Manman Ren9bfd0d02016-04-01 21:41:15 +0000107 isSwiftError = CS->paramHasAttr(AttrIdx, Attribute::SwiftError);
Andrew Trick74f4c742013-10-31 17:18:24 +0000108 Alignment = CS->getParamAlignment(AttrIdx);
109}
Tim Northoverf1450d82013-01-09 13:18:15 +0000110
111/// Generate a libcall taking the given operands as arguments and returning a
112/// result of type RetVT.
Michael Gottesman7a801722013-08-13 17:54:56 +0000113std::pair<SDValue, SDValue>
114TargetLowering::makeLibCall(SelectionDAG &DAG,
115 RTLIB::Libcall LC, EVT RetVT,
Craig Topper8fe40e02015-10-22 17:05:00 +0000116 ArrayRef<SDValue> Ops,
Michael Gottesman7a801722013-08-13 17:54:56 +0000117 bool isSigned, SDLoc dl,
118 bool doesNotReturn,
119 bool isReturnValueUsed) const {
Tim Northoverf1450d82013-01-09 13:18:15 +0000120 TargetLowering::ArgListTy Args;
Craig Topper8fe40e02015-10-22 17:05:00 +0000121 Args.reserve(Ops.size());
Tim Northoverf1450d82013-01-09 13:18:15 +0000122
123 TargetLowering::ArgListEntry Entry;
Craig Topper8fe40e02015-10-22 17:05:00 +0000124 for (SDValue Op : Ops) {
125 Entry.Node = Op;
Tim Northoverf1450d82013-01-09 13:18:15 +0000126 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
Craig Topper8fe40e02015-10-22 17:05:00 +0000127 Entry.isSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
128 Entry.isZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
Tim Northoverf1450d82013-01-09 13:18:15 +0000129 Args.push_back(Entry);
130 }
Michael Kupersteineaa16002015-10-25 08:14:05 +0000131
Ahmed Bougachae85a2d32015-03-26 22:46:58 +0000132 if (LC == RTLIB::UNKNOWN_LIBCALL)
133 report_fatal_error("Unsupported library call operation!");
Mehdi Amini44ede332015-07-09 02:09:04 +0000134 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
135 getPointerTy(DAG.getDataLayout()));
Tim Northoverf1450d82013-01-09 13:18:15 +0000136
137 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +0000138 TargetLowering::CallLoweringInfo CLI(DAG);
Petar Jovanovic5b436222015-03-23 12:28:13 +0000139 bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned);
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +0000140 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Juergen Ributzka3bd03c72014-07-01 22:01:54 +0000141 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +0000142 .setNoReturn(doesNotReturn).setDiscardResult(!isReturnValueUsed)
Petar Jovanovic5b436222015-03-23 12:28:13 +0000143 .setSExtResult(signExtend).setZExtResult(!signExtend);
Michael Gottesman7a801722013-08-13 17:54:56 +0000144 return LowerCallTo(CLI);
Tim Northoverf1450d82013-01-09 13:18:15 +0000145}
146
Sanjay Patelac6e9102015-12-29 22:11:50 +0000147/// Soften the operands of a comparison. This code is shared among BR_CC,
148/// SELECT_CC, and SETCC handlers.
Tim Northoverf1450d82013-01-09 13:18:15 +0000149void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
150 SDValue &NewLHS, SDValue &NewRHS,
151 ISD::CondCode &CCCode,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000152 SDLoc dl) const {
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000153 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
Tim Northoverf1450d82013-01-09 13:18:15 +0000154 && "Unsupported setcc type!");
155
156 // Expand into one or more soft-fp libcall(s).
157 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
Alexey Bataevb9288602015-07-15 08:39:35 +0000158 bool ShouldInvertCC = false;
Tim Northoverf1450d82013-01-09 13:18:15 +0000159 switch (CCCode) {
160 case ISD::SETEQ:
161 case ISD::SETOEQ:
162 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000163 (VT == MVT::f64) ? RTLIB::OEQ_F64 :
164 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000165 break;
166 case ISD::SETNE:
167 case ISD::SETUNE:
168 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000169 (VT == MVT::f64) ? RTLIB::UNE_F64 :
170 (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000171 break;
172 case ISD::SETGE:
173 case ISD::SETOGE:
174 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000175 (VT == MVT::f64) ? RTLIB::OGE_F64 :
176 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000177 break;
178 case ISD::SETLT:
179 case ISD::SETOLT:
180 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000181 (VT == MVT::f64) ? RTLIB::OLT_F64 :
182 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000183 break;
184 case ISD::SETLE:
185 case ISD::SETOLE:
186 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000187 (VT == MVT::f64) ? RTLIB::OLE_F64 :
188 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000189 break;
190 case ISD::SETGT:
191 case ISD::SETOGT:
192 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000193 (VT == MVT::f64) ? RTLIB::OGT_F64 :
194 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000195 break;
196 case ISD::SETUO:
197 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000198 (VT == MVT::f64) ? RTLIB::UO_F64 :
199 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000200 break;
201 case ISD::SETO:
202 LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000203 (VT == MVT::f64) ? RTLIB::O_F64 :
204 (VT == MVT::f128) ? RTLIB::O_F128 : RTLIB::O_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000205 break;
Alexey Bataevb9288602015-07-15 08:39:35 +0000206 case ISD::SETONE:
207 // SETONE = SETOLT | SETOGT
208 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000209 (VT == MVT::f64) ? RTLIB::OLT_F64 :
210 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
Alexey Bataevb9288602015-07-15 08:39:35 +0000211 LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000212 (VT == MVT::f64) ? RTLIB::OGT_F64 :
213 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
Alexey Bataevb9288602015-07-15 08:39:35 +0000214 break;
215 case ISD::SETUEQ:
Tim Northoverf1450d82013-01-09 13:18:15 +0000216 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000217 (VT == MVT::f64) ? RTLIB::UO_F64 :
218 (VT == MVT::f128) ? RTLIB::UO_F64 : RTLIB::UO_PPCF128;
Alexey Bataevb9288602015-07-15 08:39:35 +0000219 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000220 (VT == MVT::f64) ? RTLIB::OEQ_F64 :
221 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
Alexey Bataevb9288602015-07-15 08:39:35 +0000222 break;
223 default:
224 // Invert CC for unordered comparisons
225 ShouldInvertCC = true;
Tim Northoverf1450d82013-01-09 13:18:15 +0000226 switch (CCCode) {
Alexey Bataevb9288602015-07-15 08:39:35 +0000227 case ISD::SETULT:
228 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000229 (VT == MVT::f64) ? RTLIB::OGE_F64 :
230 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000231 break;
Tim Northoverf1450d82013-01-09 13:18:15 +0000232 case ISD::SETULE:
Alexey Bataevb9288602015-07-15 08:39:35 +0000233 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000234 (VT == MVT::f64) ? RTLIB::OGT_F64 :
235 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
Alexey Bataevb9288602015-07-15 08:39:35 +0000236 break;
237 case ISD::SETUGT:
238 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000239 (VT == MVT::f64) ? RTLIB::OLE_F64 :
240 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000241 break;
Alexey Bataevb9288602015-07-15 08:39:35 +0000242 case ISD::SETUGE:
243 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
Petar Jovanovic23e44f52016-02-04 14:43:50 +0000244 (VT == MVT::f64) ? RTLIB::OLT_F64 :
245 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
Tim Northoverf1450d82013-01-09 13:18:15 +0000246 break;
247 default: llvm_unreachable("Do not know how to soften this setcc!");
248 }
249 }
250
251 // Use the target specific return value for comparions lib calls.
252 EVT RetVT = getCmpLibcallReturnType();
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +0000253 SDValue Ops[2] = {NewLHS, NewRHS};
Craig Topper8fe40e02015-10-22 17:05:00 +0000254 NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, false /*sign irrelevant*/,
255 dl).first;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000256 NewRHS = DAG.getConstant(0, dl, RetVT);
Alexey Bataevb9288602015-07-15 08:39:35 +0000257
Tim Northoverf1450d82013-01-09 13:18:15 +0000258 CCCode = getCmpLibcallCC(LC1);
Alexey Bataevb9288602015-07-15 08:39:35 +0000259 if (ShouldInvertCC)
260 CCCode = getSetCCInverse(CCCode, /*isInteger=*/true);
261
Tim Northoverf1450d82013-01-09 13:18:15 +0000262 if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
Mehdi Amini44ede332015-07-09 02:09:04 +0000263 SDValue Tmp = DAG.getNode(
264 ISD::SETCC, dl,
265 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
266 NewLHS, NewRHS, DAG.getCondCode(CCCode));
Craig Topper8fe40e02015-10-22 17:05:00 +0000267 NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, false/*sign irrelevant*/,
268 dl).first;
Mehdi Amini44ede332015-07-09 02:09:04 +0000269 NewLHS = DAG.getNode(
270 ISD::SETCC, dl,
271 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
272 NewLHS, NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
Tim Northoverf1450d82013-01-09 13:18:15 +0000273 NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
274 NewRHS = SDValue();
275 }
276}
277
Sanjay Patelac6e9102015-12-29 22:11:50 +0000278/// Return the entry encoding for a jump table in the current function. The
279/// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000280unsigned TargetLowering::getJumpTableEncoding() const {
281 // In non-pic modes, just use the address of a block.
282 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
283 return MachineJumpTableInfo::EK_BlockAddress;
Wesley Peck527da1b2010-11-23 03:31:01 +0000284
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000285 // In PIC mode, if the target supports a GPRel32 directive, use it.
Craig Topperc0196b12014-04-14 00:51:57 +0000286 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000287 return MachineJumpTableInfo::EK_GPRel32BlockAddress;
Wesley Peck527da1b2010-11-23 03:31:01 +0000288
Chris Lattnerb6db2c62010-01-25 23:26:13 +0000289 // Otherwise, use a label difference.
290 return MachineJumpTableInfo::EK_LabelDifference32;
291}
292
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000293SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
294 SelectionDAG &DAG) const {
Chris Lattner547c7612010-01-26 06:53:37 +0000295 // If our PIC model is GP relative, use the global offset table as the base.
Akira Hatanaka8483a6c2012-04-09 20:32:12 +0000296 unsigned JTEncoding = getJumpTableEncoding();
297
298 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
299 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
Mehdi Amini44ede332015-07-09 02:09:04 +0000300 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
Akira Hatanaka8483a6c2012-04-09 20:32:12 +0000301
Evan Cheng797d56f2007-11-09 01:32:10 +0000302 return Table;
303}
304
Sanjay Patelac6e9102015-12-29 22:11:50 +0000305/// This returns the relocation base for the given PIC jumptable, the same as
306/// getPICJumpTableRelocBase, but as an MCExpr.
Chris Lattner8a6c1ea2010-01-26 05:30:30 +0000307const MCExpr *
Chris Lattner8a785d72010-01-26 06:28:43 +0000308TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
309 unsigned JTI,MCContext &Ctx) const{
Chris Lattner273735b2010-01-26 05:58:28 +0000310 // The normal PIC reloc base is the label at the start of the jump table.
Jim Grosbach13760bd2015-05-30 01:25:56 +0000311 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
Chris Lattner8a6c1ea2010-01-26 05:30:30 +0000312}
313
Dan Gohman2fe6bee2008-10-18 02:06:02 +0000314bool
315TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
316 // Assume that everything is safe in static mode.
317 if (getTargetMachine().getRelocationModel() == Reloc::Static)
318 return true;
319
320 // In dynamic-no-pic mode, assume that known defined values are safe.
321 if (getTargetMachine().getRelocationModel() == Reloc::DynamicNoPIC &&
Peter Collingbourne6a9d1772015-07-05 20:52:35 +0000322 GA && GA->getGlobal()->isStrongDefinitionForLinker())
Dan Gohman2fe6bee2008-10-18 02:06:02 +0000323 return true;
324
325 // Otherwise assume nothing is safe.
326 return false;
327}
328
Chris Lattneree1dadb2006-02-04 02:13:02 +0000329//===----------------------------------------------------------------------===//
330// Optimization Methods
331//===----------------------------------------------------------------------===//
332
Sanjay Patelac6e9102015-12-29 22:11:50 +0000333/// Check to see if the specified operand of the specified instruction is a
334/// constant integer. If so, check to see if there are any bits set in the
335/// constant that are not demanded. If so, shrink the constant and return true.
Wesley Peck527da1b2010-11-23 03:31:01 +0000336bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDValue Op,
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000337 const APInt &Demanded) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000338 SDLoc dl(Op);
Bill Wendling6d271472009-03-04 00:18:06 +0000339
Chris Lattner118ddba2006-02-26 23:36:02 +0000340 // FIXME: ISD::SELECT, ISD::SELECT_CC
Dan Gohmane58ab792009-01-29 01:59:02 +0000341 switch (Op.getOpcode()) {
Nate Begeman8a77efe2006-02-16 21:11:51 +0000342 default: break;
Nate Begeman8a77efe2006-02-16 21:11:51 +0000343 case ISD::XOR:
Bill Wendling6d271472009-03-04 00:18:06 +0000344 case ISD::AND:
345 case ISD::OR: {
346 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
347 if (!C) return false;
348
349 if (Op.getOpcode() == ISD::XOR &&
350 (C->getAPIntValue() | (~Demanded)).isAllOnesValue())
351 return false;
352
353 // if we can expand it to have all bits set, do it
354 if (C->getAPIntValue().intersects(~Demanded)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000355 EVT VT = Op.getValueType();
Bill Wendling6d271472009-03-04 00:18:06 +0000356 SDValue New = DAG.getNode(Op.getOpcode(), dl, VT, Op.getOperand(0),
357 DAG.getConstant(Demanded &
Wesley Peck527da1b2010-11-23 03:31:01 +0000358 C->getAPIntValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000359 dl, VT));
Bill Wendling6d271472009-03-04 00:18:06 +0000360 return CombineTo(Op, New);
361 }
362
Nate Begemandc7bba92006-02-03 22:24:05 +0000363 break;
364 }
Bill Wendling6d271472009-03-04 00:18:06 +0000365 }
366
Nate Begemandc7bba92006-02-03 22:24:05 +0000367 return false;
368}
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000369
Sanjay Patelac6e9102015-12-29 22:11:50 +0000370/// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
371/// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
372/// generalized for targets with other types of implicit widening casts.
Dan Gohmanad3e5492009-04-08 00:15:30 +0000373bool
374TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op,
375 unsigned BitWidth,
376 const APInt &Demanded,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000377 SDLoc dl) {
Dan Gohmanad3e5492009-04-08 00:15:30 +0000378 assert(Op.getNumOperands() == 2 &&
379 "ShrinkDemandedOp only supports binary operators!");
380 assert(Op.getNode()->getNumValues() == 1 &&
381 "ShrinkDemandedOp only supports nodes with one result!");
382
Hao Liu40914502014-05-29 09:19:07 +0000383 // Early return, as this function cannot handle vector types.
384 if (Op.getValueType().isVector())
385 return false;
386
Dan Gohmanad3e5492009-04-08 00:15:30 +0000387 // Don't do this if the node has another user, which may require the
388 // full value.
389 if (!Op.getNode()->hasOneUse())
390 return false;
391
392 // Search for the smallest integer type with free casts to and from
393 // Op's type. For expedience, just check power-of-2 integer types.
394 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Nadav Rotem33360d82012-12-19 07:39:08 +0000395 unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros();
396 unsigned SmallVTBits = DemandedSize;
Dan Gohmanad3e5492009-04-08 00:15:30 +0000397 if (!isPowerOf2_32(SmallVTBits))
398 SmallVTBits = NextPowerOf2(SmallVTBits);
399 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
Owen Anderson117c9e82009-08-12 00:36:31 +0000400 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
Dan Gohmanad3e5492009-04-08 00:15:30 +0000401 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
402 TLI.isZExtFree(SmallVT, Op.getValueType())) {
403 // We found a type with free casts.
404 SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
405 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
406 Op.getNode()->getOperand(0)),
407 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
408 Op.getNode()->getOperand(1)));
Nadav Rotem33360d82012-12-19 07:39:08 +0000409 bool NeedZext = DemandedSize > SmallVTBits;
410 SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND,
411 dl, Op.getValueType(), X);
Dan Gohmanad3e5492009-04-08 00:15:30 +0000412 return CombineTo(Op, Z);
413 }
414 }
415 return false;
416}
417
Sanjay Patelac6e9102015-12-29 22:11:50 +0000418/// Look at Op. At this point, we know that only the DemandedMask bits of the
419/// result of Op are ever used downstream. If we can use this information to
420/// simplify Op, create a new simplified DAG node and return true, returning the
421/// original and new nodes in Old and New. Otherwise, analyze the expression and
422/// return a mask of KnownOne and KnownZero bits for the expression (used to
423/// simplify the caller). The KnownZero/One bits may only be accurate for those
424/// bits in the DemandedMask.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000425bool TargetLowering::SimplifyDemandedBits(SDValue Op,
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000426 const APInt &DemandedMask,
427 APInt &KnownZero,
428 APInt &KnownOne,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000429 TargetLoweringOpt &TLO,
430 unsigned Depth) const {
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000431 unsigned BitWidth = DemandedMask.getBitWidth();
Dan Gohman1d459e42009-12-11 21:31:27 +0000432 assert(Op.getValueType().getScalarType().getSizeInBits() == BitWidth &&
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000433 "Mask size mismatches value type size!");
434 APInt NewMask = DemandedMask;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000435 SDLoc dl(Op);
Mehdi Amini9639d652015-07-09 02:09:20 +0000436 auto &DL = TLO.DAG.getDataLayout();
Chris Lattner0184f882007-05-17 18:19:23 +0000437
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000438 // Don't know anything.
439 KnownZero = KnownOne = APInt(BitWidth, 0);
440
Nate Begeman8a77efe2006-02-16 21:11:51 +0000441 // Other users may use these bits.
Wesley Peck527da1b2010-11-23 03:31:01 +0000442 if (!Op.getNode()->hasOneUse()) {
Nate Begeman8a77efe2006-02-16 21:11:51 +0000443 if (Depth != 0) {
Wesley Peck527da1b2010-11-23 03:31:01 +0000444 // If not at the root, Just compute the KnownZero/KnownOne bits to
Nate Begeman8a77efe2006-02-16 21:11:51 +0000445 // simplify things downstream.
Jay Foada0653a32014-05-14 21:14:37 +0000446 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
Nate Begeman8a77efe2006-02-16 21:11:51 +0000447 return false;
448 }
449 // If this is the root being simplified, allow it to have multiple uses,
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000450 // just set the NewMask to all bits.
451 NewMask = APInt::getAllOnesValue(BitWidth);
Wesley Peck527da1b2010-11-23 03:31:01 +0000452 } else if (DemandedMask == 0) {
Nate Begeman8a77efe2006-02-16 21:11:51 +0000453 // Not demanding any bits from Op.
Sanjay Patel75068522016-03-14 18:09:43 +0000454 if (!Op.isUndef())
Dale Johannesen84935752009-02-06 23:05:02 +0000455 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000456 return false;
457 } else if (Depth == 6) { // Limit search depth.
458 return false;
459 }
460
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000461 APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000462 switch (Op.getOpcode()) {
463 case ISD::Constant:
Nate Begeman8a77efe2006-02-16 21:11:51 +0000464 // We know all of the bits for a constant!
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000465 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
466 KnownZero = ~KnownOne;
Chris Lattner118ddba2006-02-26 23:36:02 +0000467 return false; // Don't fall through, will infinitely loop.
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000468 case ISD::AND:
Chris Lattnera60751d2006-02-27 00:36:27 +0000469 // If the RHS is a constant, check to see if the LHS would be zero without
470 // using the bits from the RHS. Below, we use knowledge about the RHS to
471 // simplify the LHS, here we're using information from the LHS to simplify
472 // the RHS.
473 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000474 APInt LHSZero, LHSOne;
Dale Johannesend2b48112011-01-10 21:53:07 +0000475 // Do not increment Depth here; that can cause an infinite loop.
Jay Foada0653a32014-05-14 21:14:37 +0000476 TLO.DAG.computeKnownBits(Op.getOperand(0), LHSZero, LHSOne, Depth);
Chris Lattnera60751d2006-02-27 00:36:27 +0000477 // If the LHS already has zeros where RHSC does, this and is dead.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000478 if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
Chris Lattnera60751d2006-02-27 00:36:27 +0000479 return TLO.CombineTo(Op, Op.getOperand(0));
480 // If any of the set bits in the RHS are known zero on the LHS, shrink
481 // the constant.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000482 if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
Chris Lattnera60751d2006-02-27 00:36:27 +0000483 return true;
484 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000485
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000486 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000487 KnownOne, TLO, Depth+1))
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000488 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000489 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000490 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000491 KnownZero2, KnownOne2, TLO, Depth+1))
492 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000493 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
494
Nate Begeman8a77efe2006-02-16 21:11:51 +0000495 // If all of the demanded bits are known one on one side, return the other.
496 // These bits cannot contribute to the result of the 'and'.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000497 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000498 return TLO.CombineTo(Op, Op.getOperand(0));
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000499 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000500 return TLO.CombineTo(Op, Op.getOperand(1));
501 // If all of the demanded bits in the inputs are known zeros, return zero.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000502 if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000503 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, Op.getValueType()));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000504 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000505 if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000506 return true;
Dan Gohmanad3e5492009-04-08 00:15:30 +0000507 // If the operation can be done in a smaller type, do so.
Dan Gohman600f62b2010-06-24 14:30:44 +0000508 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
Dan Gohmanad3e5492009-04-08 00:15:30 +0000509 return true;
510
Nate Begeman8a77efe2006-02-16 21:11:51 +0000511 // Output known-1 bits are only known if set in both the LHS & RHS.
512 KnownOne &= KnownOne2;
513 // Output known-0 are known to be clear if zero in either the LHS | RHS.
514 KnownZero |= KnownZero2;
515 break;
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000516 case ISD::OR:
Wesley Peck527da1b2010-11-23 03:31:01 +0000517 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000518 KnownOne, TLO, Depth+1))
519 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000520 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000521 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000522 KnownZero2, KnownOne2, TLO, Depth+1))
523 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000524 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
525
Nate Begeman8a77efe2006-02-16 21:11:51 +0000526 // If all of the demanded bits are known zero on one side, return the other.
527 // These bits cannot contribute to the result of the 'or'.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000528 if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000529 return TLO.CombineTo(Op, Op.getOperand(0));
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000530 if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000531 return TLO.CombineTo(Op, Op.getOperand(1));
532 // If all of the potentially set bits on one side are known to be set on
533 // the other side, just use the 'other' side.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000534 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000535 return TLO.CombineTo(Op, Op.getOperand(0));
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000536 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000537 return TLO.CombineTo(Op, Op.getOperand(1));
538 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000539 if (TLO.ShrinkDemandedConstant(Op, NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000540 return true;
Dan Gohmanad3e5492009-04-08 00:15:30 +0000541 // If the operation can be done in a smaller type, do so.
Dan Gohman600f62b2010-06-24 14:30:44 +0000542 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
Dan Gohmanad3e5492009-04-08 00:15:30 +0000543 return true;
544
Nate Begeman8a77efe2006-02-16 21:11:51 +0000545 // Output known-0 bits are only known if clear in both the LHS & RHS.
546 KnownZero &= KnownZero2;
547 // Output known-1 are known to be set if set in either the LHS | RHS.
548 KnownOne |= KnownOne2;
549 break;
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000550 case ISD::XOR:
Wesley Peck527da1b2010-11-23 03:31:01 +0000551 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000552 KnownOne, TLO, Depth+1))
553 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000554 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000555 if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000556 KnownOne2, TLO, Depth+1))
557 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000558 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
559
Nate Begeman8a77efe2006-02-16 21:11:51 +0000560 // If all of the demanded bits are known zero on one side, return the other.
561 // These bits cannot contribute to the result of the 'xor'.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000562 if ((KnownZero & NewMask) == NewMask)
Nate Begeman8a77efe2006-02-16 21:11:51 +0000563 return TLO.CombineTo(Op, Op.getOperand(0));
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000564 if ((KnownZero2 & NewMask) == NewMask)
Nate Begeman8a77efe2006-02-16 21:11:51 +0000565 return TLO.CombineTo(Op, Op.getOperand(1));
Dan Gohmanad3e5492009-04-08 00:15:30 +0000566 // If the operation can be done in a smaller type, do so.
Dan Gohman600f62b2010-06-24 14:30:44 +0000567 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
Dan Gohmanad3e5492009-04-08 00:15:30 +0000568 return true;
569
Chris Lattner5d5916b2006-11-27 21:50:02 +0000570 // If all of the unknown bits are known to be zero on one side or the other
571 // (but not both) turn this into an *inclusive* or.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000572 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000573 if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
Dale Johannesen400dc2e2009-02-06 21:50:26 +0000574 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
Chris Lattner5d5916b2006-11-27 21:50:02 +0000575 Op.getOperand(0),
576 Op.getOperand(1)));
Wesley Peck527da1b2010-11-23 03:31:01 +0000577
Nate Begeman8a77efe2006-02-16 21:11:51 +0000578 // Output known-0 bits are known if clear or set in both the LHS & RHS.
579 KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
580 // Output known-1 are known to be set if set in only one of the LHS, RHS.
581 KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
Wesley Peck527da1b2010-11-23 03:31:01 +0000582
Nate Begeman8a77efe2006-02-16 21:11:51 +0000583 // If all of the demanded bits on one side are known, and all of the set
584 // bits on that side are also known to be set on the other side, turn this
585 // into an AND, as we know the bits will be cleared.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000586 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Joel Jones828531f2012-04-17 22:23:10 +0000587 // NB: it is okay if more bits are known than are requested
Stephen Lincfe7f352013-07-08 00:37:03 +0000588 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side
Joel Jones828531f2012-04-17 22:23:10 +0000589 if (KnownOne == KnownOne2) { // set bits are the same on both sides
Owen Anderson53aa7a92009-08-10 22:56:29 +0000590 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000591 SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, dl, VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000592 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
Dale Johannesenf1163e92009-02-03 00:47:48 +0000593 Op.getOperand(0), ANDC));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000594 }
595 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000596
Nate Begeman8a77efe2006-02-16 21:11:51 +0000597 // If the RHS is a constant, see if we can simplify it.
Torok Edwin613d7af2008-04-06 21:23:02 +0000598 // for XOR, we prefer to force bits to 1 if they will make a -1.
599 // if we can't force bits, try to shrink constant
600 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
601 APInt Expanded = C->getAPIntValue() | (~NewMask);
602 // if we can expand it to have all bits set, do it
603 if (Expanded.isAllOnesValue()) {
604 if (Expanded != C->getAPIntValue()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000605 EVT VT = Op.getValueType();
Dale Johannesenf1163e92009-02-03 00:47:48 +0000606 SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000607 TLO.DAG.getConstant(Expanded, dl, VT));
Torok Edwin613d7af2008-04-06 21:23:02 +0000608 return TLO.CombineTo(Op, New);
609 }
610 // if it already has all the bits set, nothing to change
611 // but don't shrink either!
612 } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
613 return true;
614 }
615 }
616
Nate Begeman8a77efe2006-02-16 21:11:51 +0000617 KnownZero = KnownZeroOut;
618 KnownOne = KnownOneOut;
619 break;
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000620 case ISD::SELECT:
Wesley Peck527da1b2010-11-23 03:31:01 +0000621 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000622 KnownOne, TLO, Depth+1))
623 return true;
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000624 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000625 KnownOne2, TLO, Depth+1))
626 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000627 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
628 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
629
Nate Begeman8a77efe2006-02-16 21:11:51 +0000630 // If the operands are constants, see if we can simplify them.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000631 if (TLO.ShrinkDemandedConstant(Op, NewMask))
Nate Begeman8a77efe2006-02-16 21:11:51 +0000632 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000633
Nate Begeman8a77efe2006-02-16 21:11:51 +0000634 // Only known if known in both the LHS and RHS.
635 KnownOne &= KnownOne2;
636 KnownZero &= KnownZero2;
637 break;
Chris Lattner118ddba2006-02-26 23:36:02 +0000638 case ISD::SELECT_CC:
Wesley Peck527da1b2010-11-23 03:31:01 +0000639 if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
Chris Lattner118ddba2006-02-26 23:36:02 +0000640 KnownOne, TLO, Depth+1))
641 return true;
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000642 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
Chris Lattner118ddba2006-02-26 23:36:02 +0000643 KnownOne2, TLO, Depth+1))
644 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000645 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
646 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
647
Chris Lattner118ddba2006-02-26 23:36:02 +0000648 // If the operands are constants, see if we can simplify them.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000649 if (TLO.ShrinkDemandedConstant(Op, NewMask))
Chris Lattner118ddba2006-02-26 23:36:02 +0000650 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000651
Chris Lattner118ddba2006-02-26 23:36:02 +0000652 // Only known if known in both the LHS and RHS.
653 KnownOne &= KnownOne2;
654 KnownZero &= KnownZero2;
655 break;
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000656 case ISD::SHL:
Nate Begeman8a77efe2006-02-16 21:11:51 +0000657 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +0000658 unsigned ShAmt = SA->getZExtValue();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000659 SDValue InOp = Op.getOperand(0);
Chris Lattner9a861a82007-04-17 21:14:16 +0000660
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000661 // If the shift count is an invalid immediate, don't do anything.
662 if (ShAmt >= BitWidth)
663 break;
664
Chris Lattner9a861a82007-04-17 21:14:16 +0000665 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
666 // single shift. We can do this if the bottom bits (which are shifted
667 // out) are never demanded.
668 if (InOp.getOpcode() == ISD::SRL &&
669 isa<ConstantSDNode>(InOp.getOperand(1))) {
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000670 if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
Dan Gohmaneffb8942008-09-12 16:56:44 +0000671 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
Chris Lattner9a861a82007-04-17 21:14:16 +0000672 unsigned Opc = ISD::SHL;
673 int Diff = ShAmt-C1;
674 if (Diff < 0) {
675 Diff = -Diff;
676 Opc = ISD::SRL;
Wesley Peck527da1b2010-11-23 03:31:01 +0000677 }
678
679 SDValue NewSA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000680 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
Owen Anderson53aa7a92009-08-10 22:56:29 +0000681 EVT VT = Op.getValueType();
Dale Johannesenf1163e92009-02-03 00:47:48 +0000682 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
Chris Lattner9a861a82007-04-17 21:14:16 +0000683 InOp.getOperand(0), NewSA));
684 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000685 }
686
Dan Gohman08186842010-07-23 18:03:30 +0000687 if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt),
Nate Begeman8a77efe2006-02-16 21:11:51 +0000688 KnownZero, KnownOne, TLO, Depth+1))
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000689 return true;
Dan Gohman08186842010-07-23 18:03:30 +0000690
691 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
692 // are not demanded. This will likely allow the anyext to be folded away.
693 if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
694 SDValue InnerOp = InOp.getNode()->getOperand(0);
695 EVT InnerVT = InnerOp.getValueType();
Eli Friedman053a7242011-12-09 01:16:26 +0000696 unsigned InnerBits = InnerVT.getSizeInBits();
697 if (ShAmt < InnerBits && NewMask.lshr(InnerBits) == 0 &&
Dan Gohman08186842010-07-23 18:03:30 +0000698 isTypeDesirableForOp(ISD::SHL, InnerVT)) {
Mehdi Amini9639d652015-07-09 02:09:20 +0000699 EVT ShTy = getShiftAmountTy(InnerVT, DL);
Dan Gohman55e24462010-07-23 21:08:12 +0000700 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
701 ShTy = InnerVT;
Dan Gohman08186842010-07-23 18:03:30 +0000702 SDValue NarrowShl =
703 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000704 TLO.DAG.getConstant(ShAmt, dl, ShTy));
Dan Gohman08186842010-07-23 18:03:30 +0000705 return
706 TLO.CombineTo(Op,
707 TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(),
708 NarrowShl));
709 }
Richard Sandiford374a0e52013-10-16 10:26:19 +0000710 // Repeat the SHL optimization above in cases where an extension
711 // intervenes: (shl (anyext (shr x, c1)), c2) to
712 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits
713 // aren't demanded (as above) and that the shifted upper c1 bits of
714 // x aren't demanded.
715 if (InOp.hasOneUse() &&
716 InnerOp.getOpcode() == ISD::SRL &&
717 InnerOp.hasOneUse() &&
718 isa<ConstantSDNode>(InnerOp.getOperand(1))) {
719 uint64_t InnerShAmt = cast<ConstantSDNode>(InnerOp.getOperand(1))
720 ->getZExtValue();
721 if (InnerShAmt < ShAmt &&
722 InnerShAmt < InnerBits &&
723 NewMask.lshr(InnerBits - InnerShAmt + ShAmt) == 0 &&
724 NewMask.trunc(ShAmt) == 0) {
725 SDValue NewSA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000726 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl,
Richard Sandiford374a0e52013-10-16 10:26:19 +0000727 Op.getOperand(1).getValueType());
728 EVT VT = Op.getValueType();
729 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
730 InnerOp.getOperand(0));
731 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT,
732 NewExt, NewSA));
733 }
734 }
Dan Gohman08186842010-07-23 18:03:30 +0000735 }
736
Dan Gohmaneffb8942008-09-12 16:56:44 +0000737 KnownZero <<= SA->getZExtValue();
738 KnownOne <<= SA->getZExtValue();
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000739 // low bits known zero.
Dan Gohmaneffb8942008-09-12 16:56:44 +0000740 KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue());
Chris Lattnerf0b24d22006-01-30 04:09:27 +0000741 }
742 break;
Nate Begeman8a77efe2006-02-16 21:11:51 +0000743 case ISD::SRL:
744 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000745 EVT VT = Op.getValueType();
Dan Gohmaneffb8942008-09-12 16:56:44 +0000746 unsigned ShAmt = SA->getZExtValue();
Duncan Sands13237ac2008-06-06 12:08:01 +0000747 unsigned VTSize = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000748 SDValue InOp = Op.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +0000749
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000750 // If the shift count is an invalid immediate, don't do anything.
751 if (ShAmt >= BitWidth)
752 break;
753
Benjamin Kramer1dcd8b02015-06-26 16:59:31 +0000754 APInt InDemandedMask = (NewMask << ShAmt);
755
756 // If the shift is exact, then it does demand the low bits (and knows that
757 // they are zero).
758 if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
759 InDemandedMask |= APInt::getLowBitsSet(BitWidth, ShAmt);
760
Chris Lattner9a861a82007-04-17 21:14:16 +0000761 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
762 // single shift. We can do this if the top bits (which are shifted out)
763 // are never demanded.
764 if (InOp.getOpcode() == ISD::SHL &&
765 isa<ConstantSDNode>(InOp.getOperand(1))) {
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000766 if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
Dan Gohmaneffb8942008-09-12 16:56:44 +0000767 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
Chris Lattner9a861a82007-04-17 21:14:16 +0000768 unsigned Opc = ISD::SRL;
769 int Diff = ShAmt-C1;
770 if (Diff < 0) {
771 Diff = -Diff;
772 Opc = ISD::SHL;
Wesley Peck527da1b2010-11-23 03:31:01 +0000773 }
774
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000775 SDValue NewSA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000776 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
Dale Johannesenf1163e92009-02-03 00:47:48 +0000777 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
Chris Lattner9a861a82007-04-17 21:14:16 +0000778 InOp.getOperand(0), NewSA));
779 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000780 }
781
Nate Begeman8a77efe2006-02-16 21:11:51 +0000782 // Compute the new bits that are at the top now.
Benjamin Kramer1dcd8b02015-06-26 16:59:31 +0000783 if (SimplifyDemandedBits(InOp, InDemandedMask,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000784 KnownZero, KnownOne, TLO, Depth+1))
785 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000786 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000787 KnownZero = KnownZero.lshr(ShAmt);
788 KnownOne = KnownOne.lshr(ShAmt);
Chris Lattnerc5bb8ab2006-06-13 16:52:37 +0000789
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000790 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
Chris Lattnerc5bb8ab2006-06-13 16:52:37 +0000791 KnownZero |= HighBits; // High bits known zero.
Nate Begeman8a77efe2006-02-16 21:11:51 +0000792 }
793 break;
794 case ISD::SRA:
Dan Gohmane58ab792009-01-29 01:59:02 +0000795 // If this is an arithmetic shift right and only the low-bit is set, we can
796 // always convert this into a logical shr, even if the shift amount is
797 // variable. The low bit of the shift cannot be an input sign bit unless
798 // the shift amount is >= the size of the datatype, which is undefined.
Eli Friedman053a7242011-12-09 01:16:26 +0000799 if (NewMask == 1)
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000800 return TLO.CombineTo(Op,
801 TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
802 Op.getOperand(0), Op.getOperand(1)));
Dan Gohmane58ab792009-01-29 01:59:02 +0000803
Nate Begeman8a77efe2006-02-16 21:11:51 +0000804 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000805 EVT VT = Op.getValueType();
Dan Gohmaneffb8942008-09-12 16:56:44 +0000806 unsigned ShAmt = SA->getZExtValue();
Wesley Peck527da1b2010-11-23 03:31:01 +0000807
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000808 // If the shift count is an invalid immediate, don't do anything.
809 if (ShAmt >= BitWidth)
810 break;
811
812 APInt InDemandedMask = (NewMask << ShAmt);
Chris Lattner10c65372006-05-08 17:22:53 +0000813
Benjamin Kramer1dcd8b02015-06-26 16:59:31 +0000814 // If the shift is exact, then it does demand the low bits (and knows that
815 // they are zero).
816 if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
817 InDemandedMask |= APInt::getLowBitsSet(BitWidth, ShAmt);
818
Chris Lattner10c65372006-05-08 17:22:53 +0000819 // If any of the demanded bits are produced by the sign extension, we also
820 // demand the input sign bit.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000821 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
822 if (HighBits.intersects(NewMask))
Dan Gohman1d459e42009-12-11 21:31:27 +0000823 InDemandedMask |= APInt::getSignBit(VT.getScalarType().getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +0000824
Chris Lattner10c65372006-05-08 17:22:53 +0000825 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
Nate Begeman8a77efe2006-02-16 21:11:51 +0000826 KnownZero, KnownOne, TLO, Depth+1))
827 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000828 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000829 KnownZero = KnownZero.lshr(ShAmt);
830 KnownOne = KnownOne.lshr(ShAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +0000831
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000832 // Handle the sign bit, adjusted to where it is now in the mask.
833 APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +0000834
Nate Begeman8a77efe2006-02-16 21:11:51 +0000835 // If the input sign bit is known to be zero, or if none of the top bits
836 // are demanded, turn this into an unsigned shift right.
Benjamin Kramerc2ae7672015-06-26 14:51:49 +0000837 if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) {
838 SDNodeFlags Flags;
839 Flags.setExact(cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact());
840 return TLO.CombineTo(Op,
841 TLO.DAG.getNode(ISD::SRL, dl, VT, Op.getOperand(0),
842 Op.getOperand(1), &Flags));
843 }
Richard Sandiford95f7ba92013-10-17 11:16:57 +0000844
845 int Log2 = NewMask.exactLogBase2();
846 if (Log2 >= 0) {
847 // The bit must come from the sign.
848 SDValue NewSA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000849 TLO.DAG.getConstant(BitWidth - 1 - Log2, dl,
Richard Sandiford95f7ba92013-10-17 11:16:57 +0000850 Op.getOperand(1).getValueType());
851 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
852 Op.getOperand(0), NewSA));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000853 }
Richard Sandiford95f7ba92013-10-17 11:16:57 +0000854
855 if (KnownOne.intersects(SignBit))
856 // New bits are known one.
857 KnownOne |= HighBits;
Nate Begeman8a77efe2006-02-16 21:11:51 +0000858 }
859 break;
860 case ISD::SIGN_EXTEND_INREG: {
Nadav Rotem57935242012-01-15 19:27:55 +0000861 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
862
863 APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1);
864 // If we only care about the highest bit, don't bother shifting right.
Michael Kupersteinaf9befa2015-02-18 09:43:40 +0000865 if (MsbMask == NewMask) {
Nadav Rotem57935242012-01-15 19:27:55 +0000866 unsigned ShAmt = ExVT.getScalarType().getSizeInBits();
867 SDValue InOp = Op.getOperand(0);
Michael Kupersteinaf9befa2015-02-18 09:43:40 +0000868 unsigned VTBits = Op->getValueType(0).getScalarType().getSizeInBits();
869 bool AlreadySignExtended =
870 TLO.DAG.ComputeNumSignBits(InOp) >= VTBits-ShAmt+1;
871 // However if the input is already sign extended we expect the sign
872 // extension to be dropped altogether later and do not simplify.
873 if (!AlreadySignExtended) {
874 // Compute the correct shift amount type, which must be getShiftAmountTy
875 // for scalar types after legalization.
876 EVT ShiftAmtTy = Op.getValueType();
877 if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
Mehdi Amini9639d652015-07-09 02:09:20 +0000878 ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL);
Eli Friedman18a4c312012-01-31 01:08:03 +0000879
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000880 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, dl,
881 ShiftAmtTy);
Michael Kupersteinaf9befa2015-02-18 09:43:40 +0000882 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
883 Op.getValueType(), InOp,
884 ShiftAmt));
885 }
Nadav Rotem57935242012-01-15 19:27:55 +0000886 }
Nate Begeman8a77efe2006-02-16 21:11:51 +0000887
Wesley Peck527da1b2010-11-23 03:31:01 +0000888 // Sign extension. Compute the demanded bits in the result that are not
Nate Begeman8a77efe2006-02-16 21:11:51 +0000889 // present in the input.
Dan Gohman6bd3ef82010-01-09 02:13:55 +0000890 APInt NewBits =
891 APInt::getHighBitsSet(BitWidth,
Nadav Rotem57935242012-01-15 19:27:55 +0000892 BitWidth - ExVT.getScalarType().getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +0000893
Chris Lattner118ddba2006-02-26 23:36:02 +0000894 // If none of the extended bits are demanded, eliminate the sextinreg.
Eli Friedman460ad412010-08-02 04:42:25 +0000895 if ((NewBits & NewMask) == 0)
Chris Lattner118ddba2006-02-26 23:36:02 +0000896 return TLO.CombineTo(Op, Op.getOperand(0));
897
Jay Foad583abbc2010-12-07 08:25:19 +0000898 APInt InSignBit =
Nadav Rotem57935242012-01-15 19:27:55 +0000899 APInt::getSignBit(ExVT.getScalarType().getSizeInBits()).zext(BitWidth);
Dan Gohman6bd3ef82010-01-09 02:13:55 +0000900 APInt InputDemandedBits =
901 APInt::getLowBitsSet(BitWidth,
Nadav Rotem57935242012-01-15 19:27:55 +0000902 ExVT.getScalarType().getSizeInBits()) &
Dan Gohman6bd3ef82010-01-09 02:13:55 +0000903 NewMask;
Wesley Peck527da1b2010-11-23 03:31:01 +0000904
Chris Lattner118ddba2006-02-26 23:36:02 +0000905 // Since the sign extended bits are demanded, we know that the sign
Nate Begeman8a77efe2006-02-16 21:11:51 +0000906 // bit is demanded.
Chris Lattner118ddba2006-02-26 23:36:02 +0000907 InputDemandedBits |= InSignBit;
Nate Begeman8a77efe2006-02-16 21:11:51 +0000908
909 if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
910 KnownZero, KnownOne, TLO, Depth+1))
911 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000912 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Nate Begeman8a77efe2006-02-16 21:11:51 +0000913
914 // If the sign bit of the input is known set or clear, then we know the
915 // top bits of the result.
Wesley Peck527da1b2010-11-23 03:31:01 +0000916
Chris Lattner118ddba2006-02-26 23:36:02 +0000917 // If the input sign bit is known zero, convert this into a zero extension.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000918 if (KnownZero.intersects(InSignBit))
Wesley Peck527da1b2010-11-23 03:31:01 +0000919 return TLO.CombineTo(Op,
Nadav Rotem57935242012-01-15 19:27:55 +0000920 TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,ExVT));
Wesley Peck527da1b2010-11-23 03:31:01 +0000921
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000922 if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
Nate Begeman8a77efe2006-02-16 21:11:51 +0000923 KnownOne |= NewBits;
924 KnownZero &= ~NewBits;
Chris Lattner118ddba2006-02-26 23:36:02 +0000925 } else { // Input sign bit unknown
Nate Begeman8a77efe2006-02-16 21:11:51 +0000926 KnownZero &= ~NewBits;
927 KnownOne &= ~NewBits;
928 }
929 break;
930 }
Matt Arsenault2adca602014-05-12 17:14:48 +0000931 case ISD::BUILD_PAIR: {
932 EVT HalfVT = Op.getOperand(0).getValueType();
933 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
934
935 APInt MaskLo = NewMask.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
936 APInt MaskHi = NewMask.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
937
938 APInt KnownZeroLo, KnownOneLo;
939 APInt KnownZeroHi, KnownOneHi;
940
941 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownZeroLo,
942 KnownOneLo, TLO, Depth + 1))
943 return true;
944
945 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownZeroHi,
946 KnownOneHi, TLO, Depth + 1))
947 return true;
948
949 KnownZero = KnownZeroLo.zext(BitWidth) |
950 KnownZeroHi.zext(BitWidth).shl(HalfBitWidth);
951
952 KnownOne = KnownOneLo.zext(BitWidth) |
953 KnownOneHi.zext(BitWidth).shl(HalfBitWidth);
954 break;
955 }
Chris Lattner118ddba2006-02-26 23:36:02 +0000956 case ISD::ZERO_EXTEND: {
Dan Gohman6bd3ef82010-01-09 02:13:55 +0000957 unsigned OperandBitWidth =
958 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
Jay Foad583abbc2010-12-07 08:25:19 +0000959 APInt InMask = NewMask.trunc(OperandBitWidth);
Wesley Peck527da1b2010-11-23 03:31:01 +0000960
Chris Lattner118ddba2006-02-26 23:36:02 +0000961 // If none of the top bits are demanded, convert this into an any_extend.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000962 APInt NewBits =
963 APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
964 if (!NewBits.intersects(NewMask))
Dale Johannesenf1163e92009-02-03 00:47:48 +0000965 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
Wesley Peck527da1b2010-11-23 03:31:01 +0000966 Op.getValueType(),
Chris Lattner118ddba2006-02-26 23:36:02 +0000967 Op.getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +0000968
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000969 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
Chris Lattner118ddba2006-02-26 23:36:02 +0000970 KnownZero, KnownOne, TLO, Depth+1))
971 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +0000972 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Jay Foad583abbc2010-12-07 08:25:19 +0000973 KnownZero = KnownZero.zext(BitWidth);
974 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner118ddba2006-02-26 23:36:02 +0000975 KnownZero |= NewBits;
976 break;
977 }
978 case ISD::SIGN_EXTEND: {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000979 EVT InVT = Op.getOperand(0).getValueType();
Dan Gohman6bd3ef82010-01-09 02:13:55 +0000980 unsigned InBits = InVT.getScalarType().getSizeInBits();
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000981 APInt InMask = APInt::getLowBitsSet(BitWidth, InBits);
Dan Gohman44b4c072008-03-11 21:29:43 +0000982 APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000983 APInt NewBits = ~InMask & NewMask;
Wesley Peck527da1b2010-11-23 03:31:01 +0000984
Chris Lattner118ddba2006-02-26 23:36:02 +0000985 // If none of the top bits are demanded, convert this into an any_extend.
986 if (NewBits == 0)
Dale Johannesenf1163e92009-02-03 00:47:48 +0000987 return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
988 Op.getValueType(),
989 Op.getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +0000990
Chris Lattner118ddba2006-02-26 23:36:02 +0000991 // Since some of the sign extended bits are demanded, we know that the sign
992 // bit is demanded.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000993 APInt InDemandedBits = InMask & NewMask;
Chris Lattner118ddba2006-02-26 23:36:02 +0000994 InDemandedBits |= InSignBit;
Jay Foad583abbc2010-12-07 08:25:19 +0000995 InDemandedBits = InDemandedBits.trunc(InBits);
Wesley Peck527da1b2010-11-23 03:31:01 +0000996
997 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
Chris Lattner118ddba2006-02-26 23:36:02 +0000998 KnownOne, TLO, Depth+1))
999 return true;
Jay Foad583abbc2010-12-07 08:25:19 +00001000 KnownZero = KnownZero.zext(BitWidth);
1001 KnownOne = KnownOne.zext(BitWidth);
Wesley Peck527da1b2010-11-23 03:31:01 +00001002
Chris Lattner118ddba2006-02-26 23:36:02 +00001003 // If the sign bit is known zero, convert this to a zero extend.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00001004 if (KnownZero.intersects(InSignBit))
Dale Johannesenf1163e92009-02-03 00:47:48 +00001005 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
Wesley Peck527da1b2010-11-23 03:31:01 +00001006 Op.getValueType(),
Chris Lattner118ddba2006-02-26 23:36:02 +00001007 Op.getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00001008
Chris Lattner118ddba2006-02-26 23:36:02 +00001009 // If the sign bit is known one, the top bits match.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00001010 if (KnownOne.intersects(InSignBit)) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001011 KnownOne |= NewBits;
1012 assert((KnownZero & NewBits) == 0);
Chris Lattner118ddba2006-02-26 23:36:02 +00001013 } else { // Otherwise, top bits aren't known.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001014 assert((KnownOne & NewBits) == 0);
1015 assert((KnownZero & NewBits) == 0);
Chris Lattner118ddba2006-02-26 23:36:02 +00001016 }
1017 break;
1018 }
1019 case ISD::ANY_EXTEND: {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00001020 unsigned OperandBitWidth =
1021 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
Jay Foad583abbc2010-12-07 08:25:19 +00001022 APInt InMask = NewMask.trunc(OperandBitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00001023 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
Chris Lattner118ddba2006-02-26 23:36:02 +00001024 KnownZero, KnownOne, TLO, Depth+1))
1025 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +00001026 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Jay Foad583abbc2010-12-07 08:25:19 +00001027 KnownZero = KnownZero.zext(BitWidth);
1028 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner118ddba2006-02-26 23:36:02 +00001029 break;
1030 }
Chris Lattner0f649322006-05-05 22:32:12 +00001031 case ISD::TRUNCATE: {
Chris Lattner86a14672006-05-06 00:11:52 +00001032 // Simplify the input, using demanded bit information, and compute the known
1033 // zero/one bits live out.
Dan Gohmanc3c3c682010-03-01 17:59:21 +00001034 unsigned OperandBitWidth =
1035 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
Jay Foad583abbc2010-12-07 08:25:19 +00001036 APInt TruncMask = NewMask.zext(OperandBitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00001037 if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
Chris Lattner0f649322006-05-05 22:32:12 +00001038 KnownZero, KnownOne, TLO, Depth+1))
1039 return true;
Jay Foad583abbc2010-12-07 08:25:19 +00001040 KnownZero = KnownZero.trunc(BitWidth);
1041 KnownOne = KnownOne.trunc(BitWidth);
Wesley Peck527da1b2010-11-23 03:31:01 +00001042
Chris Lattner86a14672006-05-06 00:11:52 +00001043 // If the input is only used by this truncate, see if we can shrink it based
1044 // on the known demanded bits.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001045 if (Op.getOperand(0).getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001046 SDValue In = Op.getOperand(0);
Chris Lattner86a14672006-05-06 00:11:52 +00001047 switch (In.getOpcode()) {
1048 default: break;
1049 case ISD::SRL:
1050 // Shrink SRL by a constant if none of the high bits shifted in are
1051 // demanded.
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001052 if (TLO.LegalTypes() &&
1053 !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
1054 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1055 // undesirable.
1056 break;
1057 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
1058 if (!ShAmt)
1059 break;
Owen Anderson9c128342011-04-13 23:22:23 +00001060 SDValue Shift = In.getOperand(1);
1061 if (TLO.LegalTypes()) {
1062 uint64_t ShVal = ShAmt->getZExtValue();
Mehdi Amini9639d652015-07-09 02:09:20 +00001063 Shift = TLO.DAG.getConstant(ShVal, dl,
1064 getShiftAmountTy(Op.getValueType(), DL));
Owen Anderson9c128342011-04-13 23:22:23 +00001065 }
1066
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001067 APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
1068 OperandBitWidth - BitWidth);
Jay Foad583abbc2010-12-07 08:25:19 +00001069 HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001070
1071 if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) {
1072 // None of the shifted in bits are needed. Add a truncate of the
1073 // shift input, then shift it.
1074 SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
Wesley Peck527da1b2010-11-23 03:31:01 +00001075 Op.getValueType(),
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001076 In.getOperand(0));
1077 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
1078 Op.getValueType(),
Wesley Peck527da1b2010-11-23 03:31:01 +00001079 NewTrunc,
Owen Anderson9c128342011-04-13 23:22:23 +00001080 Shift));
Chris Lattner86a14672006-05-06 00:11:52 +00001081 }
1082 break;
1083 }
1084 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001085
1086 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0f649322006-05-05 22:32:12 +00001087 break;
1088 }
Chris Lattner118ddba2006-02-26 23:36:02 +00001089 case ISD::AssertZext: {
Owen Anderson40d756e2011-09-03 00:26:49 +00001090 // AssertZext demands all of the high bits, plus any of the low bits
1091 // demanded by its users.
1092 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1093 APInt InMask = APInt::getLowBitsSet(BitWidth,
1094 VT.getSizeInBits());
1095 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
Chris Lattner118ddba2006-02-26 23:36:02 +00001096 KnownZero, KnownOne, TLO, Depth+1))
1097 return true;
Wesley Peck527da1b2010-11-23 03:31:01 +00001098 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Dan Gohmand83e3e72010-06-03 20:21:33 +00001099
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00001100 KnownZero |= ~InMask & NewMask;
Chris Lattner118ddba2006-02-26 23:36:02 +00001101 break;
1102 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001103 case ISD::BITCAST:
Stuart Hastingsbee6fcc2011-06-06 16:44:31 +00001104 // If this is an FP->Int bitcast and if the sign bit is the only
1105 // thing demanded, turn this into a FGETSIGN.
Eli Friedman2ec82492011-12-15 02:07:20 +00001106 if (!TLO.LegalOperations() &&
1107 !Op.getValueType().isVector() &&
Eli Friedman53218b62011-11-09 22:25:12 +00001108 !Op.getOperand(0).getValueType().isVector() &&
Nadav Rotem504cf0c2011-06-12 14:56:55 +00001109 NewMask == APInt::getSignBit(Op.getValueType().getSizeInBits()) &&
1110 Op.getOperand(0).getValueType().isFloatingPoint()) {
Stuart Hastingsbee6fcc2011-06-06 16:44:31 +00001111 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
1112 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
Chih-Hung Hsiehed7d81e2015-12-03 22:02:40 +00001113 if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple() &&
1114 Op.getOperand(0).getValueType() != MVT::f128) {
1115 // Cannot eliminate/lower SHL for f128 yet.
Stuart Hastingsbee6fcc2011-06-06 16:44:31 +00001116 EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
Chris Lattnerde272b12007-12-22 21:35:38 +00001117 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1118 // place. We expect the SHL to be eliminated by other optimizations.
Stuart Hastings3ae49c02011-06-01 18:32:25 +00001119 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
Stuart Hastingsbee6fcc2011-06-06 16:44:31 +00001120 unsigned OpVTSizeInBits = Op.getValueType().getSizeInBits();
1121 if (!OpVTLegal && OpVTSizeInBits > 32)
Stuart Hastings3ae49c02011-06-01 18:32:25 +00001122 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
Duncan Sands13237ac2008-06-06 12:08:01 +00001123 unsigned ShVal = Op.getValueType().getSizeInBits()-1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001124 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, Op.getValueType());
Stuart Hastings4a4e5a22011-05-19 18:48:20 +00001125 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1126 Op.getValueType(),
Chris Lattnerde272b12007-12-22 21:35:38 +00001127 Sign, ShAmt));
1128 }
1129 }
Chris Lattnerde272b12007-12-22 21:35:38 +00001130 break;
Dan Gohmanad3e5492009-04-08 00:15:30 +00001131 case ISD::ADD:
1132 case ISD::MUL:
1133 case ISD::SUB: {
1134 // Add, Sub, and Mul don't demand any bits in positions beyond that
1135 // of the highest bit demanded of them.
1136 APInt LoMask = APInt::getLowBitsSet(BitWidth,
1137 BitWidth - NewMask.countLeadingZeros());
1138 if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
1139 KnownOne2, TLO, Depth+1))
1140 return true;
1141 if (SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
1142 KnownOne2, TLO, Depth+1))
1143 return true;
1144 // See if the operation should be performed at a smaller bit width.
Dan Gohman600f62b2010-06-24 14:30:44 +00001145 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
Dan Gohmanad3e5492009-04-08 00:15:30 +00001146 return true;
1147 }
1148 // FALL THROUGH
Dan Gohman38dc08f2008-05-06 00:53:29 +00001149 default:
Jay Foada0653a32014-05-14 21:14:37 +00001150 // Just use computeKnownBits to compute output bits.
1151 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
Chris Lattnerab816402006-02-27 01:00:42 +00001152 break;
Nate Begeman8a77efe2006-02-16 21:11:51 +00001153 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001154
Chris Lattner118ddba2006-02-26 23:36:02 +00001155 // If we know the value of all of the demanded bits, return this as a
1156 // constant.
Matthias Braun56a78142015-05-20 18:54:02 +00001157 if ((NewMask & (KnownZero|KnownOne)) == NewMask) {
1158 // Avoid folding to a constant if any OpaqueConstant is involved.
1159 const SDNode *N = Op.getNode();
1160 for (SDNodeIterator I = SDNodeIterator::begin(N),
1161 E = SDNodeIterator::end(N); I != E; ++I) {
1162 SDNode *Op = *I;
1163 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
1164 if (C->isOpaque())
1165 return false;
1166 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001167 return TLO.CombineTo(Op,
1168 TLO.DAG.getConstant(KnownOne, dl, Op.getValueType()));
Matthias Braun56a78142015-05-20 18:54:02 +00001169 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001170
Nate Begeman8a77efe2006-02-16 21:11:51 +00001171 return false;
1172}
1173
Sanjay Patelac6e9102015-12-29 22:11:50 +00001174/// Determine which of the bits specified in Mask are known to be either zero or
1175/// one and return them in the KnownZero/KnownOne bitsets.
Jay Foada0653a32014-05-14 21:14:37 +00001176void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1177 APInt &KnownZero,
1178 APInt &KnownOne,
1179 const SelectionDAG &DAG,
1180 unsigned Depth) const {
Chris Lattner6c1321c2006-04-02 06:19:46 +00001181 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1182 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1183 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1184 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
Chris Lattnerf0b24d22006-01-30 04:09:27 +00001185 "Should use MaskedValueIsZero if you don't know whether Op"
1186 " is a target node!");
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001187 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
Evan Cheng9cdc16c2005-12-21 23:05:39 +00001188}
Chris Lattner32fef532006-01-26 20:37:03 +00001189
Sanjay Patelac6e9102015-12-29 22:11:50 +00001190/// This method can be implemented by targets that want to expose additional
1191/// information about sign bits to the DAG Combiner.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001192unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
Matt Arsenaultcf6f6882014-04-04 20:13:13 +00001193 const SelectionDAG &,
Chris Lattner7206d742006-05-06 09:27:13 +00001194 unsigned Depth) const {
1195 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1196 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1197 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1198 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1199 "Should use ComputeNumSignBits if you don't know whether Op"
1200 " is a target node!");
1201 return 1;
1202}
1203
Sanjay Patelac6e9102015-12-29 22:11:50 +00001204/// Test if the given value is known to have exactly one bit set. This differs
1205/// from computeKnownBits in that it doesn't need to determine which bit is set.
Sanjay Patelc91351c2016-05-04 22:39:36 +00001206static bool valueHasExactlyOneBitSet(SDValue Val, const SelectionDAG &DAG) {
1207 // A left-shift of a constant one will have exactly one bit set because
Dan Gohmanaaee6c92009-02-15 23:59:32 +00001208 // shifting the bit off the end is undefined.
Sanjay Patelc91351c2016-05-04 22:39:36 +00001209 if (Val.getOpcode() == ISD::SHL) {
1210 auto *C = dyn_cast<ConstantSDNode>(Val.getOperand(0));
1211 if (C && C->getAPIntValue() == 1)
1212 return true;
1213 }
Dan Gohmane58ab792009-01-29 01:59:02 +00001214
Sanjay Patelc91351c2016-05-04 22:39:36 +00001215 // Similarly, a logical right-shift of a constant sign-bit will have exactly
Dan Gohmanaaee6c92009-02-15 23:59:32 +00001216 // one bit set.
Sanjay Patelc91351c2016-05-04 22:39:36 +00001217 if (Val.getOpcode() == ISD::SRL) {
1218 auto *C = dyn_cast<ConstantSDNode>(Val.getOperand(0));
1219 if (C && C->getAPIntValue().isSignBit())
1220 return true;
1221 }
Dan Gohmanaaee6c92009-02-15 23:59:32 +00001222
1223 // More could be done here, though the above checks are enough
1224 // to handle some common cases.
1225
Jay Foada0653a32014-05-14 21:14:37 +00001226 // Fall back to computeKnownBits to catch other known cases.
Owen Anderson53aa7a92009-08-10 22:56:29 +00001227 EVT OpVT = Val.getValueType();
Dan Gohman4cec5432010-03-02 02:14:38 +00001228 unsigned BitWidth = OpVT.getScalarType().getSizeInBits();
Dan Gohmane58ab792009-01-29 01:59:02 +00001229 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00001230 DAG.computeKnownBits(Val, KnownZero, KnownOne);
Dale Johannesencc5fc442009-02-11 19:19:41 +00001231 return (KnownZero.countPopulation() == BitWidth - 1) &&
1232 (KnownOne.countPopulation() == 1);
Dan Gohmane58ab792009-01-29 01:59:02 +00001233}
Chris Lattner7206d742006-05-06 09:27:13 +00001234
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001235bool TargetLowering::isConstTrueVal(const SDNode *N) const {
1236 if (!N)
1237 return false;
1238
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001239 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
Chandler Carruthbeeacac2014-07-07 19:03:32 +00001240 if (!CN) {
1241 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1242 if (!BV)
1243 return false;
1244
Chandler Carruthf0a33b72014-07-09 00:41:34 +00001245 BitVector UndefElements;
1246 CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthefbce582014-07-08 07:44:15 +00001247 // Only interested in constant splats, and we don't try to handle undef
1248 // elements in identifying boolean constants.
Chandler Carruthf0a33b72014-07-09 00:41:34 +00001249 if (!CN || UndefElements.none())
Chandler Carruthefbce582014-07-08 07:44:15 +00001250 return false;
Chandler Carruthbeeacac2014-07-07 19:03:32 +00001251 }
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001252
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001253 switch (getBooleanContents(N->getValueType(0))) {
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001254 case UndefinedBooleanContent:
1255 return CN->getAPIntValue()[0];
1256 case ZeroOrOneBooleanContent:
1257 return CN->isOne();
1258 case ZeroOrNegativeOneBooleanContent:
1259 return CN->isAllOnesValue();
1260 }
1261
1262 llvm_unreachable("Invalid boolean contents");
1263}
1264
1265bool TargetLowering::isConstFalseVal(const SDNode *N) const {
1266 if (!N)
1267 return false;
1268
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001269 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
Chandler Carruthbeeacac2014-07-07 19:03:32 +00001270 if (!CN) {
1271 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1272 if (!BV)
1273 return false;
1274
Chandler Carruthf0a33b72014-07-09 00:41:34 +00001275 BitVector UndefElements;
1276 CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthefbce582014-07-08 07:44:15 +00001277 // Only interested in constant splats, and we don't try to handle undef
1278 // elements in identifying boolean constants.
Chandler Carruthf0a33b72014-07-09 00:41:34 +00001279 if (!CN || UndefElements.none())
Chandler Carruthefbce582014-07-08 07:44:15 +00001280 return false;
Chandler Carruthbeeacac2014-07-07 19:03:32 +00001281 }
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001282
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001283 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
Matt Arsenault6310c3f2014-04-01 18:13:22 +00001284 return !CN->getAPIntValue()[0];
1285
1286 return CN->isNullValue();
1287}
1288
Tom Stellardccdc5392016-01-18 19:55:21 +00001289bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
1290 bool SExt) const {
1291 if (VT == MVT::i1)
1292 return N->isOne();
1293
1294 TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
1295 switch (Cnt) {
1296 case TargetLowering::ZeroOrOneBooleanContent:
1297 // An extended value of 1 is always true, unless its original type is i1,
1298 // in which case it will be sign extended to -1.
1299 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
1300 case TargetLowering::UndefinedBooleanContent:
1301 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1302 return N->isAllOnesValue() && SExt;
1303 }
Simon Pilgrimc4d519d2016-01-18 22:54:46 +00001304 llvm_unreachable("Unexpected enumeration.");
Tom Stellardccdc5392016-01-18 19:55:21 +00001305}
1306
Sanjay Patel91592562016-05-09 16:42:50 +00001307/// This helper function of SimplifySetCC tries to optimize the comparison when
1308/// either operand of the SetCC node is a bitwise-and instruction.
1309SDValue TargetLowering::simplifySetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
1310 ISD::CondCode Cond,
1311 DAGCombinerInfo &DCI,
1312 SDLoc DL) const {
Sanjay Patelc2751e72016-05-07 15:03:40 +00001313 // Match these patterns in any of their permutations:
1314 // (X & Y) == Y
1315 // (X & Y) != Y
1316 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
1317 std::swap(N0, N1);
1318
Sanjay Patel91592562016-05-09 16:42:50 +00001319 EVT OpVT = N0.getValueType();
1320 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
Sanjay Patelc2751e72016-05-07 15:03:40 +00001321 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
1322 return SDValue();
1323
1324 SDValue X, Y;
1325 if (N0.getOperand(0) == N1) {
1326 X = N0.getOperand(1);
1327 Y = N0.getOperand(0);
1328 } else if (N0.getOperand(1) == N1) {
1329 X = N0.getOperand(0);
1330 Y = N0.getOperand(1);
1331 } else {
1332 return SDValue();
1333 }
1334
Sanjay Patel91592562016-05-09 16:42:50 +00001335 SelectionDAG &DAG = DCI.DAG;
1336 SDValue Zero = DAG.getConstant(0, DL, OpVT);
1337 if (valueHasExactlyOneBitSet(Y, DAG)) {
1338 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
1339 // Note that where Y is variable and is known to have at most one bit set
1340 // (for example, if it is Z & 1) we cannot do this; the expressions are not
1341 // equivalent when Y == 0.
1342 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
1343 if (DCI.isBeforeLegalizeOps() ||
1344 isCondCodeLegal(Cond, N0.getSimpleValueType()))
1345 return DAG.getSetCC(DL, VT, N0, Zero, Cond);
1346 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
1347 // If the target supports an 'and-not' or 'and-complement' logic operation,
1348 // try to use that to make a comparison operation more efficient.
1349 // But don't do this transform if the mask is a single bit because there are
1350 // more efficient ways to deal with that case (for example, 'bt' on x86 or
1351 // 'rlwinm' on PPC).
Sanjay Patelc2751e72016-05-07 15:03:40 +00001352
Sanjay Patel91592562016-05-09 16:42:50 +00001353 // Bail out if the compare operand that we want to turn into a zero is
1354 // already a zero (otherwise, infinite loop).
1355 auto *YConst = dyn_cast<ConstantSDNode>(Y);
1356 if (YConst && YConst->isNullValue())
1357 return SDValue();
Sanjay Patelc2751e72016-05-07 15:03:40 +00001358
Sanjay Patel91592562016-05-09 16:42:50 +00001359 // Transform this into: ~X & Y == 0.
1360 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
1361 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
1362 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
1363 }
1364
1365 return SDValue();
Sanjay Patelc2751e72016-05-07 15:03:40 +00001366}
1367
Sanjay Patelac6e9102015-12-29 22:11:50 +00001368/// Try to simplify a setcc built with the specified operands and cc. If it is
1369/// unable to simplify it, return a null SDValue.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001370SDValue
Owen Anderson53aa7a92009-08-10 22:56:29 +00001371TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
Evan Cheng92658d52007-02-08 22:13:59 +00001372 ISD::CondCode Cond, bool foldBooleans,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001373 DAGCombinerInfo &DCI, SDLoc dl) const {
Evan Cheng92658d52007-02-08 22:13:59 +00001374 SelectionDAG &DAG = DCI.DAG;
1375
1376 // These setcc operations always fold.
1377 switch (Cond) {
1378 default: break;
1379 case ISD::SETFALSE:
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001380 case ISD::SETFALSE2: return DAG.getConstant(0, dl, VT);
Evan Cheng92658d52007-02-08 22:13:59 +00001381 case ISD::SETTRUE:
Tim Northover950fcc02013-09-06 12:38:12 +00001382 case ISD::SETTRUE2: {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001383 TargetLowering::BooleanContent Cnt =
1384 getBooleanContents(N0->getValueType(0));
Tim Northover950fcc02013-09-06 12:38:12 +00001385 return DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001386 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
1387 VT);
Tim Northover950fcc02013-09-06 12:38:12 +00001388 }
Evan Cheng92658d52007-02-08 22:13:59 +00001389 }
1390
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001391 // Ensure that the constant occurs on the RHS, and fold constant
1392 // comparisons.
Tom Stellardcd428182013-09-28 02:50:38 +00001393 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
1394 if (isa<ConstantSDNode>(N0.getNode()) &&
1395 (DCI.isBeforeLegalizeOps() ||
1396 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
1397 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
Eric Christopher5bbb2bd2011-06-17 20:41:29 +00001398
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001399 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
Dan Gohman2fa65b72008-03-03 22:22:56 +00001400 const APInt &C1 = N1C->getAPIntValue();
Dale Johannesen7aad5422008-11-07 01:28:02 +00001401
Eli Friedman65919b52009-07-26 23:47:17 +00001402 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1403 // equality comparison, then we're just comparing whether X itself is
1404 // zero.
1405 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1406 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1407 N0.getOperand(1).getOpcode() == ISD::Constant) {
Evan Cheng16b75ce2010-01-07 20:58:44 +00001408 const APInt &ShAmt
1409 = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Eli Friedman65919b52009-07-26 23:47:17 +00001410 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1411 ShAmt == Log2_32(N0.getValueType().getSizeInBits())) {
1412 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1413 // (srl (ctlz x), 5) == 0 -> X != 0
1414 // (srl (ctlz x), 5) != 1 -> X != 0
1415 Cond = ISD::SETNE;
1416 } else {
1417 // (srl (ctlz x), 5) != 0 -> X == 0
1418 // (srl (ctlz x), 5) == 1 -> X == 0
1419 Cond = ISD::SETEQ;
1420 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001421 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
Eli Friedman65919b52009-07-26 23:47:17 +00001422 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
1423 Zero, Cond);
1424 }
1425 }
1426
Benjamin Kramer24c5184d2011-01-17 12:04:57 +00001427 SDValue CTPOP = N0;
1428 // Look through truncs that don't change the value of a ctpop.
1429 if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
1430 CTPOP = N0.getOperand(0);
1431
1432 if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
Benjamin Kramer45d183c2011-01-17 18:00:28 +00001433 (N0 == CTPOP || N0.getValueType().getSizeInBits() >
Benjamin Kramer24c5184d2011-01-17 12:04:57 +00001434 Log2_32_Ceil(CTPOP.getValueType().getSizeInBits()))) {
1435 EVT CTVT = CTPOP.getValueType();
1436 SDValue CTOp = CTPOP.getOperand(0);
1437
1438 // (ctpop x) u< 2 -> (x & x-1) == 0
1439 // (ctpop x) u> 1 -> (x & x-1) != 0
1440 if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
1441 SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001442 DAG.getConstant(1, dl, CTVT));
Benjamin Kramer24c5184d2011-01-17 12:04:57 +00001443 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
1444 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001445 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC);
Benjamin Kramer24c5184d2011-01-17 12:04:57 +00001446 }
1447
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001448 // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
Benjamin Kramer24c5184d2011-01-17 12:04:57 +00001449 }
1450
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001451 // (zext x) == C --> x == (trunc C)
Matt Arsenault22b4c252014-12-21 16:48:42 +00001452 // (sext x) == C --> x == (trunc C)
1453 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1454 DCI.isBeforeLegalize() && N0->hasOneUse()) {
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001455 unsigned MinBits = N0.getValueSizeInBits();
Matt Arsenault22b4c252014-12-21 16:48:42 +00001456 SDValue PreExt;
1457 bool Signed = false;
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001458 if (N0->getOpcode() == ISD::ZERO_EXTEND) {
1459 // ZExt
1460 MinBits = N0->getOperand(0).getValueSizeInBits();
Matt Arsenault22b4c252014-12-21 16:48:42 +00001461 PreExt = N0->getOperand(0);
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001462 } else if (N0->getOpcode() == ISD::AND) {
1463 // DAGCombine turns costly ZExts into ANDs
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001464 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001465 if ((C->getAPIntValue()+1).isPowerOf2()) {
1466 MinBits = C->getAPIntValue().countTrailingOnes();
Matt Arsenault22b4c252014-12-21 16:48:42 +00001467 PreExt = N0->getOperand(0);
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001468 }
Matt Arsenault22b4c252014-12-21 16:48:42 +00001469 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
1470 // SExt
1471 MinBits = N0->getOperand(0).getValueSizeInBits();
1472 PreExt = N0->getOperand(0);
1473 Signed = true;
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001474 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
Matt Arsenault22b4c252014-12-21 16:48:42 +00001475 // ZEXTLOAD / SEXTLOAD
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001476 if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
1477 MinBits = LN0->getMemoryVT().getSizeInBits();
Matt Arsenault22b4c252014-12-21 16:48:42 +00001478 PreExt = N0;
1479 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
1480 Signed = true;
1481 MinBits = LN0->getMemoryVT().getSizeInBits();
1482 PreExt = N0;
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001483 }
1484 }
1485
Matt Arsenault22b4c252014-12-21 16:48:42 +00001486 // Figure out how many bits we need to preserve this constant.
1487 unsigned ReqdBits = Signed ?
1488 C1.getBitWidth() - C1.getNumSignBits() + 1 :
1489 C1.getActiveBits();
1490
Benjamin Kramerbde91762012-06-02 10:20:22 +00001491 // Make sure we're not losing bits from the constant.
Benjamin Kramer8aaf1972013-05-21 08:51:09 +00001492 if (MinBits > 0 &&
Matt Arsenault22b4c252014-12-21 16:48:42 +00001493 MinBits < C1.getBitWidth() &&
1494 MinBits >= ReqdBits) {
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001495 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
1496 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
1497 // Will get folded away.
Matt Arsenault22b4c252014-12-21 16:48:42 +00001498 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001499 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001500 return DAG.getSetCC(dl, VT, Trunc, C, Cond);
1501 }
Tom Stellardccdc5392016-01-18 19:55:21 +00001502
1503 // If truncating the setcc operands is not desirable, we can still
1504 // simplify the expression in some cases:
1505 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
1506 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
1507 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
1508 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
1509 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
1510 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
1511 SDValue TopSetCC = N0->getOperand(0);
1512 unsigned N0Opc = N0->getOpcode();
1513 bool SExt = (N0Opc == ISD::SIGN_EXTEND);
1514 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
1515 TopSetCC.getOpcode() == ISD::SETCC &&
1516 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
1517 (isConstFalseVal(N1C) ||
1518 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
1519
1520 bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) ||
1521 (!N1C->isNullValue() && Cond == ISD::SETNE);
1522
1523 if (!Inverse)
1524 return TopSetCC;
1525
1526 ISD::CondCode InvCond = ISD::getSetCCInverse(
1527 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
1528 TopSetCC.getOperand(0).getValueType().isInteger());
1529 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
1530 TopSetCC.getOperand(1),
1531 InvCond);
1532
1533 }
Benjamin Kramer341c11d2011-04-22 18:47:44 +00001534 }
1535 }
1536
Eli Friedman65919b52009-07-26 23:47:17 +00001537 // If the LHS is '(and load, const)', the RHS is 0,
1538 // the test is for equality or unsigned, and all 1 bits of the const are
1539 // in the same partial word, see if we can shorten the load.
1540 if (DCI.isBeforeLegalize() &&
Eli Friedmana961d692013-09-24 22:50:14 +00001541 !ISD::isSignedIntSetCC(Cond) &&
Eli Friedman65919b52009-07-26 23:47:17 +00001542 N0.getOpcode() == ISD::AND && C1 == 0 &&
1543 N0.getNode()->hasOneUse() &&
1544 isa<LoadSDNode>(N0.getOperand(0)) &&
1545 N0.getOperand(0).getNode()->hasOneUse() &&
1546 isa<ConstantSDNode>(N0.getOperand(1))) {
1547 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
Evan Cheng16b75ce2010-01-07 20:58:44 +00001548 APInt bestMask;
Eli Friedman65919b52009-07-26 23:47:17 +00001549 unsigned bestWidth = 0, bestOffset = 0;
Evan Cheng16b75ce2010-01-07 20:58:44 +00001550 if (!Lod->isVolatile() && Lod->isUnindexed()) {
Eli Friedman65919b52009-07-26 23:47:17 +00001551 unsigned origWidth = N0.getValueType().getSizeInBits();
Evan Cheng16b75ce2010-01-07 20:58:44 +00001552 unsigned maskWidth = origWidth;
Wesley Peck527da1b2010-11-23 03:31:01 +00001553 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
Eli Friedman65919b52009-07-26 23:47:17 +00001554 // 8 bits, but have to be careful...
1555 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
1556 origWidth = Lod->getMemoryVT().getSizeInBits();
Evan Cheng16b75ce2010-01-07 20:58:44 +00001557 const APInt &Mask =
1558 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Eli Friedman65919b52009-07-26 23:47:17 +00001559 for (unsigned width = origWidth / 2; width>=8; width /= 2) {
Evan Cheng16b75ce2010-01-07 20:58:44 +00001560 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
Eli Friedman65919b52009-07-26 23:47:17 +00001561 for (unsigned offset=0; offset<origWidth/width; offset++) {
1562 if ((newMask & Mask) == Mask) {
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00001563 if (!DAG.getDataLayout().isLittleEndian())
Eli Friedman65919b52009-07-26 23:47:17 +00001564 bestOffset = (origWidth/width - offset - 1) * (width/8);
1565 else
1566 bestOffset = (uint64_t)offset * (width/8);
Evan Cheng16b75ce2010-01-07 20:58:44 +00001567 bestMask = Mask.lshr(offset * (width/8) * 8);
Eli Friedman65919b52009-07-26 23:47:17 +00001568 bestWidth = width;
1569 break;
Dale Johannesen7aad5422008-11-07 01:28:02 +00001570 }
Eli Friedman65919b52009-07-26 23:47:17 +00001571 newMask = newMask << width;
Dale Johannesen7aad5422008-11-07 01:28:02 +00001572 }
1573 }
1574 }
Eli Friedman65919b52009-07-26 23:47:17 +00001575 if (bestWidth) {
Chris Lattner493b3e72011-04-14 04:12:47 +00001576 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
Eli Friedman65919b52009-07-26 23:47:17 +00001577 if (newVT.isRound()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001578 EVT PtrType = Lod->getOperand(1).getValueType();
Eli Friedman65919b52009-07-26 23:47:17 +00001579 SDValue Ptr = Lod->getBasePtr();
1580 if (bestOffset != 0)
1581 Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001582 DAG.getConstant(bestOffset, dl, PtrType));
Eli Friedman65919b52009-07-26 23:47:17 +00001583 unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
1584 SDValue NewLoad = DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
Chris Lattner1ffcf522010-09-21 16:36:31 +00001585 Lod->getPointerInfo().getWithOffset(bestOffset),
Pete Cooper82cd9e82011-11-08 18:42:53 +00001586 false, false, false, NewAlign);
Wesley Peck527da1b2010-11-23 03:31:01 +00001587 return DAG.getSetCC(dl, VT,
Eli Friedman65919b52009-07-26 23:47:17 +00001588 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
Evan Cheng16b75ce2010-01-07 20:58:44 +00001589 DAG.getConstant(bestMask.trunc(bestWidth),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001590 dl, newVT)),
1591 DAG.getConstant(0LL, dl, newVT), Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00001592 }
Eli Friedman65919b52009-07-26 23:47:17 +00001593 }
1594 }
Evan Cheng92658d52007-02-08 22:13:59 +00001595
Eli Friedman65919b52009-07-26 23:47:17 +00001596 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1597 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1598 unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits();
1599
1600 // If the comparison constant has bits in the upper part, the
1601 // zero-extended value could never match.
1602 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
1603 C1.getBitWidth() - InSize))) {
Evan Cheng92658d52007-02-08 22:13:59 +00001604 switch (Cond) {
Evan Cheng92658d52007-02-08 22:13:59 +00001605 case ISD::SETUGT:
1606 case ISD::SETUGE:
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001607 case ISD::SETEQ: return DAG.getConstant(0, dl, VT);
Evan Cheng92658d52007-02-08 22:13:59 +00001608 case ISD::SETULT:
Eli Friedman65919b52009-07-26 23:47:17 +00001609 case ISD::SETULE:
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001610 case ISD::SETNE: return DAG.getConstant(1, dl, VT);
Eli Friedman65919b52009-07-26 23:47:17 +00001611 case ISD::SETGT:
1612 case ISD::SETGE:
1613 // True if the sign bit of C1 is set.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001614 return DAG.getConstant(C1.isNegative(), dl, VT);
Eli Friedman65919b52009-07-26 23:47:17 +00001615 case ISD::SETLT:
1616 case ISD::SETLE:
1617 // True if the sign bit of C1 isn't set.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001618 return DAG.getConstant(C1.isNonNegative(), dl, VT);
Eli Friedman65919b52009-07-26 23:47:17 +00001619 default:
Jakob Stoklund Olesen1ae07362009-07-24 18:22:59 +00001620 break;
1621 }
Eli Friedman65919b52009-07-26 23:47:17 +00001622 }
Evan Cheng92658d52007-02-08 22:13:59 +00001623
Eli Friedman65919b52009-07-26 23:47:17 +00001624 // Otherwise, we can perform the comparison with the low bits.
1625 switch (Cond) {
1626 case ISD::SETEQ:
1627 case ISD::SETNE:
1628 case ISD::SETUGT:
1629 case ISD::SETUGE:
1630 case ISD::SETULT:
1631 case ISD::SETULE: {
Patrik Hagglunde98b7a02012-12-11 11:14:33 +00001632 EVT newVT = N0.getOperand(0).getValueType();
Eli Friedman65919b52009-07-26 23:47:17 +00001633 if (DCI.isBeforeLegalizeOps() ||
1634 (isOperationLegal(ISD::SETCC, newVT) &&
Matt Arsenault5f2fd4b2014-05-07 18:26:58 +00001635 getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001636 EVT NewSetCCVT =
1637 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001638 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
Matt Arsenault5f2fd4b2014-05-07 18:26:58 +00001639
1640 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
1641 NewConst, Cond);
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001642 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
Matt Arsenault5f2fd4b2014-05-07 18:26:58 +00001643 }
Eli Friedman65919b52009-07-26 23:47:17 +00001644 break;
1645 }
1646 default:
1647 break; // todo, be more careful with signed comparisons
1648 }
1649 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Evan Cheng228c31f2010-02-27 07:36:59 +00001650 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001651 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
Eli Friedman65919b52009-07-26 23:47:17 +00001652 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
Owen Anderson53aa7a92009-08-10 22:56:29 +00001653 EVT ExtDstTy = N0.getValueType();
Eli Friedman65919b52009-07-26 23:47:17 +00001654 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
1655
Eli Friedmanffe64c02010-07-30 06:44:31 +00001656 // If the constant doesn't fit into the number of bits for the source of
1657 // the sign extension, it is impossible for both sides to be equal.
1658 if (C1.getMinSignedBits() > ExtSrcTyBits)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001659 return DAG.getConstant(Cond == ISD::SETNE, dl, VT);
Wesley Peck527da1b2010-11-23 03:31:01 +00001660
Eli Friedman65919b52009-07-26 23:47:17 +00001661 SDValue ZextOp;
Owen Anderson53aa7a92009-08-10 22:56:29 +00001662 EVT Op0Ty = N0.getOperand(0).getValueType();
Eli Friedman65919b52009-07-26 23:47:17 +00001663 if (Op0Ty == ExtSrcTy) {
1664 ZextOp = N0.getOperand(0);
1665 } else {
1666 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
1667 ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001668 DAG.getConstant(Imm, dl, Op0Ty));
Eli Friedman65919b52009-07-26 23:47:17 +00001669 }
1670 if (!DCI.isCalledByLegalizer())
1671 DCI.AddToWorklist(ZextOp.getNode());
1672 // Otherwise, make this a use of a zext.
Wesley Peck527da1b2010-11-23 03:31:01 +00001673 return DAG.getSetCC(dl, VT, ZextOp,
Eli Friedman65919b52009-07-26 23:47:17 +00001674 DAG.getConstant(C1 & APInt::getLowBitsSet(
1675 ExtDstTyBits,
Wesley Peck527da1b2010-11-23 03:31:01 +00001676 ExtSrcTyBits),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001677 dl, ExtDstTy),
Eli Friedman65919b52009-07-26 23:47:17 +00001678 Cond);
1679 } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
1680 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
Eli Friedman65919b52009-07-26 23:47:17 +00001681 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC
Evan Cheng228c31f2010-02-27 07:36:59 +00001682 if (N0.getOpcode() == ISD::SETCC &&
1683 isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
Evan Cheng16b75ce2010-01-07 20:58:44 +00001684 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
Eli Friedman65919b52009-07-26 23:47:17 +00001685 if (TrueWhenTrue)
Wesley Peck527da1b2010-11-23 03:31:01 +00001686 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
Eli Friedman65919b52009-07-26 23:47:17 +00001687 // Invert the condition.
1688 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
Wesley Peck527da1b2010-11-23 03:31:01 +00001689 CC = ISD::getSetCCInverse(CC,
Eli Friedman65919b52009-07-26 23:47:17 +00001690 N0.getOperand(0).getValueType().isInteger());
Tom Stellardcd428182013-09-28 02:50:38 +00001691 if (DCI.isBeforeLegalizeOps() ||
1692 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
1693 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
Evan Cheng92658d52007-02-08 22:13:59 +00001694 }
Evan Cheng228c31f2010-02-27 07:36:59 +00001695
Eli Friedman65919b52009-07-26 23:47:17 +00001696 if ((N0.getOpcode() == ISD::XOR ||
Wesley Peck527da1b2010-11-23 03:31:01 +00001697 (N0.getOpcode() == ISD::AND &&
Eli Friedman65919b52009-07-26 23:47:17 +00001698 N0.getOperand(0).getOpcode() == ISD::XOR &&
1699 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1700 isa<ConstantSDNode>(N0.getOperand(1)) &&
1701 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
1702 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
1703 // can only do this if the top bits are known zero.
1704 unsigned BitWidth = N0.getValueSizeInBits();
1705 if (DAG.MaskedValueIsZero(N0,
1706 APInt::getHighBitsSet(BitWidth,
1707 BitWidth-1))) {
1708 // Okay, get the un-inverted input value.
1709 SDValue Val;
1710 if (N0.getOpcode() == ISD::XOR)
1711 Val = N0.getOperand(0);
1712 else {
Wesley Peck527da1b2010-11-23 03:31:01 +00001713 assert(N0.getOpcode() == ISD::AND &&
Eli Friedman65919b52009-07-26 23:47:17 +00001714 N0.getOperand(0).getOpcode() == ISD::XOR);
1715 // ((X^1)&1)^1 -> X & 1
1716 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
1717 N0.getOperand(0).getOperand(0),
1718 N0.getOperand(1));
1719 }
Evan Cheng228c31f2010-02-27 07:36:59 +00001720
Eli Friedman65919b52009-07-26 23:47:17 +00001721 return DAG.getSetCC(dl, VT, Val, N1,
1722 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1723 }
Evan Cheng228c31f2010-02-27 07:36:59 +00001724 } else if (N1C->getAPIntValue() == 1 &&
1725 (VT == MVT::i1 ||
Daniel Sanderscbd44c52014-07-10 10:18:12 +00001726 getBooleanContents(N0->getValueType(0)) ==
1727 ZeroOrOneBooleanContent)) {
Evan Cheng228c31f2010-02-27 07:36:59 +00001728 SDValue Op0 = N0;
1729 if (Op0.getOpcode() == ISD::TRUNCATE)
1730 Op0 = Op0.getOperand(0);
1731
1732 if ((Op0.getOpcode() == ISD::XOR) &&
1733 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
1734 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
1735 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
1736 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
1737 return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
1738 Cond);
Craig Topper63f59212012-12-19 06:12:28 +00001739 }
1740 if (Op0.getOpcode() == ISD::AND &&
1741 isa<ConstantSDNode>(Op0.getOperand(1)) &&
1742 cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
Evan Cheng228c31f2010-02-27 07:36:59 +00001743 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
Anton Korobeynikov737718d2010-05-01 12:52:34 +00001744 if (Op0.getValueType().bitsGT(VT))
Evan Cheng228c31f2010-02-27 07:36:59 +00001745 Op0 = DAG.getNode(ISD::AND, dl, VT,
1746 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001747 DAG.getConstant(1, dl, VT));
Anton Korobeynikov737718d2010-05-01 12:52:34 +00001748 else if (Op0.getValueType().bitsLT(VT))
1749 Op0 = DAG.getNode(ISD::AND, dl, VT,
1750 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001751 DAG.getConstant(1, dl, VT));
Anton Korobeynikov737718d2010-05-01 12:52:34 +00001752
Evan Cheng228c31f2010-02-27 07:36:59 +00001753 return DAG.getSetCC(dl, VT, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001754 DAG.getConstant(0, dl, Op0.getValueType()),
Evan Cheng228c31f2010-02-27 07:36:59 +00001755 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1756 }
Craig Topper63f59212012-12-19 06:12:28 +00001757 if (Op0.getOpcode() == ISD::AssertZext &&
1758 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
1759 return DAG.getSetCC(dl, VT, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001760 DAG.getConstant(0, dl, Op0.getValueType()),
Craig Topper63f59212012-12-19 06:12:28 +00001761 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
Evan Cheng92658d52007-02-08 22:13:59 +00001762 }
Eli Friedman65919b52009-07-26 23:47:17 +00001763 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001764
Eli Friedman65919b52009-07-26 23:47:17 +00001765 APInt MinVal, MaxVal;
1766 unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
1767 if (ISD::isSignedIntSetCC(Cond)) {
1768 MinVal = APInt::getSignedMinValue(OperandBitSize);
1769 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
1770 } else {
1771 MinVal = APInt::getMinValue(OperandBitSize);
1772 MaxVal = APInt::getMaxValue(OperandBitSize);
1773 }
Evan Cheng92658d52007-02-08 22:13:59 +00001774
Eli Friedman65919b52009-07-26 23:47:17 +00001775 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1776 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001777 if (C1 == MinVal) return DAG.getConstant(1, dl, VT); // X >= MIN --> true
Matt Arsenaultb22426c2014-03-25 16:09:21 +00001778 // X >= C0 --> X > (C0 - 1)
1779 APInt C = C1 - 1;
1780 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
1781 if ((DCI.isBeforeLegalizeOps() ||
1782 isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1783 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1784 isLegalICmpImmediate(C.getSExtValue())))) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00001785 return DAG.getSetCC(dl, VT, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001786 DAG.getConstant(C, dl, N1.getValueType()),
Matt Arsenaultb22426c2014-03-25 16:09:21 +00001787 NewCC);
1788 }
Eli Friedman65919b52009-07-26 23:47:17 +00001789 }
Evan Cheng92658d52007-02-08 22:13:59 +00001790
Eli Friedman65919b52009-07-26 23:47:17 +00001791 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001792 if (C1 == MaxVal) return DAG.getConstant(1, dl, VT); // X <= MAX --> true
Matt Arsenaultb22426c2014-03-25 16:09:21 +00001793 // X <= C0 --> X < (C0 + 1)
1794 APInt C = C1 + 1;
1795 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
1796 if ((DCI.isBeforeLegalizeOps() ||
1797 isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1798 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1799 isLegalICmpImmediate(C.getSExtValue())))) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00001800 return DAG.getSetCC(dl, VT, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001801 DAG.getConstant(C, dl, N1.getValueType()),
Matt Arsenaultb22426c2014-03-25 16:09:21 +00001802 NewCC);
1803 }
Eli Friedman65919b52009-07-26 23:47:17 +00001804 }
Evan Cheng92658d52007-02-08 22:13:59 +00001805
Eli Friedman65919b52009-07-26 23:47:17 +00001806 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001807 return DAG.getConstant(0, dl, VT); // X < MIN --> false
Eli Friedman65919b52009-07-26 23:47:17 +00001808 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001809 return DAG.getConstant(1, dl, VT); // X >= MIN --> true
Eli Friedman65919b52009-07-26 23:47:17 +00001810 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001811 return DAG.getConstant(0, dl, VT); // X > MAX --> false
Eli Friedman65919b52009-07-26 23:47:17 +00001812 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001813 return DAG.getConstant(1, dl, VT); // X <= MAX --> true
Evan Cheng92658d52007-02-08 22:13:59 +00001814
Eli Friedman65919b52009-07-26 23:47:17 +00001815 // Canonicalize setgt X, Min --> setne X, Min
1816 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1817 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1818 // Canonicalize setlt X, Max --> setne X, Max
1819 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1820 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
Evan Cheng92658d52007-02-08 22:13:59 +00001821
Eli Friedman65919b52009-07-26 23:47:17 +00001822 // If we have setult X, 1, turn it into seteq X, 0
1823 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
Wesley Peck527da1b2010-11-23 03:31:01 +00001824 return DAG.getSetCC(dl, VT, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001825 DAG.getConstant(MinVal, dl, N0.getValueType()),
Eli Friedman65919b52009-07-26 23:47:17 +00001826 ISD::SETEQ);
1827 // If we have setugt X, Max-1, turn it into seteq X, Max
Craig Topper3f194c82012-12-19 06:43:58 +00001828 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
Wesley Peck527da1b2010-11-23 03:31:01 +00001829 return DAG.getSetCC(dl, VT, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001830 DAG.getConstant(MaxVal, dl, N0.getValueType()),
Eli Friedman65919b52009-07-26 23:47:17 +00001831 ISD::SETEQ);
Evan Cheng92658d52007-02-08 22:13:59 +00001832
Eli Friedman65919b52009-07-26 23:47:17 +00001833 // If we have "setcc X, C0", check to see if we can shrink the immediate
1834 // by changing cc.
Evan Cheng92658d52007-02-08 22:13:59 +00001835
Eli Friedman65919b52009-07-26 23:47:17 +00001836 // SETUGT X, SINTMAX -> SETLT X, 0
Wesley Peck527da1b2010-11-23 03:31:01 +00001837 if (Cond == ISD::SETUGT &&
Eli Friedman65919b52009-07-26 23:47:17 +00001838 C1 == APInt::getSignedMaxValue(OperandBitSize))
Wesley Peck527da1b2010-11-23 03:31:01 +00001839 return DAG.getSetCC(dl, VT, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001840 DAG.getConstant(0, dl, N1.getValueType()),
Eli Friedman65919b52009-07-26 23:47:17 +00001841 ISD::SETLT);
Evan Cheng92658d52007-02-08 22:13:59 +00001842
Eli Friedman65919b52009-07-26 23:47:17 +00001843 // SETULT X, SINTMIN -> SETGT X, -1
1844 if (Cond == ISD::SETULT &&
1845 C1 == APInt::getSignedMinValue(OperandBitSize)) {
1846 SDValue ConstMinusOne =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001847 DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl,
Eli Friedman65919b52009-07-26 23:47:17 +00001848 N1.getValueType());
1849 return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
1850 }
Evan Cheng92658d52007-02-08 22:13:59 +00001851
Eli Friedman65919b52009-07-26 23:47:17 +00001852 // Fold bit comparisons when we can.
1853 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
Evan Cheng166a4e62010-01-06 19:38:29 +00001854 (VT == N0.getValueType() ||
1855 (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
Mehdi Amini44ede332015-07-09 02:09:04 +00001856 N0.getOpcode() == ISD::AND) {
1857 auto &DL = DAG.getDataLayout();
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001858 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001859 EVT ShiftTy = DCI.isBeforeLegalize()
1860 ? getPointerTy(DL)
Mehdi Amini9639d652015-07-09 02:09:20 +00001861 : getShiftAmountTy(N0.getValueType(), DL);
Eli Friedman65919b52009-07-26 23:47:17 +00001862 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
1863 // Perform the xform if the AND RHS is a single bit.
Evan Cheng16b75ce2010-01-07 20:58:44 +00001864 if (AndRHS->getAPIntValue().isPowerOf2()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00001865 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1866 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001867 DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl,
1868 ShiftTy)));
Eli Friedman65919b52009-07-26 23:47:17 +00001869 }
Evan Cheng16b75ce2010-01-07 20:58:44 +00001870 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
Eli Friedman65919b52009-07-26 23:47:17 +00001871 // (X & 8) == 8 --> (X & 8) >> 3
1872 // Perform the xform if C1 is a single bit.
1873 if (C1.isPowerOf2()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00001874 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1875 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001876 DAG.getConstant(C1.logBase2(), dl,
1877 ShiftTy)));
Evan Cheng92658d52007-02-08 22:13:59 +00001878 }
1879 }
Eli Friedman65919b52009-07-26 23:47:17 +00001880 }
Mehdi Amini44ede332015-07-09 02:09:04 +00001881 }
Evan Chengf579bec2012-07-17 06:53:39 +00001882
Evan Cheng47d7be92012-07-17 07:47:50 +00001883 if (C1.getMinSignedBits() <= 64 &&
1884 !isLegalICmpImmediate(C1.getSExtValue())) {
Evan Chengf579bec2012-07-17 06:53:39 +00001885 // (X & -256) == 256 -> (X >> 8) == 1
1886 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1887 N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001888 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Evan Chengf579bec2012-07-17 06:53:39 +00001889 const APInt &AndRHSC = AndRHS->getAPIntValue();
1890 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
1891 unsigned ShiftBits = AndRHSC.countTrailingZeros();
Mehdi Amini44ede332015-07-09 02:09:04 +00001892 auto &DL = DAG.getDataLayout();
1893 EVT ShiftTy = DCI.isBeforeLegalize()
1894 ? getPointerTy(DL)
Mehdi Amini9639d652015-07-09 02:09:20 +00001895 : getShiftAmountTy(N0.getValueType(), DL);
Evan Chengf579bec2012-07-17 06:53:39 +00001896 EVT CmpTy = N0.getValueType();
1897 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001898 DAG.getConstant(ShiftBits, dl,
1899 ShiftTy));
1900 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy);
Evan Chengf579bec2012-07-17 06:53:39 +00001901 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
1902 }
1903 }
Evan Cheng780f9b52012-07-17 08:31:11 +00001904 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
1905 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
1906 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
1907 // X < 0x100000000 -> (X >> 32) < 1
1908 // X >= 0x100000000 -> (X >> 32) >= 1
1909 // X <= 0x0ffffffff -> (X >> 32) < 1
1910 // X > 0x0ffffffff -> (X >> 32) >= 1
1911 unsigned ShiftBits;
1912 APInt NewC = C1;
1913 ISD::CondCode NewCond = Cond;
1914 if (AdjOne) {
1915 ShiftBits = C1.countTrailingOnes();
1916 NewC = NewC + 1;
1917 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1918 } else {
1919 ShiftBits = C1.countTrailingZeros();
1920 }
1921 NewC = NewC.lshr(ShiftBits);
Pawel Bylica8011da92015-05-20 17:21:09 +00001922 if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
1923 isLegalICmpImmediate(NewC.getSExtValue())) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001924 auto &DL = DAG.getDataLayout();
1925 EVT ShiftTy = DCI.isBeforeLegalize()
1926 ? getPointerTy(DL)
Mehdi Amini9639d652015-07-09 02:09:20 +00001927 : getShiftAmountTy(N0.getValueType(), DL);
Evan Cheng780f9b52012-07-17 08:31:11 +00001928 EVT CmpTy = N0.getValueType();
1929 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001930 DAG.getConstant(ShiftBits, dl, ShiftTy));
1931 SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy);
Evan Cheng780f9b52012-07-17 08:31:11 +00001932 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
1933 }
Evan Chengf579bec2012-07-17 06:53:39 +00001934 }
1935 }
Evan Cheng92658d52007-02-08 22:13:59 +00001936 }
1937
Gabor Greiff304a7a2008-08-28 21:40:38 +00001938 if (isa<ConstantFPSDNode>(N0.getNode())) {
Evan Cheng92658d52007-02-08 22:13:59 +00001939 // Constant fold or commute setcc.
Dale Johannesenf1163e92009-02-03 00:47:48 +00001940 SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001941 if (O.getNode()) return O;
Sanjay Patel7a7abc92015-12-29 21:49:08 +00001942 } else if (auto *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
Chris Lattner3b6a8212007-12-29 08:37:08 +00001943 // If the RHS of an FP comparison is a constant, simplify it away in
1944 // some cases.
1945 if (CFP->getValueAPF().isNaN()) {
1946 // If an operand is known to be a nan, we can fold it.
1947 switch (ISD::getUnorderedFlavor(Cond)) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001948 default: llvm_unreachable("Unknown flavor!");
Chris Lattner3b6a8212007-12-29 08:37:08 +00001949 case 0: // Known false.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001950 return DAG.getConstant(0, dl, VT);
Chris Lattner3b6a8212007-12-29 08:37:08 +00001951 case 1: // Known true.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001952 return DAG.getConstant(1, dl, VT);
Chris Lattner96317d22007-12-30 21:21:10 +00001953 case 2: // Undefined.
Dale Johannesen84935752009-02-06 23:05:02 +00001954 return DAG.getUNDEF(VT);
Chris Lattner3b6a8212007-12-29 08:37:08 +00001955 }
1956 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001957
Chris Lattner3b6a8212007-12-29 08:37:08 +00001958 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
1959 // constant if knowing that the operand is non-nan is enough. We prefer to
1960 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
1961 // materialize 0.0.
1962 if (Cond == ISD::SETO || Cond == ISD::SETUO)
Dale Johannesenf1163e92009-02-03 00:47:48 +00001963 return DAG.getSetCC(dl, VT, N0, N0, Cond);
Dan Gohman832800a2009-09-26 15:24:17 +00001964
1965 // If the condition is not legal, see if we can find an equivalent one
1966 // which is legal.
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001967 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
Dan Gohman832800a2009-09-26 15:24:17 +00001968 // If the comparison was an awkward floating-point == or != and one of
1969 // the comparison operands is infinity or negative infinity, convert the
1970 // condition to a less-awkward <= or >=.
1971 if (CFP->getValueAPF().isInfinity()) {
1972 if (CFP->getValueAPF().isNegative()) {
1973 if (Cond == ISD::SETOEQ &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001974 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001975 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
1976 if (Cond == ISD::SETUEQ &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001977 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001978 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
1979 if (Cond == ISD::SETUNE &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001980 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001981 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
1982 if (Cond == ISD::SETONE &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001983 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001984 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
1985 } else {
1986 if (Cond == ISD::SETOEQ &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001987 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001988 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
1989 if (Cond == ISD::SETUEQ &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001990 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001991 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
1992 if (Cond == ISD::SETUNE &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001993 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001994 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
1995 if (Cond == ISD::SETONE &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00001996 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
Dan Gohman832800a2009-09-26 15:24:17 +00001997 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
1998 }
1999 }
2000 }
Evan Cheng92658d52007-02-08 22:13:59 +00002001 }
2002
2003 if (N0 == N1) {
Duncan Sands0552a2c2012-07-05 09:32:46 +00002004 // The sext(setcc()) => setcc() optimization relies on the appropriate
2005 // constant being emitted.
Nadav Rotema8e15b02012-09-06 11:13:55 +00002006 uint64_t EqVal = 0;
Daniel Sanderscbd44c52014-07-10 10:18:12 +00002007 switch (getBooleanContents(N0.getValueType())) {
Duncan Sands0552a2c2012-07-05 09:32:46 +00002008 case UndefinedBooleanContent:
2009 case ZeroOrOneBooleanContent:
2010 EqVal = ISD::isTrueWhenEqual(Cond);
2011 break;
2012 case ZeroOrNegativeOneBooleanContent:
2013 EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0;
2014 break;
2015 }
2016
Evan Cheng92658d52007-02-08 22:13:59 +00002017 // We can always fold X == X for integer setcc's.
Chad Rosier2a02fe12012-04-03 20:11:24 +00002018 if (N0.getValueType().isInteger()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002019 return DAG.getConstant(EqVal, dl, VT);
Chad Rosier2a02fe12012-04-03 20:11:24 +00002020 }
Evan Cheng92658d52007-02-08 22:13:59 +00002021 unsigned UOF = ISD::getUnorderedFlavor(Cond);
2022 if (UOF == 2) // FP operators that are undefined on NaNs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002023 return DAG.getConstant(EqVal, dl, VT);
Evan Cheng92658d52007-02-08 22:13:59 +00002024 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002025 return DAG.getConstant(EqVal, dl, VT);
Evan Cheng92658d52007-02-08 22:13:59 +00002026 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
2027 // if it is not already.
2028 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
Micah Villmowb67d7a32012-07-31 18:07:43 +00002029 if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
Patrik Hagglunddeee9002012-12-19 10:09:26 +00002030 getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
Dale Johannesenf1163e92009-02-03 00:47:48 +00002031 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
Evan Cheng92658d52007-02-08 22:13:59 +00002032 }
2033
2034 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002035 N0.getValueType().isInteger()) {
Evan Cheng92658d52007-02-08 22:13:59 +00002036 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
2037 N0.getOpcode() == ISD::XOR) {
2038 // Simplify (X+Y) == (X+Z) --> Y == Z
2039 if (N0.getOpcode() == N1.getOpcode()) {
2040 if (N0.getOperand(0) == N1.getOperand(0))
Dale Johannesenf1163e92009-02-03 00:47:48 +00002041 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002042 if (N0.getOperand(1) == N1.getOperand(1))
Dale Johannesenf1163e92009-02-03 00:47:48 +00002043 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002044 if (DAG.isCommutativeBinOp(N0.getOpcode())) {
2045 // If X op Y == Y op X, try other combinations.
2046 if (N0.getOperand(0) == N1.getOperand(1))
Wesley Peck527da1b2010-11-23 03:31:01 +00002047 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
Dale Johannesenf1163e92009-02-03 00:47:48 +00002048 Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002049 if (N0.getOperand(1) == N1.getOperand(0))
Wesley Peck527da1b2010-11-23 03:31:01 +00002050 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00002051 Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002052 }
2053 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002054
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002055 // If RHS is a legal immediate value for a compare instruction, we need
2056 // to be careful about increasing register pressure needlessly.
2057 bool LegalRHSImm = false;
2058
Sanjay Patel7a7abc92015-12-29 21:49:08 +00002059 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
2060 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Evan Cheng92658d52007-02-08 22:13:59 +00002061 // Turn (X+C1) == C2 --> X == C2-C1
Gabor Greiff304a7a2008-08-28 21:40:38 +00002062 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
Dale Johannesenf1163e92009-02-03 00:47:48 +00002063 return DAG.getSetCC(dl, VT, N0.getOperand(0),
Dan Gohmaneffb8942008-09-12 16:56:44 +00002064 DAG.getConstant(RHSC->getAPIntValue()-
2065 LHSR->getAPIntValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002066 dl, N0.getValueType()), Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002067 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002068
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002069 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
Evan Cheng92658d52007-02-08 22:13:59 +00002070 if (N0.getOpcode() == ISD::XOR)
2071 // If we know that all of the inverted bits are zero, don't bother
2072 // performing the inversion.
Dan Gohman1f372ed2008-02-25 21:11:39 +00002073 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
2074 return
Dale Johannesenf1163e92009-02-03 00:47:48 +00002075 DAG.getSetCC(dl, VT, N0.getOperand(0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002076 DAG.getConstant(LHSR->getAPIntValue() ^
2077 RHSC->getAPIntValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002078 dl, N0.getValueType()),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002079 Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002080 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002081
Evan Cheng92658d52007-02-08 22:13:59 +00002082 // Turn (C1-X) == C2 --> X == C1-C2
Sanjay Patel7a7abc92015-12-29 21:49:08 +00002083 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00002084 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002085 return
Dale Johannesenf1163e92009-02-03 00:47:48 +00002086 DAG.getSetCC(dl, VT, N0.getOperand(1),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002087 DAG.getConstant(SUBC->getAPIntValue() -
2088 RHSC->getAPIntValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002089 dl, N0.getValueType()),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002090 Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002091 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002092 }
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002093
2094 // Could RHSC fold directly into a compare?
2095 if (RHSC->getValueType(0).getSizeInBits() <= 64)
2096 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
Evan Cheng92658d52007-02-08 22:13:59 +00002097 }
2098
2099 // Simplify (X+Z) == X --> Z == 0
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002100 // Don't do this if X is an immediate that can fold into a cmp
2101 // instruction and X+Z has other uses. It could be an induction variable
2102 // chain, and the transform would increase register pressure.
2103 if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
2104 if (N0.getOperand(0) == N1)
2105 return DAG.getSetCC(dl, VT, N0.getOperand(1),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002106 DAG.getConstant(0, dl, N0.getValueType()), Cond);
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002107 if (N0.getOperand(1) == N1) {
2108 if (DAG.isCommutativeBinOp(N0.getOpcode()))
2109 return DAG.getSetCC(dl, VT, N0.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002110 DAG.getConstant(0, dl, N0.getValueType()),
2111 Cond);
Craig Topper3f194c82012-12-19 06:43:58 +00002112 if (N0.getNode()->hasOneUse()) {
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002113 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
Mehdi Amini9639d652015-07-09 02:09:20 +00002114 auto &DL = DAG.getDataLayout();
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002115 // (Z-X) == X --> Z == X<<1
Mehdi Amini9639d652015-07-09 02:09:20 +00002116 SDValue SH = DAG.getNode(
2117 ISD::SHL, dl, N1.getValueType(), N1,
2118 DAG.getConstant(1, dl,
2119 getShiftAmountTy(N1.getValueType(), DL)));
Jakob Stoklund Olesen37492ea2012-04-05 20:30:20 +00002120 if (!DCI.isCalledByLegalizer())
2121 DCI.AddToWorklist(SH.getNode());
2122 return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
2123 }
Evan Cheng92658d52007-02-08 22:13:59 +00002124 }
2125 }
2126 }
2127
2128 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
2129 N1.getOpcode() == ISD::XOR) {
2130 // Simplify X == (X+Z) --> Z == 0
Craig Topper3f194c82012-12-19 06:43:58 +00002131 if (N1.getOperand(0) == N0)
Dale Johannesenf1163e92009-02-03 00:47:48 +00002132 return DAG.getSetCC(dl, VT, N1.getOperand(1),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002133 DAG.getConstant(0, dl, N1.getValueType()), Cond);
Craig Topper3f194c82012-12-19 06:43:58 +00002134 if (N1.getOperand(1) == N0) {
2135 if (DAG.isCommutativeBinOp(N1.getOpcode()))
Dale Johannesenf1163e92009-02-03 00:47:48 +00002136 return DAG.getSetCC(dl, VT, N1.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002137 DAG.getConstant(0, dl, N1.getValueType()), Cond);
Craig Topper3f194c82012-12-19 06:43:58 +00002138 if (N1.getNode()->hasOneUse()) {
Evan Cheng92658d52007-02-08 22:13:59 +00002139 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
Mehdi Amini9639d652015-07-09 02:09:20 +00002140 auto &DL = DAG.getDataLayout();
Evan Cheng92658d52007-02-08 22:13:59 +00002141 // X == (Z-X) --> X<<1 == Z
Mehdi Amini9639d652015-07-09 02:09:20 +00002142 SDValue SH = DAG.getNode(
2143 ISD::SHL, dl, N1.getValueType(), N0,
2144 DAG.getConstant(1, dl, getShiftAmountTy(N0.getValueType(), DL)));
Evan Cheng92658d52007-02-08 22:13:59 +00002145 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002146 DCI.AddToWorklist(SH.getNode());
Dale Johannesenf1163e92009-02-03 00:47:48 +00002147 return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
Evan Cheng92658d52007-02-08 22:13:59 +00002148 }
2149 }
2150 }
Dan Gohmane58ab792009-01-29 01:59:02 +00002151
Sanjay Patel91592562016-05-09 16:42:50 +00002152 if (SDValue V = simplifySetCCWithAnd(VT, N0, N1, Cond, DCI, dl))
2153 return V;
Evan Cheng92658d52007-02-08 22:13:59 +00002154 }
2155
2156 // Fold away ALL boolean setcc's.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002157 SDValue Temp;
Owen Anderson9f944592009-08-11 20:47:22 +00002158 if (N0.getValueType() == MVT::i1 && foldBooleans) {
Evan Cheng92658d52007-02-08 22:13:59 +00002159 switch (Cond) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00002160 default: llvm_unreachable("Unknown integer setcc!");
Bob Wilsonc5890052009-01-22 17:39:32 +00002161 case ISD::SETEQ: // X == Y -> ~(X^Y)
Owen Anderson9f944592009-08-11 20:47:22 +00002162 Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2163 N0 = DAG.getNOT(dl, Temp, MVT::i1);
Evan Cheng92658d52007-02-08 22:13:59 +00002164 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002165 DCI.AddToWorklist(Temp.getNode());
Evan Cheng92658d52007-02-08 22:13:59 +00002166 break;
2167 case ISD::SETNE: // X != Y --> (X^Y)
Owen Anderson9f944592009-08-11 20:47:22 +00002168 N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
Evan Cheng92658d52007-02-08 22:13:59 +00002169 break;
Bob Wilsonc5890052009-01-22 17:39:32 +00002170 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
2171 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
Owen Anderson9f944592009-08-11 20:47:22 +00002172 Temp = DAG.getNOT(dl, N0, MVT::i1);
2173 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
Evan Cheng92658d52007-02-08 22:13:59 +00002174 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002175 DCI.AddToWorklist(Temp.getNode());
Evan Cheng92658d52007-02-08 22:13:59 +00002176 break;
Bob Wilsonc5890052009-01-22 17:39:32 +00002177 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
2178 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
Owen Anderson9f944592009-08-11 20:47:22 +00002179 Temp = DAG.getNOT(dl, N1, MVT::i1);
2180 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
Evan Cheng92658d52007-02-08 22:13:59 +00002181 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002182 DCI.AddToWorklist(Temp.getNode());
Evan Cheng92658d52007-02-08 22:13:59 +00002183 break;
Bob Wilsonc5890052009-01-22 17:39:32 +00002184 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
2185 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
Owen Anderson9f944592009-08-11 20:47:22 +00002186 Temp = DAG.getNOT(dl, N0, MVT::i1);
2187 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
Evan Cheng92658d52007-02-08 22:13:59 +00002188 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002189 DCI.AddToWorklist(Temp.getNode());
Evan Cheng92658d52007-02-08 22:13:59 +00002190 break;
Bob Wilsonc5890052009-01-22 17:39:32 +00002191 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
2192 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
Owen Anderson9f944592009-08-11 20:47:22 +00002193 Temp = DAG.getNOT(dl, N1, MVT::i1);
2194 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
Evan Cheng92658d52007-02-08 22:13:59 +00002195 break;
2196 }
Owen Anderson9f944592009-08-11 20:47:22 +00002197 if (VT != MVT::i1) {
Evan Cheng92658d52007-02-08 22:13:59 +00002198 if (!DCI.isCalledByLegalizer())
Gabor Greiff304a7a2008-08-28 21:40:38 +00002199 DCI.AddToWorklist(N0.getNode());
Evan Cheng92658d52007-02-08 22:13:59 +00002200 // FIXME: If running after legalize, we probably can't do this.
Dale Johannesenf1163e92009-02-03 00:47:48 +00002201 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
Evan Cheng92658d52007-02-08 22:13:59 +00002202 }
2203 return N0;
2204 }
2205
2206 // Could not fold it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002207 return SDValue();
Evan Cheng92658d52007-02-08 22:13:59 +00002208}
2209
Sanjay Patelac6e9102015-12-29 22:11:50 +00002210/// Returns true (and the GlobalValue and the offset) if the node is a
2211/// GlobalAddress + offset.
Chris Lattner46c01a32011-02-13 22:25:43 +00002212bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
Evan Cheng2609d5e2008-05-12 19:56:52 +00002213 int64_t &Offset) const {
Sanjay Pateld1d9db52015-12-29 22:00:37 +00002214 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
Dan Gohmane38cc012008-06-09 22:05:52 +00002215 GA = GASD->getGlobal();
2216 Offset += GASD->getOffset();
Evan Cheng2609d5e2008-05-12 19:56:52 +00002217 return true;
2218 }
2219
2220 if (N->getOpcode() == ISD::ADD) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002221 SDValue N1 = N->getOperand(0);
2222 SDValue N2 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002223 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
Sanjay Pateld1d9db52015-12-29 22:00:37 +00002224 if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
Dan Gohman6e054832008-09-26 21:54:37 +00002225 Offset += V->getSExtValue();
Evan Cheng2609d5e2008-05-12 19:56:52 +00002226 return true;
2227 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00002228 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
Sanjay Pateld1d9db52015-12-29 22:00:37 +00002229 if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
Dan Gohman6e054832008-09-26 21:54:37 +00002230 Offset += V->getSExtValue();
Evan Cheng2609d5e2008-05-12 19:56:52 +00002231 return true;
2232 }
2233 }
2234 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002235
Evan Cheng2609d5e2008-05-12 19:56:52 +00002236 return false;
2237}
2238
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +00002239SDValue TargetLowering::PerformDAGCombine(SDNode *N,
2240 DAGCombinerInfo &DCI) const {
Chris Lattner4a2eeea2006-03-01 04:52:55 +00002241 // Default implementation: no optimization.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002242 return SDValue();
Chris Lattner4a2eeea2006-03-01 04:52:55 +00002243}
2244
Chris Lattneree1dadb2006-02-04 02:13:02 +00002245//===----------------------------------------------------------------------===//
2246// Inline Assembler Implementation Methods
2247//===----------------------------------------------------------------------===//
2248
2249TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00002250TargetLowering::getConstraintType(StringRef Constraint) const {
Eric Christopher0cb6fd92013-01-11 18:12:39 +00002251 unsigned S = Constraint.size();
2252
2253 if (S == 1) {
Chris Lattnerd6855142007-03-25 02:14:49 +00002254 switch (Constraint[0]) {
2255 default: break;
2256 case 'r': return C_RegisterClass;
2257 case 'm': // memory
2258 case 'o': // offsetable
2259 case 'V': // not offsetable
2260 return C_Memory;
2261 case 'i': // Simple Integer or Relocatable Constant
2262 case 'n': // Simple Integer
John Thompsonc467aa22010-09-21 22:04:54 +00002263 case 'E': // Floating Point Constant
2264 case 'F': // Floating Point Constant
Chris Lattnerd6855142007-03-25 02:14:49 +00002265 case 's': // Relocatable Constant
John Thompsonc467aa22010-09-21 22:04:54 +00002266 case 'p': // Address.
Chris Lattner3d7efa22007-03-25 04:35:41 +00002267 case 'X': // Allow ANY value.
Chris Lattnerd6855142007-03-25 02:14:49 +00002268 case 'I': // Target registers.
2269 case 'J':
2270 case 'K':
2271 case 'L':
2272 case 'M':
2273 case 'N':
2274 case 'O':
2275 case 'P':
John Thompsonc467aa22010-09-21 22:04:54 +00002276 case '<':
2277 case '>':
Chris Lattnerd6855142007-03-25 02:14:49 +00002278 return C_Other;
2279 }
Chris Lattneree1dadb2006-02-04 02:13:02 +00002280 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002281
Eric Christopher0cb6fd92013-01-11 18:12:39 +00002282 if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00002283 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
Eric Christopher0cb6fd92013-01-11 18:12:39 +00002284 return C_Memory;
Chris Lattner843e4452007-03-25 02:18:14 +00002285 return C_Register;
Eric Christopher0cb6fd92013-01-11 18:12:39 +00002286 }
Chris Lattnerd6855142007-03-25 02:14:49 +00002287 return C_Unknown;
Chris Lattneree1dadb2006-02-04 02:13:02 +00002288}
2289
Sanjay Patelac6e9102015-12-29 22:11:50 +00002290/// Try to replace an X constraint, which matches anything, with another that
2291/// has more specific requirements based on the type of the corresponding
2292/// operand.
Owen Anderson53aa7a92009-08-10 22:56:29 +00002293const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
Duncan Sands13237ac2008-06-06 12:08:01 +00002294 if (ConstraintVT.isInteger())
Chris Lattner724539c2008-04-26 23:02:14 +00002295 return "r";
Duncan Sands13237ac2008-06-06 12:08:01 +00002296 if (ConstraintVT.isFloatingPoint())
Chris Lattner724539c2008-04-26 23:02:14 +00002297 return "f"; // works for many targets
Craig Topperc0196b12014-04-14 00:51:57 +00002298 return nullptr;
Dale Johannesen2b3bc302008-01-29 02:21:21 +00002299}
2300
Sanjay Patelac6e9102015-12-29 22:11:50 +00002301/// Lower the specified operand into the Ops vector.
2302/// If it is invalid, don't add anything to Ops.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002303void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
Eric Christopherde9399b2011-06-02 23:16:42 +00002304 std::string &Constraint,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002305 std::vector<SDValue> &Ops,
Chris Lattner724539c2008-04-26 23:02:14 +00002306 SelectionDAG &DAG) const {
Eric Christopher5bbb2bd2011-06-17 20:41:29 +00002307
Eric Christopherde9399b2011-06-02 23:16:42 +00002308 if (Constraint.length() > 1) return;
Eric Christopher5bbb2bd2011-06-17 20:41:29 +00002309
Eric Christopherde9399b2011-06-02 23:16:42 +00002310 char ConstraintLetter = Constraint[0];
Chris Lattneree1dadb2006-02-04 02:13:02 +00002311 switch (ConstraintLetter) {
Chris Lattnera9f917a2007-02-17 06:00:35 +00002312 default: break;
Dale Johannesen4646aa32007-11-05 21:20:28 +00002313 case 'X': // Allows any operand; labels (basic block) use this.
2314 if (Op.getOpcode() == ISD::BasicBlock) {
2315 Ops.push_back(Op);
2316 return;
2317 }
2318 // fall through
Chris Lattneree1dadb2006-02-04 02:13:02 +00002319 case 'i': // Simple Integer or Relocatable Constant
2320 case 'n': // Simple Integer
Dale Johannesen4646aa32007-11-05 21:20:28 +00002321 case 's': { // Relocatable Constant
Chris Lattner44a2ed62007-05-03 16:54:34 +00002322 // These operands are interested in values of the form (GV+C), where C may
2323 // be folded in as an offset of GV, or it may be explicitly added. Also, it
2324 // is possible and fine if either GV or C are missing.
2325 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2326 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
Wesley Peck527da1b2010-11-23 03:31:01 +00002327
Chris Lattner44a2ed62007-05-03 16:54:34 +00002328 // If we have "(add GV, C)", pull out GV/C
2329 if (Op.getOpcode() == ISD::ADD) {
2330 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2331 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
Craig Topperc0196b12014-04-14 00:51:57 +00002332 if (!C || !GA) {
Chris Lattner44a2ed62007-05-03 16:54:34 +00002333 C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
2334 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
2335 }
Richard Trieu7a083812016-02-18 22:09:30 +00002336 if (!C || !GA) {
2337 C = nullptr;
2338 GA = nullptr;
2339 }
Chris Lattner44a2ed62007-05-03 16:54:34 +00002340 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002341
Chris Lattner44a2ed62007-05-03 16:54:34 +00002342 // If we find a valid operand, map to the TargetXXX version so that the
2343 // value itself doesn't get selected.
2344 if (GA) { // Either &GV or &GV+C
2345 if (ConstraintLetter != 'n') {
2346 int64_t Offs = GA->getOffset();
Dan Gohmaneffb8942008-09-12 16:56:44 +00002347 if (C) Offs += C->getZExtValue();
Wesley Peck527da1b2010-11-23 03:31:01 +00002348 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002349 C ? SDLoc(C) : SDLoc(),
Chris Lattnerd8c9cb92007-08-25 00:47:38 +00002350 Op.getValueType(), Offs));
Chris Lattner44a2ed62007-05-03 16:54:34 +00002351 }
James Y Knight46f91c82015-07-13 16:36:22 +00002352 return;
Chris Lattner44a2ed62007-05-03 16:54:34 +00002353 }
2354 if (C) { // just C, no GV.
Chris Lattnera9f917a2007-02-17 06:00:35 +00002355 // Simple constants are not allowed for 's'.
Chris Lattnerd8c9cb92007-08-25 00:47:38 +00002356 if (ConstraintLetter != 's') {
Dale Johannesen65577522009-02-12 20:58:09 +00002357 // gcc prints these as sign extended. Sign extend value to 64 bits
2358 // now; without this it would get ZExt'd later in
2359 // ScheduleDAGSDNodes::EmitNode, which is very generic.
2360 Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002361 SDLoc(C), MVT::i64));
Chris Lattnerd8c9cb92007-08-25 00:47:38 +00002362 }
James Y Knight46f91c82015-07-13 16:36:22 +00002363 return;
Chris Lattnera9f917a2007-02-17 06:00:35 +00002364 }
Chris Lattnera9f917a2007-02-17 06:00:35 +00002365 break;
Chris Lattneree1dadb2006-02-04 02:13:02 +00002366 }
Chris Lattner44a2ed62007-05-03 16:54:34 +00002367 }
Chris Lattneree1dadb2006-02-04 02:13:02 +00002368}
2369
Eric Christopher11e4df72015-02-26 22:38:43 +00002370std::pair<unsigned, const TargetRegisterClass *>
2371TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00002372 StringRef Constraint,
Eric Christopher11e4df72015-02-26 22:38:43 +00002373 MVT VT) const {
Will Dietzae726a92013-10-13 03:08:49 +00002374 if (Constraint.empty() || Constraint[0] != '{')
Craig Topperc0196b12014-04-14 00:51:57 +00002375 return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr));
Chris Lattner7ed31012006-02-01 01:29:47 +00002376 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
2377
2378 // Remove the braces from around the name.
Benjamin Kramer68e49452009-11-12 20:36:59 +00002379 StringRef RegName(Constraint.data()+1, Constraint.size()-2);
Chris Lattner7ad77df2006-02-22 00:56:39 +00002380
Hal Finkel943f76d2012-12-18 17:50:58 +00002381 std::pair<unsigned, const TargetRegisterClass*> R =
Craig Topperc0196b12014-04-14 00:51:57 +00002382 std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr));
Hal Finkel943f76d2012-12-18 17:50:58 +00002383
Chris Lattner7ad77df2006-02-22 00:56:39 +00002384 // Figure out which register class contains this reg.
Dan Gohman3a4be0f2008-02-10 18:45:23 +00002385 for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
Chris Lattner7ad77df2006-02-22 00:56:39 +00002386 E = RI->regclass_end(); RCI != E; ++RCI) {
2387 const TargetRegisterClass *RC = *RCI;
Wesley Peck527da1b2010-11-23 03:31:01 +00002388
2389 // If none of the value types for this register class are valid, we
Chris Lattner2e124af2006-02-22 23:00:51 +00002390 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Jakob Stoklund Olesen35163e22011-10-12 01:24:51 +00002391 if (!isLegalRC(RC))
2392 continue;
Wesley Peck527da1b2010-11-23 03:31:01 +00002393
2394 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002395 I != E; ++I) {
Tom Stellard52686e42016-04-11 16:21:12 +00002396 if (RegName.equals_lower(RI->getRegAsmName(*I))) {
Hal Finkel943f76d2012-12-18 17:50:58 +00002397 std::pair<unsigned, const TargetRegisterClass*> S =
2398 std::make_pair(*I, RC);
2399
2400 // If this register class has the requested value type, return it,
2401 // otherwise keep searching and return the first class found
2402 // if no other is found which explicitly has the requested type.
2403 if (RC->hasType(VT))
2404 return S;
2405 else if (!R.second)
2406 R = S;
2407 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00002408 }
Chris Lattner32fef532006-01-26 20:37:03 +00002409 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002410
Hal Finkel943f76d2012-12-18 17:50:58 +00002411 return R;
Chris Lattner32fef532006-01-26 20:37:03 +00002412}
Evan Chengaf598d22006-03-13 23:18:16 +00002413
2414//===----------------------------------------------------------------------===//
Chris Lattner47935152008-04-27 00:09:47 +00002415// Constraint Selection.
2416
Sanjay Patelac6e9102015-12-29 22:11:50 +00002417/// Return true of this is an input operand that is a matching constraint like
2418/// "4".
Chris Lattner860df6e2008-10-17 16:47:46 +00002419bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
Chris Lattneref890172008-10-17 16:21:11 +00002420 assert(!ConstraintCode.empty() && "No known constraint!");
Guy Benyei83c74e92013-02-12 21:21:59 +00002421 return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
Chris Lattneref890172008-10-17 16:21:11 +00002422}
2423
Sanjay Patelac6e9102015-12-29 22:11:50 +00002424/// If this is an input matching constraint, this method returns the output
2425/// operand it matches.
Chris Lattneref890172008-10-17 16:21:11 +00002426unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
2427 assert(!ConstraintCode.empty() && "No known constraint!");
2428 return atoi(ConstraintCode.c_str());
2429}
2430
Sanjay Patelac6e9102015-12-29 22:11:50 +00002431/// Split up the constraint string from the inline assembly value into the
2432/// specific constraints and their prefixes, and also tie in the associated
2433/// operand values.
John Thompson1094c802010-09-13 18:15:37 +00002434/// If this returns an empty vector, and if the constraint string itself
2435/// isn't empty, there was an error parsing.
Eric Christopher11e4df72015-02-26 22:38:43 +00002436TargetLowering::AsmOperandInfoVector
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00002437TargetLowering::ParseConstraints(const DataLayout &DL,
2438 const TargetRegisterInfo *TRI,
Eric Christopher11e4df72015-02-26 22:38:43 +00002439 ImmutableCallSite CS) const {
Sanjay Patelac6e9102015-12-29 22:11:50 +00002440 /// Information about all of the constraints.
John Thompsone8360b72010-10-29 17:29:13 +00002441 AsmOperandInfoVector ConstraintOperands;
John Thompson1094c802010-09-13 18:15:37 +00002442 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
John Thompsonc467aa22010-09-21 22:04:54 +00002443 unsigned maCount = 0; // Largest number of multiple alternative constraints.
John Thompson1094c802010-09-13 18:15:37 +00002444
2445 // Do a prepass over the constraints, canonicalizing them, and building up the
2446 // ConstraintOperands list.
John Thompson1094c802010-09-13 18:15:37 +00002447 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
2448 unsigned ResNo = 0; // ResNo - The result number of the next output.
2449
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00002450 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2451 ConstraintOperands.emplace_back(std::move(CI));
John Thompson1094c802010-09-13 18:15:37 +00002452 AsmOperandInfo &OpInfo = ConstraintOperands.back();
2453
John Thompsonc467aa22010-09-21 22:04:54 +00002454 // Update multiple alternative constraint count.
2455 if (OpInfo.multipleAlternatives.size() > maCount)
2456 maCount = OpInfo.multipleAlternatives.size();
2457
John Thompsone8360b72010-10-29 17:29:13 +00002458 OpInfo.ConstraintVT = MVT::Other;
John Thompson1094c802010-09-13 18:15:37 +00002459
2460 // Compute the value type for each operand.
2461 switch (OpInfo.Type) {
2462 case InlineAsm::isOutput:
2463 // Indirect outputs just consume an argument.
2464 if (OpInfo.isIndirect) {
2465 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2466 break;
2467 }
2468
2469 // The return value of the call is this value. As such, there is no
2470 // corresponding argument.
2471 assert(!CS.getType()->isVoidTy() &&
2472 "Bad inline asm!");
Chris Lattner229907c2011-07-18 04:54:35 +00002473 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002474 OpInfo.ConstraintVT =
2475 getSimpleValueType(DL, STy->getElementType(ResNo));
John Thompson1094c802010-09-13 18:15:37 +00002476 } else {
2477 assert(ResNo == 0 && "Asm only has one result!");
Mehdi Amini44ede332015-07-09 02:09:04 +00002478 OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType());
John Thompson1094c802010-09-13 18:15:37 +00002479 }
2480 ++ResNo;
2481 break;
2482 case InlineAsm::isInput:
2483 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2484 break;
2485 case InlineAsm::isClobber:
2486 // Nothing to do.
2487 break;
2488 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002489
John Thompsone8360b72010-10-29 17:29:13 +00002490 if (OpInfo.CallOperandVal) {
Chris Lattner229907c2011-07-18 04:54:35 +00002491 llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
John Thompsone8360b72010-10-29 17:29:13 +00002492 if (OpInfo.isIndirect) {
Chris Lattner229907c2011-07-18 04:54:35 +00002493 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
John Thompsone8360b72010-10-29 17:29:13 +00002494 if (!PtrTy)
2495 report_fatal_error("Indirect operand for inline asm not a pointer!");
2496 OpTy = PtrTy->getElementType();
2497 }
Eric Christopher5bbb2bd2011-06-17 20:41:29 +00002498
Eric Christopher44804282011-05-09 20:04:43 +00002499 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
Chris Lattner229907c2011-07-18 04:54:35 +00002500 if (StructType *STy = dyn_cast<StructType>(OpTy))
Eric Christopher44804282011-05-09 20:04:43 +00002501 if (STy->getNumElements() == 1)
2502 OpTy = STy->getElementType(0);
2503
John Thompsone8360b72010-10-29 17:29:13 +00002504 // If OpTy is not a single value, it may be a struct/union that we
2505 // can tile with integers.
2506 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00002507 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
John Thompsone8360b72010-10-29 17:29:13 +00002508 switch (BitSize) {
2509 default: break;
2510 case 1:
2511 case 8:
2512 case 16:
2513 case 32:
2514 case 64:
2515 case 128:
Dale Johannesenf11ea9c2010-11-09 01:15:07 +00002516 OpInfo.ConstraintVT =
Patrik Hagglundf9934612012-12-19 15:19:11 +00002517 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
John Thompsone8360b72010-10-29 17:29:13 +00002518 break;
2519 }
Micah Villmow89021e42012-10-09 16:06:12 +00002520 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00002521 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
Matt Arsenaulta98c3b12013-10-10 19:09:05 +00002522 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
John Thompsone8360b72010-10-29 17:29:13 +00002523 } else {
Patrik Hagglundf9934612012-12-19 15:19:11 +00002524 OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
John Thompsone8360b72010-10-29 17:29:13 +00002525 }
2526 }
John Thompson1094c802010-09-13 18:15:37 +00002527 }
2528
2529 // If we have multiple alternative constraints, select the best alternative.
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00002530 if (!ConstraintOperands.empty()) {
John Thompson1094c802010-09-13 18:15:37 +00002531 if (maCount) {
2532 unsigned bestMAIndex = 0;
2533 int bestWeight = -1;
2534 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
2535 int weight = -1;
2536 unsigned maIndex;
2537 // Compute the sums of the weights for each alternative, keeping track
2538 // of the best (highest weight) one so far.
2539 for (maIndex = 0; maIndex < maCount; ++maIndex) {
2540 int weightSum = 0;
2541 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2542 cIndex != eIndex; ++cIndex) {
2543 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2544 if (OpInfo.Type == InlineAsm::isClobber)
2545 continue;
John Thompson1094c802010-09-13 18:15:37 +00002546
John Thompsone8360b72010-10-29 17:29:13 +00002547 // If this is an output operand with a matching input operand,
2548 // look up the matching input. If their types mismatch, e.g. one
2549 // is an integer, the other is floating point, or their sizes are
2550 // different, flag it as an maCantMatch.
John Thompson1094c802010-09-13 18:15:37 +00002551 if (OpInfo.hasMatchingInput()) {
2552 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
John Thompson1094c802010-09-13 18:15:37 +00002553 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2554 if ((OpInfo.ConstraintVT.isInteger() !=
2555 Input.ConstraintVT.isInteger()) ||
2556 (OpInfo.ConstraintVT.getSizeInBits() !=
2557 Input.ConstraintVT.getSizeInBits())) {
2558 weightSum = -1; // Can't match.
2559 break;
2560 }
John Thompson1094c802010-09-13 18:15:37 +00002561 }
2562 }
John Thompson1094c802010-09-13 18:15:37 +00002563 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
2564 if (weight == -1) {
2565 weightSum = -1;
2566 break;
2567 }
2568 weightSum += weight;
2569 }
2570 // Update best.
2571 if (weightSum > bestWeight) {
2572 bestWeight = weightSum;
2573 bestMAIndex = maIndex;
2574 }
2575 }
2576
2577 // Now select chosen alternative in each constraint.
2578 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2579 cIndex != eIndex; ++cIndex) {
2580 AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
2581 if (cInfo.Type == InlineAsm::isClobber)
2582 continue;
2583 cInfo.selectAlternative(bestMAIndex);
2584 }
2585 }
2586 }
2587
2588 // Check and hook up tied operands, choose constraint code to use.
2589 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2590 cIndex != eIndex; ++cIndex) {
2591 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
Wesley Peck527da1b2010-11-23 03:31:01 +00002592
John Thompson1094c802010-09-13 18:15:37 +00002593 // If this is an output operand with a matching input operand, look up the
2594 // matching input. If their types mismatch, e.g. one is an integer, the
2595 // other is floating point, or their sizes are different, flag it as an
2596 // error.
2597 if (OpInfo.hasMatchingInput()) {
2598 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
John Thompsone8360b72010-10-29 17:29:13 +00002599
John Thompson1094c802010-09-13 18:15:37 +00002600 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Eric Christopher11e4df72015-02-26 22:38:43 +00002601 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
2602 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
2603 OpInfo.ConstraintVT);
2604 std::pair<unsigned, const TargetRegisterClass *> InputRC =
2605 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
2606 Input.ConstraintVT);
John Thompson1094c802010-09-13 18:15:37 +00002607 if ((OpInfo.ConstraintVT.isInteger() !=
2608 Input.ConstraintVT.isInteger()) ||
Eric Christopher92464be2011-07-14 20:13:52 +00002609 (MatchRC.second != InputRC.second)) {
John Thompson1094c802010-09-13 18:15:37 +00002610 report_fatal_error("Unsupported asm: input constraint"
2611 " with a matching output constraint of"
2612 " incompatible type!");
2613 }
John Thompson1094c802010-09-13 18:15:37 +00002614 }
2615 }
2616 }
2617
2618 return ConstraintOperands;
2619}
2620
Sanjay Patelac6e9102015-12-29 22:11:50 +00002621/// Return an integer indicating how general CT is.
Chris Lattner47935152008-04-27 00:09:47 +00002622static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2623 switch (CT) {
Chris Lattner47935152008-04-27 00:09:47 +00002624 case TargetLowering::C_Other:
2625 case TargetLowering::C_Unknown:
2626 return 0;
2627 case TargetLowering::C_Register:
2628 return 1;
2629 case TargetLowering::C_RegisterClass:
2630 return 2;
2631 case TargetLowering::C_Memory:
2632 return 3;
2633 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00002634 llvm_unreachable("Invalid constraint type");
Chris Lattner47935152008-04-27 00:09:47 +00002635}
2636
John Thompsone8360b72010-10-29 17:29:13 +00002637/// Examine constraint type and operand type and determine a weight value.
John Thompson1094c802010-09-13 18:15:37 +00002638/// This object must already have been set up with the operand type
2639/// and the current alternative constraint selected.
John Thompsone8360b72010-10-29 17:29:13 +00002640TargetLowering::ConstraintWeight
2641 TargetLowering::getMultipleConstraintMatchWeight(
John Thompson1094c802010-09-13 18:15:37 +00002642 AsmOperandInfo &info, int maIndex) const {
John Thompsone8360b72010-10-29 17:29:13 +00002643 InlineAsm::ConstraintCodeVector *rCodes;
John Thompsonc467aa22010-09-21 22:04:54 +00002644 if (maIndex >= (int)info.multipleAlternatives.size())
2645 rCodes = &info.Codes;
2646 else
2647 rCodes = &info.multipleAlternatives[maIndex].Codes;
John Thompsone8360b72010-10-29 17:29:13 +00002648 ConstraintWeight BestWeight = CW_Invalid;
John Thompson1094c802010-09-13 18:15:37 +00002649
2650 // Loop over the options, keeping track of the most general one.
John Thompsonc467aa22010-09-21 22:04:54 +00002651 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
John Thompsone8360b72010-10-29 17:29:13 +00002652 ConstraintWeight weight =
2653 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
John Thompson1094c802010-09-13 18:15:37 +00002654 if (weight > BestWeight)
2655 BestWeight = weight;
2656 }
2657
2658 return BestWeight;
2659}
2660
John Thompsone8360b72010-10-29 17:29:13 +00002661/// Examine constraint type and operand type and determine a weight value.
John Thompson1094c802010-09-13 18:15:37 +00002662/// This object must already have been set up with the operand type
2663/// and the current alternative constraint selected.
John Thompsone8360b72010-10-29 17:29:13 +00002664TargetLowering::ConstraintWeight
2665 TargetLowering::getSingleConstraintMatchWeight(
John Thompson1094c802010-09-13 18:15:37 +00002666 AsmOperandInfo &info, const char *constraint) const {
John Thompsone8360b72010-10-29 17:29:13 +00002667 ConstraintWeight weight = CW_Invalid;
John Thompson1094c802010-09-13 18:15:37 +00002668 Value *CallOperandVal = info.CallOperandVal;
2669 // If we don't have a value, we can't do a match,
2670 // but allow it at the lowest weight.
Craig Topperc0196b12014-04-14 00:51:57 +00002671 if (!CallOperandVal)
John Thompsone8360b72010-10-29 17:29:13 +00002672 return CW_Default;
John Thompson1094c802010-09-13 18:15:37 +00002673 // Look at the constraint type.
2674 switch (*constraint) {
2675 case 'i': // immediate integer.
2676 case 'n': // immediate integer with a known value.
John Thompsone8360b72010-10-29 17:29:13 +00002677 if (isa<ConstantInt>(CallOperandVal))
2678 weight = CW_Constant;
John Thompson1094c802010-09-13 18:15:37 +00002679 break;
2680 case 's': // non-explicit intregal immediate.
John Thompsone8360b72010-10-29 17:29:13 +00002681 if (isa<GlobalValue>(CallOperandVal))
2682 weight = CW_Constant;
John Thompson1094c802010-09-13 18:15:37 +00002683 break;
John Thompsone8360b72010-10-29 17:29:13 +00002684 case 'E': // immediate float if host format.
2685 case 'F': // immediate float.
2686 if (isa<ConstantFP>(CallOperandVal))
2687 weight = CW_Constant;
2688 break;
2689 case '<': // memory operand with autodecrement.
2690 case '>': // memory operand with autoincrement.
John Thompson1094c802010-09-13 18:15:37 +00002691 case 'm': // memory operand.
2692 case 'o': // offsettable memory operand
2693 case 'V': // non-offsettable memory operand
John Thompsone8360b72010-10-29 17:29:13 +00002694 weight = CW_Memory;
John Thompson1094c802010-09-13 18:15:37 +00002695 break;
John Thompsone8360b72010-10-29 17:29:13 +00002696 case 'r': // general register.
John Thompson1094c802010-09-13 18:15:37 +00002697 case 'g': // general register, memory operand or immediate integer.
John Thompsone8360b72010-10-29 17:29:13 +00002698 // note: Clang converts "g" to "imr".
2699 if (CallOperandVal->getType()->isIntegerTy())
2700 weight = CW_Register;
John Thompson1094c802010-09-13 18:15:37 +00002701 break;
John Thompsone8360b72010-10-29 17:29:13 +00002702 case 'X': // any operand.
John Thompson1094c802010-09-13 18:15:37 +00002703 default:
John Thompsone8360b72010-10-29 17:29:13 +00002704 weight = CW_Default;
John Thompson1094c802010-09-13 18:15:37 +00002705 break;
2706 }
2707 return weight;
2708}
2709
Sanjay Patelac6e9102015-12-29 22:11:50 +00002710/// If there are multiple different constraints that we could pick for this
2711/// operand (e.g. "imr") try to pick the 'best' one.
Chris Lattner58b9ece2008-04-27 01:49:46 +00002712/// This is somewhat tricky: constraints fall into four classes:
Chris Lattner47935152008-04-27 00:09:47 +00002713/// Other -> immediates and magic values
2714/// Register -> one specific register
2715/// RegisterClass -> a group of regs
2716/// Memory -> memory
2717/// Ideally, we would pick the most specific constraint possible: if we have
2718/// something that fits into a register, we would pick it. The problem here
2719/// is that if we have something that could either be in a register or in
2720/// memory that use of the register could cause selection of *other*
2721/// operands to fail: they might only succeed if we pick memory. Because of
2722/// this the heuristic we use is:
2723///
2724/// 1) If there is an 'other' constraint, and if the operand is valid for
2725/// that constraint, use it. This makes us take advantage of 'i'
2726/// constraints when available.
2727/// 2) Otherwise, pick the most general constraint present. This prefers
2728/// 'm' over 'r', for example.
2729///
2730static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
Dale Johannesence97d552010-06-25 21:55:36 +00002731 const TargetLowering &TLI,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002732 SDValue Op, SelectionDAG *DAG) {
Chris Lattner47935152008-04-27 00:09:47 +00002733 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
2734 unsigned BestIdx = 0;
2735 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
2736 int BestGenerality = -1;
Dale Johannesen17feb072010-06-28 22:09:45 +00002737
Chris Lattner47935152008-04-27 00:09:47 +00002738 // Loop over the options, keeping track of the most general one.
2739 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
2740 TargetLowering::ConstraintType CType =
2741 TLI.getConstraintType(OpInfo.Codes[i]);
Dale Johannesen17feb072010-06-28 22:09:45 +00002742
Chris Lattner22379732008-04-27 00:37:18 +00002743 // If this is an 'other' constraint, see if the operand is valid for it.
2744 // For example, on X86 we might have an 'rI' constraint. If the operand
2745 // is an integer in the range [0..31] we want to use I (saving a load
2746 // of a register), otherwise we must use 'r'.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002747 if (CType == TargetLowering::C_Other && Op.getNode()) {
Chris Lattner22379732008-04-27 00:37:18 +00002748 assert(OpInfo.Codes[i].size() == 1 &&
2749 "Unhandled multi-letter 'other' constraint");
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002750 std::vector<SDValue> ResultOps;
Eric Christopherde9399b2011-06-02 23:16:42 +00002751 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
Chris Lattner22379732008-04-27 00:37:18 +00002752 ResultOps, *DAG);
2753 if (!ResultOps.empty()) {
2754 BestType = CType;
2755 BestIdx = i;
2756 break;
2757 }
2758 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002759
Dale Johannesen17feb072010-06-28 22:09:45 +00002760 // Things with matching constraints can only be registers, per gcc
2761 // documentation. This mainly affects "g" constraints.
2762 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
2763 continue;
Wesley Peck527da1b2010-11-23 03:31:01 +00002764
Chris Lattner47935152008-04-27 00:09:47 +00002765 // This constraint letter is more general than the previous one, use it.
2766 int Generality = getConstraintGenerality(CType);
2767 if (Generality > BestGenerality) {
2768 BestType = CType;
2769 BestIdx = i;
2770 BestGenerality = Generality;
2771 }
2772 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002773
Chris Lattner47935152008-04-27 00:09:47 +00002774 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
2775 OpInfo.ConstraintType = BestType;
2776}
2777
Sanjay Patelac6e9102015-12-29 22:11:50 +00002778/// Determines the constraint code and constraint type to use for the specific
2779/// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
Chris Lattner22379732008-04-27 00:37:18 +00002780void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
Wesley Peck527da1b2010-11-23 03:31:01 +00002781 SDValue Op,
Chris Lattner22379732008-04-27 00:37:18 +00002782 SelectionDAG *DAG) const {
Chris Lattner47935152008-04-27 00:09:47 +00002783 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
Wesley Peck527da1b2010-11-23 03:31:01 +00002784
Chris Lattner47935152008-04-27 00:09:47 +00002785 // Single-letter constraints ('r') are very common.
2786 if (OpInfo.Codes.size() == 1) {
2787 OpInfo.ConstraintCode = OpInfo.Codes[0];
2788 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2789 } else {
Dale Johannesence97d552010-06-25 21:55:36 +00002790 ChooseConstraint(OpInfo, *this, Op, DAG);
Chris Lattner47935152008-04-27 00:09:47 +00002791 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002792
Chris Lattner47935152008-04-27 00:09:47 +00002793 // 'X' matches anything.
2794 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
2795 // Labels and constants are handled elsewhere ('X' is the only thing
Dale Johannesen4e331152009-07-07 23:26:33 +00002796 // that matches labels). For Functions, the type here is the type of
Dale Johannesenade297d2009-07-20 23:27:39 +00002797 // the result, which is not what we want to look at; leave them alone.
2798 Value *v = OpInfo.CallOperandVal;
Dale Johannesen4e331152009-07-07 23:26:33 +00002799 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
2800 OpInfo.CallOperandVal = v;
Chris Lattner47935152008-04-27 00:09:47 +00002801 return;
Dale Johannesen4e331152009-07-07 23:26:33 +00002802 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002803
Chris Lattner47935152008-04-27 00:09:47 +00002804 // Otherwise, try to resolve it to something we know about by looking at
2805 // the actual operand type.
2806 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
2807 OpInfo.ConstraintCode = Repl;
2808 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2809 }
2810 }
2811}
2812
David Majnemer0fc86702013-06-08 23:51:45 +00002813/// \brief Given an exact SDIV by a constant, create a multiplication
Benjamin Kramer9960a252011-07-08 10:31:30 +00002814/// with the multiplicative inverse of the constant.
Benjamin Kramer5b455f02015-06-27 20:33:26 +00002815static SDValue BuildExactSDIV(const TargetLowering &TLI, SDValue Op1, APInt d,
2816 SDLoc dl, SelectionDAG &DAG,
2817 std::vector<SDNode *> &Created) {
Benjamin Kramer9960a252011-07-08 10:31:30 +00002818 assert(d != 0 && "Division by zero!");
2819
2820 // Shift the value upfront if it is even, so the LSB is one.
2821 unsigned ShAmt = d.countTrailingZeros();
2822 if (ShAmt) {
2823 // TODO: For UDIV use SRL instead of SRA.
NAKAMURA Takumie4529982015-05-06 14:03:22 +00002824 SDValue Amt =
Mehdi Amini9639d652015-07-09 02:09:20 +00002825 DAG.getConstant(ShAmt, dl, TLI.getShiftAmountTy(Op1.getValueType(),
2826 DAG.getDataLayout()));
Sanjay Patelf1340482015-06-16 16:25:43 +00002827 SDNodeFlags Flags;
2828 Flags.setExact(true);
2829 Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, &Flags);
Benjamin Kramer5b455f02015-06-27 20:33:26 +00002830 Created.push_back(Op1.getNode());
Benjamin Kramer9960a252011-07-08 10:31:30 +00002831 d = d.ashr(ShAmt);
2832 }
2833
2834 // Calculate the multiplicative inverse, using Newton's method.
2835 APInt t, xn = d;
2836 while ((t = d*xn) != 1)
2837 xn *= APInt(d.getBitWidth(), 2) - t;
2838
Benjamin Kramer5b455f02015-06-27 20:33:26 +00002839 SDValue Op2 = DAG.getConstant(xn, dl, Op1.getValueType());
2840 SDValue Mul = DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
2841 Created.push_back(Mul.getNode());
2842 return Mul;
Benjamin Kramer9960a252011-07-08 10:31:30 +00002843}
2844
Steve King5cdbd202015-08-25 02:31:21 +00002845SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
2846 SelectionDAG &DAG,
2847 std::vector<SDNode *> *Created) const {
2848 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2849 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2850 if (TLI.isIntDivCheap(N->getValueType(0), Attr))
2851 return SDValue(N,0); // Lower SDIV as SDIV
2852 return SDValue();
2853}
2854
David Majnemer0fc86702013-06-08 23:51:45 +00002855/// \brief Given an ISD::SDIV node expressing a divide by constant,
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002856/// return a DAG expression to select that will generate the same value by
Sanjay Patelbb292212014-09-15 19:47:44 +00002857/// multiplying by a magic number.
2858/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002859SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor,
2860 SelectionDAG &DAG, bool IsAfterLegalization,
2861 std::vector<SDNode *> *Created) const {
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002862 assert(Created && "No vector to hold sdiv ops.");
2863
Owen Anderson53aa7a92009-08-10 22:56:29 +00002864 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002865 SDLoc dl(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00002866
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002867 // Check to see if we can do this.
Eli Friedmanc8228d22008-11-30 06:35:39 +00002868 // FIXME: We should be more aggressive here.
2869 if (!isTypeLegal(VT))
2870 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +00002871
Benjamin Kramer5b455f02015-06-27 20:33:26 +00002872 // If the sdiv has an 'exact' bit we can use a simpler lowering.
2873 if (cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact())
2874 return BuildExactSDIV(*this, N->getOperand(0), Divisor, dl, DAG, *Created);
2875
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002876 APInt::ms magics = Divisor.magic();
Wesley Peck527da1b2010-11-23 03:31:01 +00002877
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002878 // Multiply the numerator (operand 0) by the magic value
Eli Friedmanc8228d22008-11-30 06:35:39 +00002879 // FIXME: We should support doing a MUL in a wider type
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002880 SDValue Q;
Richard Osborne561fac42011-11-07 17:09:05 +00002881 if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
2882 isOperationLegalOrCustom(ISD::MULHS, VT))
Dale Johannesenf1163e92009-02-03 00:47:48 +00002883 Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002884 DAG.getConstant(magics.m, dl, VT));
Richard Osborne561fac42011-11-07 17:09:05 +00002885 else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
2886 isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
Dale Johannesenf1163e92009-02-03 00:47:48 +00002887 Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
Dan Gohmana1603612007-10-08 18:33:35 +00002888 N->getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002889 DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
Dan Gohmana1603612007-10-08 18:33:35 +00002890 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002891 return SDValue(); // No mulhs or equvialent
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002892 // If d > 0 and m < 0, add the numerator
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002893 if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
Dale Johannesenf1163e92009-02-03 00:47:48 +00002894 Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002895 Created->push_back(Q.getNode());
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002896 }
2897 // If d < 0 and m > 0, subtract the numerator.
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002898 if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
Dale Johannesenf1163e92009-02-03 00:47:48 +00002899 Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002900 Created->push_back(Q.getNode());
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002901 }
Mehdi Amini9639d652015-07-09 02:09:20 +00002902 auto &DL = DAG.getDataLayout();
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002903 // Shift right algebraic if shift value is nonzero
2904 if (magics.s > 0) {
Mehdi Amini9639d652015-07-09 02:09:20 +00002905 Q = DAG.getNode(
2906 ISD::SRA, dl, VT, Q,
2907 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002908 Created->push_back(Q.getNode());
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002909 }
2910 // Extract the sign bit and add it to the quotient
Mehdi Amini9639d652015-07-09 02:09:20 +00002911 SDValue T =
2912 DAG.getNode(ISD::SRL, dl, VT, Q,
2913 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl,
2914 getShiftAmountTy(Q.getValueType(), DL)));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002915 Created->push_back(T.getNode());
Dale Johannesenf1163e92009-02-03 00:47:48 +00002916 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002917}
2918
David Majnemer0fc86702013-06-08 23:51:45 +00002919/// \brief Given an ISD::UDIV node expressing a divide by constant,
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002920/// return a DAG expression to select that will generate the same value by
Sanjay Patelbb292212014-09-15 19:47:44 +00002921/// multiplying by a magic number.
2922/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002923SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor,
2924 SelectionDAG &DAG, bool IsAfterLegalization,
2925 std::vector<SDNode *> *Created) const {
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002926 assert(Created && "No vector to hold udiv ops.");
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00002927
Owen Anderson53aa7a92009-08-10 22:56:29 +00002928 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002929 SDLoc dl(N);
Mehdi Amini9639d652015-07-09 02:09:20 +00002930 auto &DL = DAG.getDataLayout();
Eli Friedman1b7fc152008-11-30 06:02:26 +00002931
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002932 // Check to see if we can do this.
Eli Friedman1b7fc152008-11-30 06:02:26 +00002933 // FIXME: We should be more aggressive here.
2934 if (!isTypeLegal(VT))
2935 return SDValue();
2936
2937 // FIXME: We should use a narrower constant when the upper
2938 // bits are known to be zero.
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002939 APInt::mu magics = Divisor.magicu();
Benjamin Kramercfcea122011-03-17 20:39:14 +00002940
2941 SDValue Q = N->getOperand(0);
2942
2943 // If the divisor is even, we can avoid using the expensive fixup by shifting
2944 // the divided value upfront.
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002945 if (magics.a != 0 && !Divisor[0]) {
2946 unsigned Shift = Divisor.countTrailingZeros();
Mehdi Amini9639d652015-07-09 02:09:20 +00002947 Q = DAG.getNode(
2948 ISD::SRL, dl, VT, Q,
2949 DAG.getConstant(Shift, dl, getShiftAmountTy(Q.getValueType(), DL)));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002950 Created->push_back(Q.getNode());
Benjamin Kramercfcea122011-03-17 20:39:14 +00002951
2952 // Get magic number for the shifted divisor.
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002953 magics = Divisor.lshr(Shift).magicu(Shift);
Benjamin Kramercfcea122011-03-17 20:39:14 +00002954 assert(magics.a == 0 && "Should use cheap fixup now");
2955 }
Eli Friedman1b7fc152008-11-30 06:02:26 +00002956
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002957 // Multiply the numerator (operand 0) by the magic value
Eli Friedman1b7fc152008-11-30 06:02:26 +00002958 // FIXME: We should support doing a MUL in a wider type
Richard Osborne561fac42011-11-07 17:09:05 +00002959 if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
2960 isOperationLegalOrCustom(ISD::MULHU, VT))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002961 Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, dl, VT));
Richard Osborne561fac42011-11-07 17:09:05 +00002962 else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
2963 isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
Benjamin Kramercfcea122011-03-17 20:39:14 +00002964 Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002965 DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
Dan Gohmana1603612007-10-08 18:33:35 +00002966 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002967 return SDValue(); // No mulhu or equvialent
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002968
2969 Created->push_back(Q.getNode());
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002970
2971 if (magics.a == 0) {
Benjamin Kramer4dae5982014-04-26 12:06:28 +00002972 assert(magics.s < Divisor.getBitWidth() &&
Eli Friedman1b7fc152008-11-30 06:02:26 +00002973 "We shouldn't generate an undefined shift!");
Mehdi Amini9639d652015-07-09 02:09:20 +00002974 return DAG.getNode(
2975 ISD::SRL, dl, VT, Q,
2976 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002977 } else {
Dale Johannesenf1163e92009-02-03 00:47:48 +00002978 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002979 Created->push_back(NPQ.getNode());
Mehdi Amini9639d652015-07-09 02:09:20 +00002980 NPQ = DAG.getNode(
2981 ISD::SRL, dl, VT, NPQ,
2982 DAG.getConstant(1, dl, getShiftAmountTy(NPQ.getValueType(), DL)));
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002983 Created->push_back(NPQ.getNode());
Dale Johannesenf1163e92009-02-03 00:47:48 +00002984 NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
Sanjay Pateld4f4c4e2014-09-15 21:52:51 +00002985 Created->push_back(NPQ.getNode());
Mehdi Amini9639d652015-07-09 02:09:20 +00002986 return DAG.getNode(
2987 ISD::SRL, dl, VT, NPQ,
2988 DAG.getConstant(magics.s - 1, dl,
2989 getShiftAmountTy(NPQ.getValueType(), DL)));
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +00002990 }
2991}
Bill Wendling908bf812014-01-06 00:43:20 +00002992
2993bool TargetLowering::
2994verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
2995 if (!isa<ConstantSDNode>(Op.getOperand(0))) {
2996 DAG.getContext()->emitError("argument to '__builtin_return_address' must "
2997 "be a constant integer");
2998 return true;
2999 }
3000
3001 return false;
3002}
Tom Stellardb3a7fa22014-04-11 16:11:58 +00003003
3004//===----------------------------------------------------------------------===//
3005// Legalization Utilities
3006//===----------------------------------------------------------------------===//
3007
3008bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
3009 SelectionDAG &DAG, SDValue LL, SDValue LH,
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003010 SDValue RL, SDValue RH) const {
Tom Stellardb3a7fa22014-04-11 16:11:58 +00003011 EVT VT = N->getValueType(0);
3012 SDLoc dl(N);
3013
3014 bool HasMULHS = isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
3015 bool HasMULHU = isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
3016 bool HasSMUL_LOHI = isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
3017 bool HasUMUL_LOHI = isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
3018 if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
3019 unsigned OuterBitSize = VT.getSizeInBits();
3020 unsigned InnerBitSize = HiLoVT.getSizeInBits();
3021 unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0));
3022 unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1));
3023
3024 // LL, LH, RL, and RH must be either all NULL or all set to a value.
3025 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
3026 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
3027
3028 if (!LL.getNode() && !RL.getNode() &&
3029 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
3030 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(0));
3031 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(1));
3032 }
3033
3034 if (!LL.getNode())
3035 return false;
3036
3037 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
3038 if (DAG.MaskedValueIsZero(N->getOperand(0), HighMask) &&
3039 DAG.MaskedValueIsZero(N->getOperand(1), HighMask)) {
3040 // The inputs are both zero-extended.
3041 if (HasUMUL_LOHI) {
3042 // We can emit a umul_lohi.
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003043 Lo = DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL,
3044 RL);
Tom Stellardb3a7fa22014-04-11 16:11:58 +00003045 Hi = SDValue(Lo.getNode(), 1);
3046 return true;
3047 }
3048 if (HasMULHU) {
3049 // We can emit a mulhu+mul.
3050 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
3051 Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
3052 return true;
3053 }
3054 }
3055 if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
3056 // The input values are both sign-extended.
3057 if (HasSMUL_LOHI) {
3058 // We can emit a smul_lohi.
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003059 Lo = DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL,
3060 RL);
Tom Stellardb3a7fa22014-04-11 16:11:58 +00003061 Hi = SDValue(Lo.getNode(), 1);
3062 return true;
3063 }
3064 if (HasMULHS) {
3065 // We can emit a mulhs+mul.
3066 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
3067 Hi = DAG.getNode(ISD::MULHS, dl, HiLoVT, LL, RL);
3068 return true;
3069 }
3070 }
3071
3072 if (!LH.getNode() && !RH.getNode() &&
3073 isOperationLegalOrCustom(ISD::SRL, VT) &&
3074 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
Mehdi Amini9639d652015-07-09 02:09:20 +00003075 auto &DL = DAG.getDataLayout();
Tom Stellardb3a7fa22014-04-11 16:11:58 +00003076 unsigned ShiftAmt = VT.getSizeInBits() - HiLoVT.getSizeInBits();
Mehdi Amini9639d652015-07-09 02:09:20 +00003077 SDValue Shift = DAG.getConstant(ShiftAmt, dl, getShiftAmountTy(VT, DL));
Tom Stellardb3a7fa22014-04-11 16:11:58 +00003078 LH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(0), Shift);
3079 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
3080 RH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(1), Shift);
3081 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
3082 }
3083
3084 if (!LH.getNode())
3085 return false;
3086
3087 if (HasUMUL_LOHI) {
3088 // Lo,Hi = umul LHS, RHS.
3089 SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI, dl,
3090 DAG.getVTList(HiLoVT, HiLoVT), LL, RL);
3091 Lo = UMulLOHI;
3092 Hi = UMulLOHI.getValue(1);
3093 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
3094 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
3095 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
3096 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
3097 return true;
3098 }
3099 if (HasMULHU) {
3100 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
3101 Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
3102 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
3103 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
3104 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
3105 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
3106 return true;
3107 }
3108 }
3109 return false;
3110}
Jan Veselyeca89d22014-07-10 22:40:18 +00003111
3112bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
3113 SelectionDAG &DAG) const {
3114 EVT VT = Node->getOperand(0).getValueType();
3115 EVT NVT = Node->getValueType(0);
3116 SDLoc dl(SDValue(Node, 0));
3117
3118 // FIXME: Only f32 to i64 conversions are supported.
3119 if (VT != MVT::f32 || NVT != MVT::i64)
3120 return false;
3121
3122 // Expand f32 -> i64 conversion
3123 // This algorithm comes from compiler-rt's implementation of fixsfdi:
3124 // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c
3125 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(),
3126 VT.getSizeInBits());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003127 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
3128 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
3129 SDValue Bias = DAG.getConstant(127, dl, IntVT);
3130 SDValue SignMask = DAG.getConstant(APInt::getSignBit(VT.getSizeInBits()), dl,
Jan Veselyeca89d22014-07-10 22:40:18 +00003131 IntVT);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003132 SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, dl, IntVT);
3133 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
Jan Veselyeca89d22014-07-10 22:40:18 +00003134
3135 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0));
3136
Mehdi Amini9639d652015-07-09 02:09:20 +00003137 auto &DL = DAG.getDataLayout();
3138 SDValue ExponentBits = DAG.getNode(
3139 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
3140 DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT, DL)));
Jan Veselyeca89d22014-07-10 22:40:18 +00003141 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
3142
Mehdi Amini9639d652015-07-09 02:09:20 +00003143 SDValue Sign = DAG.getNode(
3144 ISD::SRA, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
3145 DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT, DL)));
Jan Veselyeca89d22014-07-10 22:40:18 +00003146 Sign = DAG.getSExtOrTrunc(Sign, dl, NVT);
3147
3148 SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
3149 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003150 DAG.getConstant(0x00800000, dl, IntVT));
Jan Veselyeca89d22014-07-10 22:40:18 +00003151
3152 R = DAG.getZExtOrTrunc(R, dl, NVT);
3153
Mehdi Amini9639d652015-07-09 02:09:20 +00003154 R = DAG.getSelectCC(
3155 dl, Exponent, ExponentLoBit,
3156 DAG.getNode(ISD::SHL, dl, NVT, R,
3157 DAG.getZExtOrTrunc(
3158 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
3159 dl, getShiftAmountTy(IntVT, DL))),
3160 DAG.getNode(ISD::SRL, dl, NVT, R,
3161 DAG.getZExtOrTrunc(
3162 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
3163 dl, getShiftAmountTy(IntVT, DL))),
3164 ISD::SETGT);
Jan Veselyeca89d22014-07-10 22:40:18 +00003165
3166 SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT,
3167 DAG.getNode(ISD::XOR, dl, NVT, R, Sign),
3168 Sign);
3169
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003170 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
3171 DAG.getConstant(0, dl, NVT), Ret, ISD::SETLT);
Jan Veselyeca89d22014-07-10 22:40:18 +00003172 return true;
3173}
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003174
Matt Arsenaulta4b1b6e2016-03-30 21:15:10 +00003175SDValue TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
3176 SelectionDAG &DAG) const {
3177 SDLoc SL(LD);
3178 SDValue Chain = LD->getChain();
3179 SDValue BasePTR = LD->getBasePtr();
3180 EVT SrcVT = LD->getMemoryVT();
3181 ISD::LoadExtType ExtType = LD->getExtensionType();
3182
3183 unsigned NumElem = SrcVT.getVectorNumElements();
3184
3185 EVT SrcEltVT = SrcVT.getScalarType();
3186 EVT DstEltVT = LD->getValueType(0).getScalarType();
3187
3188 unsigned Stride = SrcEltVT.getSizeInBits() / 8;
3189 assert(SrcEltVT.isByteSized());
3190
3191 EVT PtrVT = BasePTR.getValueType();
3192
3193 SmallVector<SDValue, 8> Vals;
3194 SmallVector<SDValue, 8> LoadChains;
3195
3196 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
3197 SDValue ScalarLoad = DAG.getExtLoad(
3198 ExtType, SL, DstEltVT,
3199 Chain, BasePTR, LD->getPointerInfo().getWithOffset(Idx * Stride),
3200 SrcEltVT,
3201 LD->isVolatile(), LD->isNonTemporal(), LD->isInvariant(),
3202 MinAlign(LD->getAlignment(), Idx * Stride), LD->getAAInfo());
3203
3204 BasePTR = DAG.getNode(ISD::ADD, SL, PtrVT, BasePTR,
3205 DAG.getConstant(Stride, SL, PtrVT));
3206
3207 Vals.push_back(ScalarLoad.getValue(0));
3208 LoadChains.push_back(ScalarLoad.getValue(1));
3209 }
3210
3211 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
3212 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, SL, LD->getValueType(0), Vals);
3213
3214 return DAG.getMergeValues({ Value, NewChain }, SL);
3215}
3216
Matt Arsenault46ba3162016-03-30 21:15:18 +00003217// FIXME: This relies on each element having a byte size, otherwise the stride
3218// is 0 and just overwrites the same location. ExpandStore currently expects
3219// this broken behavior.
3220SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
3221 SelectionDAG &DAG) const {
3222 SDLoc SL(ST);
3223
3224 SDValue Chain = ST->getChain();
3225 SDValue BasePtr = ST->getBasePtr();
3226 SDValue Value = ST->getValue();
3227 EVT StVT = ST->getMemoryVT();
3228
3229 unsigned Alignment = ST->getAlignment();
3230 bool isVolatile = ST->isVolatile();
3231 bool isNonTemporal = ST->isNonTemporal();
3232 AAMDNodes AAInfo = ST->getAAInfo();
3233
3234 // The type of the data we want to save
3235 EVT RegVT = Value.getValueType();
3236 EVT RegSclVT = RegVT.getScalarType();
3237
3238 // The type of data as saved in memory.
3239 EVT MemSclVT = StVT.getScalarType();
3240
3241 EVT PtrVT = BasePtr.getValueType();
3242
3243 // Store Stride in bytes
3244 unsigned Stride = MemSclVT.getSizeInBits() / 8;
3245 EVT IdxVT = getVectorIdxTy(DAG.getDataLayout());
3246 unsigned NumElem = StVT.getVectorNumElements();
3247
3248 // Extract each of the elements from the original vector and save them into
3249 // memory individually.
3250 SmallVector<SDValue, 8> Stores;
3251 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
3252 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
3253 DAG.getConstant(Idx, SL, IdxVT));
3254
3255 SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
3256 DAG.getConstant(Idx * Stride, SL, PtrVT));
3257
3258 // This scalar TruncStore may be illegal, but we legalize it later.
3259 SDValue Store = DAG.getTruncStore(
3260 Chain, SL, Elt, Ptr,
3261 ST->getPointerInfo().getWithOffset(Idx * Stride), MemSclVT,
3262 isVolatile, isNonTemporal, MinAlign(Alignment, Idx * Stride),
3263 AAInfo);
3264
3265 Stores.push_back(Store);
3266 }
3267
3268 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
3269}
3270
Matt Arsenault7846d882016-04-21 18:19:11 +00003271std::pair<SDValue, SDValue>
3272TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
3273 assert(LD->getAddressingMode() == ISD::UNINDEXED &&
3274 "unaligned indexed loads not implemented!");
3275 SDValue Chain = LD->getChain();
3276 SDValue Ptr = LD->getBasePtr();
3277 EVT VT = LD->getValueType(0);
3278 EVT LoadedVT = LD->getMemoryVT();
3279 SDLoc dl(LD);
3280 if (VT.isFloatingPoint() || VT.isVector()) {
3281 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
3282 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
3283 if (!isOperationLegalOrCustom(ISD::LOAD, intVT)) {
3284 // Scalarize the load and let the individual components be handled.
3285 SDValue Scalarized = scalarizeVectorLoad(LD, DAG);
3286 return std::make_pair(Scalarized.getValue(0), Scalarized.getValue(1));
3287 }
3288
3289 // Expand to a (misaligned) integer load of the same size,
3290 // then bitconvert to floating point or vector.
3291 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
3292 LD->getMemOperand());
3293 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
3294 if (LoadedVT != VT)
3295 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
3296 ISD::ANY_EXTEND, dl, VT, Result);
3297
3298 return std::make_pair(Result, newLoad.getValue(1));
3299 }
3300
3301 // Copy the value to a (aligned) stack slot using (unaligned) integer
3302 // loads and stores, then do a (aligned) load from the stack slot.
3303 MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
3304 unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
3305 unsigned RegBytes = RegVT.getSizeInBits() / 8;
3306 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
3307
3308 // Make sure the stack slot is also aligned for the register type.
3309 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
3310
3311 SmallVector<SDValue, 8> Stores;
3312 SDValue StackPtr = StackBase;
3313 unsigned Offset = 0;
3314
3315 EVT PtrVT = Ptr.getValueType();
3316 EVT StackPtrVT = StackPtr.getValueType();
3317
3318 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
3319 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
3320
3321 // Do all but one copies using the full register width.
3322 for (unsigned i = 1; i < NumRegs; i++) {
3323 // Load one integer register's worth from the original location.
3324 SDValue Load = DAG.getLoad(RegVT, dl, Chain, Ptr,
3325 LD->getPointerInfo().getWithOffset(Offset),
3326 LD->isVolatile(), LD->isNonTemporal(),
3327 LD->isInvariant(),
3328 MinAlign(LD->getAlignment(), Offset),
3329 LD->getAAInfo());
3330 // Follow the load with a store to the stack slot. Remember the store.
3331 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
3332 MachinePointerInfo(), false, false, 0));
3333 // Increment the pointers.
3334 Offset += RegBytes;
3335 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement);
3336 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT, StackPtr,
3337 StackPtrIncrement);
3338 }
3339
3340 // The last copy may be partial. Do an extending load.
3341 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
3342 8 * (LoadedBytes - Offset));
3343 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
3344 LD->getPointerInfo().getWithOffset(Offset),
3345 MemVT, LD->isVolatile(),
3346 LD->isNonTemporal(),
3347 LD->isInvariant(),
3348 MinAlign(LD->getAlignment(), Offset),
3349 LD->getAAInfo());
3350 // Follow the load with a store to the stack slot. Remember the store.
3351 // On big-endian machines this requires a truncating store to ensure
3352 // that the bits end up in the right place.
3353 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
3354 MachinePointerInfo(), MemVT,
3355 false, false, 0));
3356
3357 // The order of the stores doesn't matter - say it with a TokenFactor.
3358 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
3359
3360 // Finally, perform the original load only redirected to the stack slot.
3361 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
3362 MachinePointerInfo(), LoadedVT, false,false, false,
3363 0);
3364
3365 // Callers expect a MERGE_VALUES node.
3366 return std::make_pair(Load, TF);
3367 }
3368
3369 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
3370 "Unaligned load of unsupported type.");
3371
3372 // Compute the new VT that is half the size of the old one. This is an
3373 // integer MVT.
3374 unsigned NumBits = LoadedVT.getSizeInBits();
3375 EVT NewLoadedVT;
3376 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
3377 NumBits >>= 1;
3378
3379 unsigned Alignment = LD->getAlignment();
3380 unsigned IncrementSize = NumBits / 8;
3381 ISD::LoadExtType HiExtType = LD->getExtensionType();
3382
3383 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
3384 if (HiExtType == ISD::NON_EXTLOAD)
3385 HiExtType = ISD::ZEXTLOAD;
3386
3387 // Load the value in two parts
3388 SDValue Lo, Hi;
3389 if (DAG.getDataLayout().isLittleEndian()) {
3390 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
3391 NewLoadedVT, LD->isVolatile(),
3392 LD->isNonTemporal(), LD->isInvariant(), Alignment,
3393 LD->getAAInfo());
3394 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3395 DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3396 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
3397 LD->getPointerInfo().getWithOffset(IncrementSize),
3398 NewLoadedVT, LD->isVolatile(),
3399 LD->isNonTemporal(),LD->isInvariant(),
3400 MinAlign(Alignment, IncrementSize), LD->getAAInfo());
3401 } else {
3402 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
3403 NewLoadedVT, LD->isVolatile(),
3404 LD->isNonTemporal(), LD->isInvariant(), Alignment,
3405 LD->getAAInfo());
3406 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3407 DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3408 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
3409 LD->getPointerInfo().getWithOffset(IncrementSize),
3410 NewLoadedVT, LD->isVolatile(),
3411 LD->isNonTemporal(), LD->isInvariant(),
3412 MinAlign(Alignment, IncrementSize), LD->getAAInfo());
3413 }
3414
3415 // aggregate the two parts
3416 SDValue ShiftAmount =
3417 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
3418 DAG.getDataLayout()));
3419 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
3420 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
3421
3422 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
3423 Hi.getValue(1));
3424
3425 return std::make_pair(Result, TF);
3426}
3427
3428SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
3429 SelectionDAG &DAG) const {
3430 assert(ST->getAddressingMode() == ISD::UNINDEXED &&
3431 "unaligned indexed stores not implemented!");
3432 SDValue Chain = ST->getChain();
3433 SDValue Ptr = ST->getBasePtr();
3434 SDValue Val = ST->getValue();
3435 EVT VT = Val.getValueType();
3436 int Alignment = ST->getAlignment();
3437
3438 SDLoc dl(ST);
3439 if (ST->getMemoryVT().isFloatingPoint() ||
3440 ST->getMemoryVT().isVector()) {
3441 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
3442 if (isTypeLegal(intVT)) {
3443 if (!isOperationLegalOrCustom(ISD::STORE, intVT)) {
3444 // Scalarize the store and let the individual components be handled.
3445 SDValue Result = scalarizeVectorStore(ST, DAG);
3446
3447 return Result;
3448 }
3449 // Expand to a bitconvert of the value to the integer type of the
3450 // same size, then a (misaligned) int store.
3451 // FIXME: Does not handle truncating floating point stores!
3452 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
3453 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
3454 ST->isVolatile(), ST->isNonTemporal(), Alignment);
3455 return Result;
3456 }
3457 // Do a (aligned) store to a stack slot, then copy from the stack slot
3458 // to the final destination using (unaligned) integer loads and stores.
3459 EVT StoredVT = ST->getMemoryVT();
3460 MVT RegVT =
3461 getRegisterType(*DAG.getContext(),
3462 EVT::getIntegerVT(*DAG.getContext(),
3463 StoredVT.getSizeInBits()));
3464 EVT PtrVT = Ptr.getValueType();
3465 unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
3466 unsigned RegBytes = RegVT.getSizeInBits() / 8;
3467 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
3468
3469 // Make sure the stack slot is also aligned for the register type.
3470 SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
3471
3472 // Perform the original store, only redirected to the stack slot.
3473 SDValue Store = DAG.getTruncStore(Chain, dl,
3474 Val, StackPtr, MachinePointerInfo(),
3475 StoredVT, false, false, 0);
3476
3477 EVT StackPtrVT = StackPtr.getValueType();
3478
3479 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
3480 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
3481 SmallVector<SDValue, 8> Stores;
3482 unsigned Offset = 0;
3483
3484 // Do all but one copies using the full register width.
3485 for (unsigned i = 1; i < NumRegs; i++) {
3486 // Load one integer register's worth from the stack slot.
3487 SDValue Load = DAG.getLoad(RegVT, dl, Store, StackPtr,
3488 MachinePointerInfo(),
3489 false, false, false, 0);
3490 // Store it to the final location. Remember the store.
3491 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
3492 ST->getPointerInfo().getWithOffset(Offset),
3493 ST->isVolatile(), ST->isNonTemporal(),
3494 MinAlign(ST->getAlignment(), Offset)));
3495 // Increment the pointers.
3496 Offset += RegBytes;
3497 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT,
3498 StackPtr, StackPtrIncrement);
3499 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement);
3500 }
3501
3502 // The last store may be partial. Do a truncating store. On big-endian
3503 // machines this requires an extending load from the stack slot to ensure
3504 // that the bits are in the right place.
3505 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
3506 8 * (StoredBytes - Offset));
3507
3508 // Load from the stack slot.
3509 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
3510 MachinePointerInfo(),
3511 MemVT, false, false, false, 0);
3512
3513 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
3514 ST->getPointerInfo()
3515 .getWithOffset(Offset),
3516 MemVT, ST->isVolatile(),
3517 ST->isNonTemporal(),
3518 MinAlign(ST->getAlignment(), Offset),
3519 ST->getAAInfo()));
3520 // The order of the stores doesn't matter - say it with a TokenFactor.
3521 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
3522 return Result;
3523 }
3524
3525 assert(ST->getMemoryVT().isInteger() &&
3526 !ST->getMemoryVT().isVector() &&
3527 "Unaligned store of unknown type.");
3528 // Get the half-size VT
3529 EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
3530 int NumBits = NewStoredVT.getSizeInBits();
3531 int IncrementSize = NumBits / 8;
3532
3533 // Divide the stored value in two parts.
3534 SDValue ShiftAmount =
3535 DAG.getConstant(NumBits, dl, getShiftAmountTy(Val.getValueType(),
3536 DAG.getDataLayout()));
3537 SDValue Lo = Val;
3538 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
3539
3540 // Store the two parts
3541 SDValue Store1, Store2;
3542 Store1 = DAG.getTruncStore(Chain, dl,
3543 DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
3544 Ptr, ST->getPointerInfo(), NewStoredVT,
3545 ST->isVolatile(), ST->isNonTemporal(), Alignment);
3546
3547 EVT PtrVT = Ptr.getValueType();
3548 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3549 DAG.getConstant(IncrementSize, dl, PtrVT));
3550 Alignment = MinAlign(Alignment, IncrementSize);
3551 Store2 = DAG.getTruncStore(
3552 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
3553 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT,
3554 ST->isVolatile(), ST->isNonTemporal(), Alignment, ST->getAAInfo());
3555
3556 SDValue Result =
3557 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
3558 return Result;
3559}
3560
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003561//===----------------------------------------------------------------------===//
3562// Implementation of Emulated TLS Model
3563//===----------------------------------------------------------------------===//
3564
3565SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
3566 SelectionDAG &DAG) const {
3567 // Access to address of TLS varialbe xyz is lowered to a function call:
3568 // __emutls_get_address( address of global variable named "__emutls_v.xyz" )
3569 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3570 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
3571 SDLoc dl(GA);
3572
3573 ArgListTy Args;
3574 ArgListEntry Entry;
3575 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
3576 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
3577 StringRef EmuTlsVarName(NameString);
3578 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
Chih-Hung Hsieh57886402016-01-13 23:56:37 +00003579 assert(EmuTlsVar && "Cannot find EmuTlsVar ");
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003580 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
3581 Entry.Ty = VoidPtrType;
3582 Args.push_back(Entry);
3583
3584 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
3585
3586 TargetLowering::CallLoweringInfo CLI(DAG);
3587 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
3588 CLI.setCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args), 0);
3589 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3590
3591 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
3592 // At last for X86 targets, maybe good for other targets too?
3593 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3594 MFI->setAdjustsStack(true); // Is this only for X86 target?
3595 MFI->setHasCalls(true);
3596
3597 assert((GA->getOffset() == 0) &&
3598 "Emulated TLS must have zero offset in GlobalAddressSDNode");
3599 return CallResult.first;
3600}