blob: 20f846eace2a9f03eb52ada8313375d1d4d1a892 [file] [log] [blame]
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001//===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
Dan Gohman575fad32008-09-03 16:12:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements routines for translating from LLVM IR into SelectionDAG IR.
11//
12//===----------------------------------------------------------------------===//
13
Dan Gohman1a6c47f2009-11-23 18:04:58 +000014#include "SelectionDAGBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "SDNodeDbgValue.h"
Dan Gohman575fad32008-09-03 16:12:24 +000016#include "llvm/ADT/BitVector.h"
David Blaikie0252265b2013-06-16 20:34:15 +000017#include "llvm/ADT/Optional.h"
Dan Gohman5eba3bc2008-09-04 20:49:27 +000018#include "llvm/ADT/SmallSet.h"
Philip Reames1a1bdb22014-12-02 18:50:36 +000019#include "llvm/ADT/Statistic.h"
Dan Gohman575fad32008-09-03 16:12:24 +000020#include "llvm/Analysis/AliasAnalysis.h"
Jakub Staszaka9286e92013-01-10 22:13:13 +000021#include "llvm/Analysis/BranchProbabilityInfo.h"
Chris Lattner1a32ede2009-12-24 00:37:38 +000022#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000023#include "llvm/Analysis/TargetLibraryInfo.h"
Nadav Rotem7c277da2012-09-06 09:17:37 +000024#include "llvm/Analysis/ValueTracking.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/CodeGen/Analysis.h"
26#include "llvm/CodeGen/FastISel.h"
27#include "llvm/CodeGen/FunctionLoweringInfo.h"
28#include "llvm/CodeGen/GCMetadata.h"
Philip Reames56a03932015-01-26 18:26:35 +000029#include "llvm/CodeGen/GCStrategy.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/CodeGen/MachineFrameInfo.h"
31#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
33#include "llvm/CodeGen/MachineJumpTableInfo.h"
34#include "llvm/CodeGen/MachineModuleInfo.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
36#include "llvm/CodeGen/SelectionDAG.h"
Andrew Trick153ebe62013-10-31 22:11:56 +000037#include "llvm/CodeGen/StackMaps.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/CallingConv.h"
39#include "llvm/IR/Constants.h"
40#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000041#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/DerivedTypes.h"
43#include "llvm/IR/Function.h"
44#include "llvm/IR/GlobalVariable.h"
45#include "llvm/IR/InlineAsm.h"
46#include "llvm/IR/Instructions.h"
47#include "llvm/IR/IntrinsicInst.h"
48#include "llvm/IR/Intrinsics.h"
49#include "llvm/IR/LLVMContext.h"
50#include "llvm/IR/Module.h"
Philip Reames1a1bdb22014-12-02 18:50:36 +000051#include "llvm/IR/Statepoint.h"
Reid Klecknere9b89312015-01-13 00:48:10 +000052#include "llvm/MC/MCSymbol.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000053#include "llvm/Support/CommandLine.h"
54#include "llvm/Support/Debug.h"
55#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000056#include "llvm/Support/MathExtras.h"
57#include "llvm/Support/raw_ostream.h"
Anton Korobeynikov2f931282011-01-10 12:39:04 +000058#include "llvm/Target/TargetFrameLowering.h"
Dan Gohman575fad32008-09-03 16:12:24 +000059#include "llvm/Target/TargetInstrInfo.h"
Dale Johannesenb842d522009-02-05 01:49:45 +000060#include "llvm/Target/TargetIntrinsicInfo.h"
Dan Gohman575fad32008-09-03 16:12:24 +000061#include "llvm/Target/TargetLowering.h"
Dan Gohman575fad32008-09-03 16:12:24 +000062#include "llvm/Target/TargetOptions.h"
Richard Sandiford564681c2013-08-12 10:28:10 +000063#include "llvm/Target/TargetSelectionDAGInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000064#include "llvm/Target/TargetSubtargetInfo.h"
Dan Gohman575fad32008-09-03 16:12:24 +000065#include <algorithm>
66using namespace llvm;
67
Chandler Carruth1b9dde02014-04-22 02:02:50 +000068#define DEBUG_TYPE "isel"
69
Dale Johannesenf2a52bb2008-09-05 01:48:15 +000070/// LimitFloatPrecision - Generate low-precision inline sequences for
71/// some float libcalls (6, 8 or 12 bits).
72static unsigned LimitFloatPrecision;
73
74static cl::opt<unsigned, true>
75LimitFPPrecision("limit-float-precision",
76 cl::desc("Generate low-precision inline sequences "
77 "for some float libcalls"),
78 cl::location(LimitFloatPrecision),
79 cl::init(0));
80
Andrew Trick116efac2010-11-12 17:50:46 +000081// Limit the width of DAG chains. This is important in general to prevent
82// prevent DAG-based analysis from blowing up. For example, alias analysis and
83// load clustering may not complete in reasonable time. It is difficult to
84// recognize and avoid this situation within each individual analysis, and
85// future analyses are likely to have the same behavior. Limiting DAG width is
Andrew Trickcf7fefb2010-11-20 07:26:51 +000086// the safe approach, and will be especially important with global DAGs.
Andrew Trick116efac2010-11-12 17:50:46 +000087//
88// MaxParallelChains default is arbitrarily high to avoid affecting
89// optimization, but could be lowered to improve compile time. Any ld-ld-st-st
Andrew Trickcf7fefb2010-11-20 07:26:51 +000090// sequence over this should have been converted to llvm.memcpy by the
91// frontend. It easy to induce this behavior with .ll code such as:
92// %buffer = alloca [4096 x i8]
93// %data = load [4096 x i8]* %argPtr
94// store [4096 x i8] %data, [4096 x i8]* %buffer
Andrew Trick710d5da2011-03-11 17:46:59 +000095static const unsigned MaxParallelChains = 64;
Andrew Trick116efac2010-11-12 17:50:46 +000096
Andrew Trickef9de2a2013-05-25 02:42:55 +000097static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
Chris Lattner05bcb482010-08-24 23:20:40 +000098 const SDValue *Parts, unsigned NumParts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +000099 MVT PartVT, EVT ValueVT, const Value *V);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000100
Dan Gohman575fad32008-09-03 16:12:24 +0000101/// getCopyFromParts - Create a value that contains the specified legal parts
102/// combined into the value they represent. If the parts combine to a type
103/// larger then ValueVT then AssertOp can be used to specify whether the extra
104/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
105/// (ISD::AssertSext).
Andrew Trickef9de2a2013-05-25 02:42:55 +0000106static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
Dale Johannesendb7c5f62009-01-31 02:22:37 +0000107 const SDValue *Parts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000108 unsigned NumParts, MVT PartVT, EVT ValueVT,
Bill Wendling81406f62012-09-26 04:04:19 +0000109 const Value *V,
Duncan Sandsba21b7d2009-01-28 14:42:54 +0000110 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Chris Lattner05bcb482010-08-24 23:20:40 +0000111 if (ValueVT.isVector())
Bill Wendling81406f62012-09-26 04:04:19 +0000112 return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
113 PartVT, ValueVT, V);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000114
Dan Gohman575fad32008-09-03 16:12:24 +0000115 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohman91febd12009-01-15 16:58:17 +0000116 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman575fad32008-09-03 16:12:24 +0000117 SDValue Val = Parts[0];
118
119 if (NumParts > 1) {
120 // Assemble the value from multiple parts.
Chris Lattner05bcb482010-08-24 23:20:40 +0000121 if (ValueVT.isInteger()) {
Dan Gohman575fad32008-09-03 16:12:24 +0000122 unsigned PartBits = PartVT.getSizeInBits();
123 unsigned ValueBits = ValueVT.getSizeInBits();
124
125 // Assemble the power of 2 part.
126 unsigned RoundParts = NumParts & (NumParts - 1) ?
127 1 << Log2_32(NumParts) : NumParts;
128 unsigned RoundBits = PartBits * RoundParts;
Owen Anderson53aa7a92009-08-10 22:56:29 +0000129 EVT RoundVT = RoundBits == ValueBits ?
Owen Anderson117c9e82009-08-12 00:36:31 +0000130 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
Dan Gohman575fad32008-09-03 16:12:24 +0000131 SDValue Lo, Hi;
132
Owen Anderson117c9e82009-08-12 00:36:31 +0000133 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
Duncan Sands17e678b2008-10-29 14:22:20 +0000134
Dan Gohman575fad32008-09-03 16:12:24 +0000135 if (RoundParts > 2) {
Chris Lattner05bcb482010-08-24 23:20:40 +0000136 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
Bill Wendling81406f62012-09-26 04:04:19 +0000137 PartVT, HalfVT, V);
Chris Lattner05bcb482010-08-24 23:20:40 +0000138 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
Bill Wendling81406f62012-09-26 04:04:19 +0000139 RoundParts / 2, PartVT, HalfVT, V);
Dan Gohman575fad32008-09-03 16:12:24 +0000140 } else {
Wesley Peck527da1b2010-11-23 03:31:01 +0000141 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
142 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
Dan Gohman575fad32008-09-03 16:12:24 +0000143 }
Bill Wendling919b7aa2009-12-22 02:10:19 +0000144
Dan Gohman575fad32008-09-03 16:12:24 +0000145 if (TLI.isBigEndian())
146 std::swap(Lo, Hi);
Bill Wendling919b7aa2009-12-22 02:10:19 +0000147
Chris Lattner05bcb482010-08-24 23:20:40 +0000148 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
Dan Gohman575fad32008-09-03 16:12:24 +0000149
150 if (RoundParts < NumParts) {
151 // Assemble the trailing non-power-of-2 part.
152 unsigned OddParts = NumParts - RoundParts;
Owen Anderson117c9e82009-08-12 00:36:31 +0000153 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
Chris Lattner05bcb482010-08-24 23:20:40 +0000154 Hi = getCopyFromParts(DAG, DL,
Bill Wendling81406f62012-09-26 04:04:19 +0000155 Parts + RoundParts, OddParts, PartVT, OddVT, V);
Dan Gohman575fad32008-09-03 16:12:24 +0000156
157 // Combine the round and odd parts.
158 Lo = Val;
159 if (TLI.isBigEndian())
160 std::swap(Lo, Hi);
Owen Anderson117c9e82009-08-12 00:36:31 +0000161 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Chris Lattner05bcb482010-08-24 23:20:40 +0000162 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
163 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
Dan Gohman575fad32008-09-03 16:12:24 +0000164 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands41826032009-01-31 15:50:11 +0000165 TLI.getPointerTy()));
Chris Lattner05bcb482010-08-24 23:20:40 +0000166 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
167 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
Dan Gohman575fad32008-09-03 16:12:24 +0000168 }
Eli Friedman9030c352009-05-20 06:02:09 +0000169 } else if (PartVT.isFloatingPoint()) {
170 // FP split into multiple FP parts (for ppcf128)
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000171 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
Eli Friedman9030c352009-05-20 06:02:09 +0000172 "Unexpected split");
173 SDValue Lo, Hi;
Wesley Peck527da1b2010-11-23 03:31:01 +0000174 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
175 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
Ulrich Weigandf236bb12014-07-03 15:06:47 +0000176 if (TLI.hasBigEndianPartOrdering(ValueVT))
Eli Friedman9030c352009-05-20 06:02:09 +0000177 std::swap(Lo, Hi);
Chris Lattner05bcb482010-08-24 23:20:40 +0000178 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
Eli Friedman9030c352009-05-20 06:02:09 +0000179 } else {
180 // FP split into integer parts (soft fp)
181 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
182 !PartVT.isVector() && "Unexpected split");
Owen Anderson117c9e82009-08-12 00:36:31 +0000183 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
Bill Wendling81406f62012-09-26 04:04:19 +0000184 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
Dan Gohman575fad32008-09-03 16:12:24 +0000185 }
186 }
187
188 // There is now one part, held in Val. Correct it to match ValueVT.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000189 EVT PartEVT = Val.getValueType();
Dan Gohman575fad32008-09-03 16:12:24 +0000190
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000191 if (PartEVT == ValueVT)
Dan Gohman575fad32008-09-03 16:12:24 +0000192 return Val;
193
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000194 if (PartEVT.isInteger() && ValueVT.isInteger()) {
195 if (ValueVT.bitsLT(PartEVT)) {
Dan Gohman575fad32008-09-03 16:12:24 +0000196 // For a truncate, see if we have any information to
197 // indicate whether the truncated bits will always be
198 // zero or sign-extension.
199 if (AssertOp != ISD::DELETED_NODE)
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000200 Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
Dan Gohman575fad32008-09-03 16:12:24 +0000201 DAG.getValueType(ValueVT));
Chris Lattner05bcb482010-08-24 23:20:40 +0000202 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
Dan Gohman575fad32008-09-03 16:12:24 +0000203 }
Chris Lattner05bcb482010-08-24 23:20:40 +0000204 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
Dan Gohman575fad32008-09-03 16:12:24 +0000205 }
206
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000207 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Chris Lattner05bcb482010-08-24 23:20:40 +0000208 // FP_ROUND's are always exact here.
209 if (ValueVT.bitsLT(Val.getValueType()))
210 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
Pete Coopere3d305a2012-01-17 01:54:07 +0000211 DAG.getTargetConstant(1, TLI.getPointerTy()));
Bill Wendling919b7aa2009-12-22 02:10:19 +0000212
Chris Lattner05bcb482010-08-24 23:20:40 +0000213 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
Dan Gohman575fad32008-09-03 16:12:24 +0000214 }
215
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000216 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
Wesley Peck527da1b2010-11-23 03:31:01 +0000217 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
Dan Gohman575fad32008-09-03 16:12:24 +0000218
Torok Edwinfbcc6632009-07-14 16:55:14 +0000219 llvm_unreachable("Unknown mismatch!");
Dan Gohman575fad32008-09-03 16:12:24 +0000220}
221
Benjamin Kramerfd719b92014-03-29 16:54:29 +0000222static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
223 const Twine &ErrMsg) {
224 const Instruction *I = dyn_cast_or_null<Instruction>(V);
225 if (!V)
226 return Ctx.emitError(ErrMsg);
227
228 const char *AsmError = ", possible invalid constraint for vector type";
229 if (const CallInst *CI = dyn_cast<CallInst>(I))
230 if (isa<InlineAsm>(CI->getCalledValue()))
231 return Ctx.emitError(I, ErrMsg + AsmError);
232
233 return Ctx.emitError(I, ErrMsg);
234}
235
Bill Wendling81406f62012-09-26 04:04:19 +0000236/// getCopyFromPartsVector - Create a value that contains the specified legal
237/// parts combined into the value they represent. If the parts combine to a
238/// type larger then ValueVT then AssertOp can be used to specify whether the
239/// extra bits are known to be zero (ISD::AssertZext) or sign extended from
240/// ValueVT (ISD::AssertSext).
Andrew Trickef9de2a2013-05-25 02:42:55 +0000241static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
Chris Lattner05bcb482010-08-24 23:20:40 +0000242 const SDValue *Parts, unsigned NumParts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000243 MVT PartVT, EVT ValueVT, const Value *V) {
Chris Lattner05bcb482010-08-24 23:20:40 +0000244 assert(ValueVT.isVector() && "Not a vector value");
245 assert(NumParts > 0 && "No parts to assemble!");
246 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
247 SDValue Val = Parts[0];
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000248
Chris Lattner05bcb482010-08-24 23:20:40 +0000249 // Handle a multi-element vector.
250 if (NumParts > 1) {
Patrik Hagglund3f1905192012-12-19 11:53:21 +0000251 EVT IntermediateVT;
252 MVT RegisterVT;
Chris Lattner05bcb482010-08-24 23:20:40 +0000253 unsigned NumIntermediates;
254 unsigned NumRegs =
255 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
256 NumIntermediates, RegisterVT);
257 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
258 NumParts = NumRegs; // Silence a compiler warning.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000259 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
Patrik Hagglund3f1905192012-12-19 11:53:21 +0000260 assert(RegisterVT == Parts[0].getSimpleValueType() &&
Chris Lattner05bcb482010-08-24 23:20:40 +0000261 "Part type doesn't match part!");
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000262
Chris Lattner05bcb482010-08-24 23:20:40 +0000263 // Assemble the parts into intermediate operands.
264 SmallVector<SDValue, 8> Ops(NumIntermediates);
265 if (NumIntermediates == NumParts) {
266 // If the register was not expanded, truncate or copy the value,
267 // as appropriate.
268 for (unsigned i = 0; i != NumParts; ++i)
269 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
Bill Wendling81406f62012-09-26 04:04:19 +0000270 PartVT, IntermediateVT, V);
Chris Lattner05bcb482010-08-24 23:20:40 +0000271 } else if (NumParts > 0) {
272 // If the intermediate type was expanded, build the intermediate
273 // operands from the parts.
274 assert(NumParts % NumIntermediates == 0 &&
275 "Must expand into a divisible number of parts!");
276 unsigned Factor = NumParts / NumIntermediates;
277 for (unsigned i = 0; i != NumIntermediates; ++i)
278 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
Bill Wendling81406f62012-09-26 04:04:19 +0000279 PartVT, IntermediateVT, V);
Chris Lattner05bcb482010-08-24 23:20:40 +0000280 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000281
Chris Lattner05bcb482010-08-24 23:20:40 +0000282 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
283 // intermediate operands.
Craig Topper48d114b2014-04-26 18:35:24 +0000284 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
285 : ISD::BUILD_VECTOR,
286 DL, ValueVT, Ops);
Chris Lattner05bcb482010-08-24 23:20:40 +0000287 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000288
Chris Lattner05bcb482010-08-24 23:20:40 +0000289 // There is now one part, held in Val. Correct it to match ValueVT.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000290 EVT PartEVT = Val.getValueType();
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000291
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000292 if (PartEVT == ValueVT)
Chris Lattner05bcb482010-08-24 23:20:40 +0000293 return Val;
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000294
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000295 if (PartEVT.isVector()) {
Chris Lattner75ff0532010-08-25 22:49:25 +0000296 // If the element type of the source/dest vectors are the same, but the
297 // parts vector has more elements than the value vector, then we have a
298 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
299 // elements we want.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000300 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
301 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
Chris Lattner75ff0532010-08-25 22:49:25 +0000302 "Cannot narrow, it would be a lossy transformation");
303 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
Tom Stellardd42c5942013-08-05 22:22:01 +0000304 DAG.getConstant(0, TLI.getVectorIdxTy()));
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000305 }
306
Chris Lattner75ff0532010-08-25 22:49:25 +0000307 // Vector/Vector bitcast.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000308 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000309 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
310
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000311 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000312 "Cannot handle this kind of promotion");
313 // Promoted vector extract
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000314 bool Smaller = ValueVT.bitsLE(PartEVT);
Nadav Rotem083837e2011-06-12 14:49:38 +0000315 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
316 DL, ValueVT, Val);
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000317
Chris Lattner75ff0532010-08-25 22:49:25 +0000318 }
Eric Christopher0713a9d2011-06-08 23:55:35 +0000319
Eric Christopher690030c2011-06-01 19:55:10 +0000320 // Trivial bitcast if the types are the same size and the destination
321 // vector type is legal.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000322 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
Eric Christopher690030c2011-06-01 19:55:10 +0000323 TLI.isTypeLegal(ValueVT))
324 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000325
Nadav Rotem083837e2011-06-12 14:49:38 +0000326 // Handle cases such as i8 -> <1 x i1>
Bill Wendling81406f62012-09-26 04:04:19 +0000327 if (ValueVT.getVectorNumElements() != 1) {
Benjamin Kramerfd719b92014-03-29 16:54:29 +0000328 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
329 "non-trivial scalar-to-vector conversion");
Chad Rosier8e4824f2013-05-01 19:49:26 +0000330 return DAG.getUNDEF(ValueVT);
Bill Wendling81406f62012-09-26 04:04:19 +0000331 }
Nadav Rotem083837e2011-06-12 14:49:38 +0000332
333 if (ValueVT.getVectorNumElements() == 1 &&
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000334 ValueVT.getVectorElementType() != PartEVT) {
335 bool Smaller = ValueVT.bitsLE(PartEVT);
Nadav Rotem083837e2011-06-12 14:49:38 +0000336 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
337 DL, ValueVT.getScalarType(), Val);
338 }
339
Chris Lattner05bcb482010-08-24 23:20:40 +0000340 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
341}
342
Andrew Trickef9de2a2013-05-25 02:42:55 +0000343static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
Chris Lattner96a77eb2010-08-24 23:10:06 +0000344 SDValue Val, SDValue *Parts, unsigned NumParts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000345 MVT PartVT, const Value *V);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000346
Dan Gohman575fad32008-09-03 16:12:24 +0000347/// getCopyToParts - Create a series of nodes that contain the specified value
348/// split into legal parts. If the parts contain more bits than Val, then, for
349/// integers, ExtendKind can be used to specify how to generate the extra bits.
Andrew Trickef9de2a2013-05-25 02:42:55 +0000350static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
Bill Wendling919b7aa2009-12-22 02:10:19 +0000351 SDValue Val, SDValue *Parts, unsigned NumParts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000352 MVT PartVT, const Value *V,
Dan Gohman575fad32008-09-03 16:12:24 +0000353 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000354 EVT ValueVT = Val.getValueType();
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000355
Chris Lattner96a77eb2010-08-24 23:10:06 +0000356 // Handle the vector case separately.
357 if (ValueVT.isVector())
Bill Wendling5def8912012-09-26 06:16:18 +0000358 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000359
Chris Lattner96a77eb2010-08-24 23:10:06 +0000360 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman575fad32008-09-03 16:12:24 +0000361 unsigned PartBits = PartVT.getSizeInBits();
Dale Johannesen7d12ea02009-02-25 22:39:13 +0000362 unsigned OrigNumParts = NumParts;
Dan Gohman575fad32008-09-03 16:12:24 +0000363 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
364
Chris Lattner96a77eb2010-08-24 23:10:06 +0000365 if (NumParts == 0)
Dan Gohman575fad32008-09-03 16:12:24 +0000366 return;
367
Chris Lattner96a77eb2010-08-24 23:10:06 +0000368 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000369 EVT PartEVT = PartVT;
370 if (PartEVT == ValueVT) {
Chris Lattner96a77eb2010-08-24 23:10:06 +0000371 assert(NumParts == 1 && "No-op copy with multiple parts!");
Dan Gohman575fad32008-09-03 16:12:24 +0000372 Parts[0] = Val;
373 return;
374 }
375
Chris Lattner96a77eb2010-08-24 23:10:06 +0000376 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
377 // If the parts cover more bits than the value has, promote the value.
378 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
379 assert(NumParts == 1 && "Do not know what to promote to!");
380 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
381 } else {
Bill Wendling38b31612012-02-23 23:25:25 +0000382 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
383 ValueVT.isInteger() &&
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000384 "Unknown mismatch!");
Chris Lattner96a77eb2010-08-24 23:10:06 +0000385 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
386 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
Bill Wendling38b31612012-02-23 23:25:25 +0000387 if (PartVT == MVT::x86mmx)
388 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattner96a77eb2010-08-24 23:10:06 +0000389 }
390 } else if (PartBits == ValueVT.getSizeInBits()) {
391 // Different types of the same size.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000392 assert(NumParts == 1 && PartEVT != ValueVT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000393 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattner96a77eb2010-08-24 23:10:06 +0000394 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
395 // If the parts cover less bits than value has, truncate the value.
Bill Wendling38b31612012-02-23 23:25:25 +0000396 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
397 ValueVT.isInteger() &&
Chris Lattner96a77eb2010-08-24 23:10:06 +0000398 "Unknown mismatch!");
399 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
400 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
Bill Wendling38b31612012-02-23 23:25:25 +0000401 if (PartVT == MVT::x86mmx)
402 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattner96a77eb2010-08-24 23:10:06 +0000403 }
404
405 // The value may have changed - recompute ValueVT.
406 ValueVT = Val.getValueType();
407 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
408 "Failed to tile the value with PartVT!");
409
410 if (NumParts == 1) {
Benjamin Kramerfd719b92014-03-29 16:54:29 +0000411 if (PartEVT != ValueVT)
412 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
413 "scalar-to-vector conversion failed");
Bill Wendling5def8912012-09-26 06:16:18 +0000414
Chris Lattner96a77eb2010-08-24 23:10:06 +0000415 Parts[0] = Val;
416 return;
417 }
418
419 // Expand the value into multiple parts.
420 if (NumParts & (NumParts - 1)) {
421 // The number of parts is not a power of 2. Split off and copy the tail.
422 assert(PartVT.isInteger() && ValueVT.isInteger() &&
423 "Do not know what to expand to!");
424 unsigned RoundParts = 1 << Log2_32(NumParts);
425 unsigned RoundBits = RoundParts * PartBits;
426 unsigned OddParts = NumParts - RoundParts;
427 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
428 DAG.getIntPtrConstant(RoundBits));
Bill Wendling5def8912012-09-26 06:16:18 +0000429 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
Chris Lattner96a77eb2010-08-24 23:10:06 +0000430
431 if (TLI.isBigEndian())
432 // The odd parts were reversed by getCopyToParts - unreverse them.
433 std::reverse(Parts + RoundParts, Parts + NumParts);
434
435 NumParts = RoundParts;
436 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
437 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
438 }
439
440 // The number of parts is a power of 2. Repeatedly bisect the value using
441 // EXTRACT_ELEMENT.
Wesley Peck527da1b2010-11-23 03:31:01 +0000442 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
Chris Lattner96a77eb2010-08-24 23:10:06 +0000443 EVT::getIntegerVT(*DAG.getContext(),
444 ValueVT.getSizeInBits()),
445 Val);
446
447 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
448 for (unsigned i = 0; i < NumParts; i += StepSize) {
449 unsigned ThisBits = StepSize * PartBits / 2;
450 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
451 SDValue &Part0 = Parts[i];
452 SDValue &Part1 = Parts[i+StepSize/2];
453
454 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
455 ThisVT, Part0, DAG.getIntPtrConstant(1));
456 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
457 ThisVT, Part0, DAG.getIntPtrConstant(0));
458
459 if (ThisBits == PartBits && ThisVT != PartVT) {
Wesley Peck527da1b2010-11-23 03:31:01 +0000460 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
461 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
Chris Lattner96a77eb2010-08-24 23:10:06 +0000462 }
463 }
464 }
465
466 if (TLI.isBigEndian())
467 std::reverse(Parts, Parts + OrigNumParts);
468}
469
470
471/// getCopyToPartsVector - Create a series of nodes that contain the specified
472/// value split into legal parts.
Andrew Trickef9de2a2013-05-25 02:42:55 +0000473static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
Chris Lattner96a77eb2010-08-24 23:10:06 +0000474 SDValue Val, SDValue *Parts, unsigned NumParts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000475 MVT PartVT, const Value *V) {
Chris Lattner96a77eb2010-08-24 23:10:06 +0000476 EVT ValueVT = Val.getValueType();
477 assert(ValueVT.isVector() && "Not a vector");
478 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000479
Chris Lattner96a77eb2010-08-24 23:10:06 +0000480 if (NumParts == 1) {
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000481 EVT PartEVT = PartVT;
482 if (PartEVT == ValueVT) {
Chris Lattner75ff0532010-08-25 22:49:25 +0000483 // Nothing to do.
484 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
485 // Bitconvert vector->vector case.
Wesley Peck527da1b2010-11-23 03:31:01 +0000486 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattner75ff0532010-08-25 22:49:25 +0000487 } else if (PartVT.isVector() &&
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000488 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
489 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
Chris Lattner75ff0532010-08-25 22:49:25 +0000490 EVT ElementVT = PartVT.getVectorElementType();
491 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
492 // undef elements.
493 SmallVector<SDValue, 16> Ops;
494 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
495 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
Tom Stellardd42c5942013-08-05 22:22:01 +0000496 ElementVT, Val, DAG.getConstant(i,
497 TLI.getVectorIdxTy())));
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000498
Chris Lattner75ff0532010-08-25 22:49:25 +0000499 for (unsigned i = ValueVT.getVectorNumElements(),
500 e = PartVT.getVectorNumElements(); i != e; ++i)
501 Ops.push_back(DAG.getUNDEF(ElementVT));
502
Craig Topper48d114b2014-04-26 18:35:24 +0000503 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
Chris Lattner75ff0532010-08-25 22:49:25 +0000504
505 // FIXME: Use CONCAT for 2x -> 4x.
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000506
Chris Lattner75ff0532010-08-25 22:49:25 +0000507 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
508 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000509 } else if (PartVT.isVector() &&
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000510 PartEVT.getVectorElementType().bitsGE(
Nadav Rotem083837e2011-06-12 14:49:38 +0000511 ValueVT.getVectorElementType()) &&
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000512 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000513
514 // Promoted vector extract
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000515 bool Smaller = PartEVT.bitsLE(ValueVT);
Nadav Rotem36896bf2011-06-19 08:49:38 +0000516 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
517 DL, PartVT, Val);
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000518 } else{
Chris Lattner75ff0532010-08-25 22:49:25 +0000519 // Vector -> scalar conversion.
Nadav Rotem083837e2011-06-12 14:49:38 +0000520 assert(ValueVT.getVectorNumElements() == 1 &&
Chris Lattner75ff0532010-08-25 22:49:25 +0000521 "Only trivial vector-to-scalar conversions should get here!");
522 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
Tom Stellardd42c5942013-08-05 22:22:01 +0000523 PartVT, Val, DAG.getConstant(0, TLI.getVectorIdxTy()));
Nadav Rotem083837e2011-06-12 14:49:38 +0000524
525 bool Smaller = ValueVT.bitsLE(PartVT);
526 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
527 DL, PartVT, Val);
Chris Lattner96a77eb2010-08-24 23:10:06 +0000528 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000529
Chris Lattner96a77eb2010-08-24 23:10:06 +0000530 Parts[0] = Val;
531 return;
532 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000533
Dan Gohman575fad32008-09-03 16:12:24 +0000534 // Handle a multi-element vector.
Patrik Hagglund3f1905192012-12-19 11:53:21 +0000535 EVT IntermediateVT;
536 MVT RegisterVT;
Dan Gohman575fad32008-09-03 16:12:24 +0000537 unsigned NumIntermediates;
Owen Anderson117c9e82009-08-12 00:36:31 +0000538 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
Devang Patel977057f2010-08-26 20:32:32 +0000539 IntermediateVT,
540 NumIntermediates, RegisterVT);
Dan Gohman575fad32008-09-03 16:12:24 +0000541 unsigned NumElements = ValueVT.getVectorNumElements();
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000542
Dan Gohman575fad32008-09-03 16:12:24 +0000543 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
544 NumParts = NumRegs; // Silence a compiler warning.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000545 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000546
Dan Gohman575fad32008-09-03 16:12:24 +0000547 // Split the vector into intermediate operands.
548 SmallVector<SDValue, 8> Ops(NumIntermediates);
Bill Wendling919b7aa2009-12-22 02:10:19 +0000549 for (unsigned i = 0; i != NumIntermediates; ++i) {
Dan Gohman575fad32008-09-03 16:12:24 +0000550 if (IntermediateVT.isVector())
Chris Lattner96a77eb2010-08-24 23:10:06 +0000551 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
Dan Gohman575fad32008-09-03 16:12:24 +0000552 IntermediateVT, Val,
Tom Stellardd42c5942013-08-05 22:22:01 +0000553 DAG.getConstant(i * (NumElements / NumIntermediates),
554 TLI.getVectorIdxTy()));
Dan Gohman575fad32008-09-03 16:12:24 +0000555 else
Chris Lattner96a77eb2010-08-24 23:10:06 +0000556 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
Tom Stellardd42c5942013-08-05 22:22:01 +0000557 IntermediateVT, Val,
558 DAG.getConstant(i, TLI.getVectorIdxTy()));
Bill Wendling919b7aa2009-12-22 02:10:19 +0000559 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000560
Dan Gohman575fad32008-09-03 16:12:24 +0000561 // Split the intermediate operands into legal parts.
562 if (NumParts == NumIntermediates) {
563 // If the register was not expanded, promote or copy the value,
564 // as appropriate.
565 for (unsigned i = 0; i != NumParts; ++i)
Bill Wendling5def8912012-09-26 06:16:18 +0000566 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
Dan Gohman575fad32008-09-03 16:12:24 +0000567 } else if (NumParts > 0) {
568 // If the intermediate type was expanded, split each the value into
569 // legal parts.
Michael Ilsemanaddddc42014-12-15 18:48:43 +0000570 assert(NumIntermediates != 0 && "division by zero");
Dan Gohman575fad32008-09-03 16:12:24 +0000571 assert(NumParts % NumIntermediates == 0 &&
572 "Must expand into a divisible number of parts!");
573 unsigned Factor = NumParts / NumIntermediates;
574 for (unsigned i = 0; i != NumIntermediates; ++i)
Bill Wendling5def8912012-09-26 06:16:18 +0000575 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
Dan Gohman575fad32008-09-03 16:12:24 +0000576 }
577}
578
Dan Gohman4db93c92010-05-29 17:53:24 +0000579namespace {
580 /// RegsForValue - This struct represents the registers (physical or virtual)
581 /// that a particular set of values is assigned, and the type information
582 /// about the value. The most common situation is to represent one value at a
583 /// time, but struct or array values are handled element-wise as multiple
584 /// values. The splitting of aggregates is performed recursively, so that we
585 /// never have aggregate-typed registers. The values at this point do not
586 /// necessarily have legal types, so each value may require one or more
587 /// registers of some legal type.
588 ///
589 struct RegsForValue {
590 /// ValueVTs - The value types of the values, which may not be legal, and
591 /// may need be promoted or synthesized from one or more registers.
592 ///
593 SmallVector<EVT, 4> ValueVTs;
594
595 /// RegVTs - The value types of the registers. This is the same size as
596 /// ValueVTs and it records, for each value, what the type of the assigned
597 /// register or registers are. (Individual values are never synthesized
598 /// from more than one type of register.)
599 ///
600 /// With virtual registers, the contents of RegVTs is redundant with TLI's
601 /// getRegisterType member function, however when with physical registers
602 /// it is necessary to have a separate record of the types.
603 ///
Patrik Hagglund4e0f8282012-12-19 12:23:01 +0000604 SmallVector<MVT, 4> RegVTs;
Dan Gohman4db93c92010-05-29 17:53:24 +0000605
606 /// Regs - This list holds the registers assigned to the values.
607 /// Each legal or promoted value requires one register, and each
608 /// expanded value requires multiple registers.
609 ///
610 SmallVector<unsigned, 4> Regs;
611
612 RegsForValue() {}
613
614 RegsForValue(const SmallVector<unsigned, 4> &regs,
Patrik Hagglund4e0f8282012-12-19 12:23:01 +0000615 MVT regvt, EVT valuevt)
Dan Gohman4db93c92010-05-29 17:53:24 +0000616 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
617
Dan Gohman4db93c92010-05-29 17:53:24 +0000618 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
Chris Lattner229907c2011-07-18 04:54:35 +0000619 unsigned Reg, Type *Ty) {
Dan Gohman4db93c92010-05-29 17:53:24 +0000620 ComputeValueVTs(tli, Ty, ValueVTs);
621
622 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
623 EVT ValueVT = ValueVTs[Value];
624 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
Patrik Hagglundbad545c2012-12-19 11:48:16 +0000625 MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
Dan Gohman4db93c92010-05-29 17:53:24 +0000626 for (unsigned i = 0; i != NumRegs; ++i)
627 Regs.push_back(Reg + i);
628 RegVTs.push_back(RegisterVT);
629 Reg += NumRegs;
630 }
631 }
632
Dan Gohman4db93c92010-05-29 17:53:24 +0000633 /// append - Add the specified values to this one.
634 void append(const RegsForValue &RHS) {
635 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
636 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
637 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
638 }
639
640 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
641 /// this value and returns the result as a ValueVTs value. This uses
642 /// Chain/Flag as the input and updates them for the output Chain/Flag.
643 /// If the Flag pointer is NULL, no flag is used.
644 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000645 SDLoc dl,
Bill Wendling81406f62012-09-26 04:04:19 +0000646 SDValue &Chain, SDValue *Flag,
Craig Topperc0196b12014-04-14 00:51:57 +0000647 const Value *V = nullptr) const;
Dan Gohman4db93c92010-05-29 17:53:24 +0000648
649 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
650 /// specified value into the registers specified by this object. This uses
651 /// Chain/Flag as the input and updates them for the output Chain/Flag.
652 /// If the Flag pointer is NULL, no flag is used.
Jiangning Liuffbc6902014-09-19 05:30:35 +0000653 void
654 getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl, SDValue &Chain,
655 SDValue *Flag, const Value *V,
656 ISD::NodeType PreferredExtendType = ISD::ANY_EXTEND) const;
Dan Gohman4db93c92010-05-29 17:53:24 +0000657
658 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
659 /// operand list. This adds the code marker, matching input operand index
660 /// (if applicable), and includes the number of values added into it.
661 void AddInlineAsmOperands(unsigned Kind,
662 bool HasMatching, unsigned MatchingIdx,
663 SelectionDAG &DAG,
664 std::vector<SDValue> &Ops) const;
665 };
666}
667
668/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
669/// this value and returns the result as a ValueVT value. This uses
670/// Chain/Flag as the input and updates them for the output Chain/Flag.
671/// If the Flag pointer is NULL, no flag is used.
672SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
673 FunctionLoweringInfo &FuncInfo,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000674 SDLoc dl,
Bill Wendling81406f62012-09-26 04:04:19 +0000675 SDValue &Chain, SDValue *Flag,
676 const Value *V) const {
Dan Gohman2810bac2010-07-26 18:15:41 +0000677 // A Value with type {} or [0 x %t] needs no registers.
678 if (ValueVTs.empty())
679 return SDValue();
680
Dan Gohman4db93c92010-05-29 17:53:24 +0000681 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
682
683 // Assemble the legal parts into the final values.
684 SmallVector<SDValue, 4> Values(ValueVTs.size());
685 SmallVector<SDValue, 8> Parts;
686 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
687 // Copy the legal parts from the registers.
688 EVT ValueVT = ValueVTs[Value];
689 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
Patrik Hagglund4e0f8282012-12-19 12:23:01 +0000690 MVT RegisterVT = RegVTs[Value];
Dan Gohman4db93c92010-05-29 17:53:24 +0000691
692 Parts.resize(NumRegs);
693 for (unsigned i = 0; i != NumRegs; ++i) {
694 SDValue P;
Craig Topperc0196b12014-04-14 00:51:57 +0000695 if (!Flag) {
Dan Gohman4db93c92010-05-29 17:53:24 +0000696 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
697 } else {
698 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
699 *Flag = P.getValue(2);
700 }
701
702 Chain = P.getValue(1);
Chris Lattnercb404362010-12-13 01:11:17 +0000703 Parts[i] = P;
Dan Gohman4db93c92010-05-29 17:53:24 +0000704
705 // If the source register was virtual and if we know something about it,
706 // add an assert node.
Chris Lattnercb404362010-12-13 01:11:17 +0000707 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
Cameron Zwarich64706472011-02-24 10:00:08 +0000708 !RegisterVT.isInteger() || RegisterVT.isVector())
Chris Lattnercb404362010-12-13 01:11:17 +0000709 continue;
Cameron Zwarich64706472011-02-24 10:00:08 +0000710
711 const FunctionLoweringInfo::LiveOutInfo *LOI =
712 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
713 if (!LOI)
714 continue;
Dan Gohman4db93c92010-05-29 17:53:24 +0000715
Chris Lattnercb404362010-12-13 01:11:17 +0000716 unsigned RegSize = RegisterVT.getSizeInBits();
Cameron Zwarich64706472011-02-24 10:00:08 +0000717 unsigned NumSignBits = LOI->NumSignBits;
718 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
Dan Gohman4db93c92010-05-29 17:53:24 +0000719
Quentin Colombetb51a6862013-06-18 20:14:39 +0000720 if (NumZeroBits == RegSize) {
721 // The current value is a zero.
722 // Explicitly express that as it would be easier for
723 // optimizations to kick in.
724 Parts[i] = DAG.getConstant(0, RegisterVT);
725 continue;
726 }
727
Chris Lattnercb404362010-12-13 01:11:17 +0000728 // FIXME: We capture more information than the dag can represent. For
729 // now, just use the tightest assertzext/assertsext possible.
730 bool isSExt = true;
731 EVT FromVT(MVT::Other);
732 if (NumSignBits == RegSize)
733 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
734 else if (NumZeroBits >= RegSize-1)
735 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
736 else if (NumSignBits > RegSize-8)
737 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
738 else if (NumZeroBits >= RegSize-8)
739 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
740 else if (NumSignBits > RegSize-16)
741 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
742 else if (NumZeroBits >= RegSize-16)
743 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
744 else if (NumSignBits > RegSize-32)
745 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
746 else if (NumZeroBits >= RegSize-32)
747 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
748 else
749 continue;
Dan Gohman4db93c92010-05-29 17:53:24 +0000750
Chris Lattnercb404362010-12-13 01:11:17 +0000751 // Add an assertion node.
752 assert(FromVT != MVT::Other);
753 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
754 RegisterVT, P, DAG.getValueType(FromVT));
Dan Gohman4db93c92010-05-29 17:53:24 +0000755 }
756
757 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
Bill Wendling81406f62012-09-26 04:04:19 +0000758 NumRegs, RegisterVT, ValueVT, V);
Dan Gohman4db93c92010-05-29 17:53:24 +0000759 Part += NumRegs;
760 Parts.clear();
761 }
762
Craig Topper48d114b2014-04-26 18:35:24 +0000763 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
Dan Gohman4db93c92010-05-29 17:53:24 +0000764}
765
766/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
767/// specified value into the registers specified by this object. This uses
768/// Chain/Flag as the input and updates them for the output Chain/Flag.
769/// If the Flag pointer is NULL, no flag is used.
Andrew Trickef9de2a2013-05-25 02:42:55 +0000770void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
Jiangning Liuffbc6902014-09-19 05:30:35 +0000771 SDValue &Chain, SDValue *Flag, const Value *V,
772 ISD::NodeType PreferredExtendType) const {
Dan Gohman4db93c92010-05-29 17:53:24 +0000773 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Jiangning Liuffbc6902014-09-19 05:30:35 +0000774 ISD::NodeType ExtendKind = PreferredExtendType;
Dan Gohman4db93c92010-05-29 17:53:24 +0000775
776 // Get the list of the values's legal parts.
777 unsigned NumRegs = Regs.size();
778 SmallVector<SDValue, 8> Parts(NumRegs);
779 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
780 EVT ValueVT = ValueVTs[Value];
781 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
Patrik Hagglund4e0f8282012-12-19 12:23:01 +0000782 MVT RegisterVT = RegVTs[Value];
Jiangning Liuffbc6902014-09-19 05:30:35 +0000783
784 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
785 ExtendKind = ISD::ZERO_EXTEND;
Dan Gohman4db93c92010-05-29 17:53:24 +0000786
Chris Lattner05bcb482010-08-24 23:20:40 +0000787 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
Evan Cheng9ec512d2012-12-06 19:13:27 +0000788 &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
Dan Gohman4db93c92010-05-29 17:53:24 +0000789 Part += NumParts;
790 }
791
792 // Copy the parts into the registers.
793 SmallVector<SDValue, 8> Chains(NumRegs);
794 for (unsigned i = 0; i != NumRegs; ++i) {
795 SDValue Part;
Craig Topperc0196b12014-04-14 00:51:57 +0000796 if (!Flag) {
Dan Gohman4db93c92010-05-29 17:53:24 +0000797 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
798 } else {
799 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
800 *Flag = Part.getValue(1);
801 }
802
803 Chains[i] = Part.getValue(0);
804 }
805
806 if (NumRegs == 1 || Flag)
807 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
808 // flagged to it. That is the CopyToReg nodes and the user are considered
809 // a single scheduling unit. If we create a TokenFactor and return it as
810 // chain, then the TokenFactor is both a predecessor (operand) of the
811 // user as well as a successor (the TF operands are flagged to the user).
812 // c1, f1 = CopyToReg
813 // c2, f2 = CopyToReg
814 // c3 = TokenFactor c1, c2
815 // ...
816 // = op c3, ..., f2
817 Chain = Chains[NumRegs-1];
818 else
Craig Topper48d114b2014-04-26 18:35:24 +0000819 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
Dan Gohman4db93c92010-05-29 17:53:24 +0000820}
821
822/// AddInlineAsmOperands - Add this value to the specified inlineasm node
823/// operand list. This adds the code marker and includes the number of
824/// values added into it.
825void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
826 unsigned MatchingIdx,
827 SelectionDAG &DAG,
828 std::vector<SDValue> &Ops) const {
829 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
830
831 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
832 if (HasMatching)
833 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
Jakob Stoklund Olesen24abd9d2011-10-12 23:37:29 +0000834 else if (!Regs.empty() &&
835 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
836 // Put the register class of the virtual registers in the flag word. That
837 // way, later passes can recompute register class constraints for inline
838 // assembly as well as normal instructions.
839 // Don't do this for tied operands that can use the regclass information
840 // from the def.
841 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
842 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
843 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
844 }
845
Dan Gohman4db93c92010-05-29 17:53:24 +0000846 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
847 Ops.push_back(Res);
848
Reid Kleckneree088972013-12-10 18:27:32 +0000849 unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
Dan Gohman4db93c92010-05-29 17:53:24 +0000850 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
851 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
Patrik Hagglund4e0f8282012-12-19 12:23:01 +0000852 MVT RegisterVT = RegVTs[Value];
Dan Gohman4db93c92010-05-29 17:53:24 +0000853 for (unsigned i = 0; i != NumRegs; ++i) {
854 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Reid Kleckneree088972013-12-10 18:27:32 +0000855 unsigned TheReg = Regs[Reg++];
856 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
857
Reid Kleckneree088972013-12-10 18:27:32 +0000858 if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
Hans Wennborgacb842d2014-03-05 02:43:26 +0000859 // If we clobbered the stack pointer, MFI should know about it.
860 assert(DAG.getMachineFunction().getFrameInfo()->
861 hasInlineAsmWithSPAdjust());
Reid Kleckneree088972013-12-10 18:27:32 +0000862 }
Dan Gohman4db93c92010-05-29 17:53:24 +0000863 }
864 }
865}
Dan Gohman575fad32008-09-03 16:12:24 +0000866
Owen Andersonbb15fec2011-12-08 22:15:21 +0000867void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
868 const TargetLibraryInfo *li) {
Dan Gohman575fad32008-09-03 16:12:24 +0000869 AA = &aa;
870 GFI = gfi;
Owen Andersonbb15fec2011-12-08 22:15:21 +0000871 LibInfo = li;
Eric Christopher8b770652015-01-26 19:03:15 +0000872 DL = DAG.getTarget().getDataLayout();
Richard Smith3fb20472012-08-22 00:42:39 +0000873 Context = DAG.getContext();
Bill Wendling2730a002011-10-15 01:00:26 +0000874 LPadToCallSiteMap.clear();
Dan Gohman575fad32008-09-03 16:12:24 +0000875}
876
Dan Gohmanf5cca352010-04-14 18:24:06 +0000877/// clear - Clear out the current SelectionDAG and the associated
Dan Gohman1a6c47f2009-11-23 18:04:58 +0000878/// state and prepare this SelectionDAGBuilder object to be used
Dan Gohman575fad32008-09-03 16:12:24 +0000879/// for a new block. This doesn't clear out information about
880/// additional blocks that are needed to complete switch lowering
881/// or PHI node updating; that information is cleared out as it is
882/// consumed.
Dan Gohman1a6c47f2009-11-23 18:04:58 +0000883void SelectionDAGBuilder::clear() {
Dan Gohman575fad32008-09-03 16:12:24 +0000884 NodeMap.clear();
Devang Patelb0c76392010-06-01 19:59:01 +0000885 UnusedArgNodeMap.clear();
Dan Gohman575fad32008-09-03 16:12:24 +0000886 PendingLoads.clear();
887 PendingExports.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000888 CurInst = nullptr;
Dan Gohmanf9bbcd12009-08-05 01:29:28 +0000889 HasTailCall = false;
Nico Rieckb5262d62014-01-12 14:09:17 +0000890 SDNodeOrder = LowestSDNodeOrder;
Philip Reames1a1bdb22014-12-02 18:50:36 +0000891 StatepointLowering.clear();
Dan Gohman575fad32008-09-03 16:12:24 +0000892}
893
Devang Patel799288382011-05-23 17:44:13 +0000894/// clearDanglingDebugInfo - Clear the dangling debug information
Benjamin Kramerbde91762012-06-02 10:20:22 +0000895/// map. This function is separated from the clear so that debug
Devang Patel799288382011-05-23 17:44:13 +0000896/// information that is dangling in a basic block can be properly
897/// resolved in a different basic block. This allows the
898/// SelectionDAG to resolve dangling debug information attached
899/// to PHI nodes.
900void SelectionDAGBuilder::clearDanglingDebugInfo() {
901 DanglingDebugInfoMap.clear();
902}
903
Dan Gohman575fad32008-09-03 16:12:24 +0000904/// getRoot - Return the current virtual root of the Selection DAG,
905/// flushing any PendingLoad items. This must be done before emitting
906/// a store or any other node that may need to be ordered after any
907/// prior load instructions.
908///
Dan Gohman1a6c47f2009-11-23 18:04:58 +0000909SDValue SelectionDAGBuilder::getRoot() {
Dan Gohman575fad32008-09-03 16:12:24 +0000910 if (PendingLoads.empty())
911 return DAG.getRoot();
912
913 if (PendingLoads.size() == 1) {
914 SDValue Root = PendingLoads[0];
915 DAG.setRoot(Root);
916 PendingLoads.clear();
917 return Root;
918 }
919
920 // Otherwise, we have to make a token factor node.
Andrew Trickef9de2a2013-05-25 02:42:55 +0000921 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +0000922 PendingLoads);
Dan Gohman575fad32008-09-03 16:12:24 +0000923 PendingLoads.clear();
924 DAG.setRoot(Root);
925 return Root;
926}
927
928/// getControlRoot - Similar to getRoot, but instead of flushing all the
929/// PendingLoad items, flush all the PendingExports items. It is necessary
930/// to do this before emitting a terminator instruction.
931///
Dan Gohman1a6c47f2009-11-23 18:04:58 +0000932SDValue SelectionDAGBuilder::getControlRoot() {
Dan Gohman575fad32008-09-03 16:12:24 +0000933 SDValue Root = DAG.getRoot();
934
935 if (PendingExports.empty())
936 return Root;
937
938 // Turn all of the CopyToReg chains into one factored node.
939 if (Root.getOpcode() != ISD::EntryToken) {
940 unsigned i = 0, e = PendingExports.size();
941 for (; i != e; ++i) {
942 assert(PendingExports[i].getNode()->getNumOperands() > 1);
943 if (PendingExports[i].getNode()->getOperand(0) == Root)
944 break; // Don't add the root if we already indirectly depend on it.
945 }
946
947 if (i == e)
948 PendingExports.push_back(Root);
949 }
950
Andrew Trickef9de2a2013-05-25 02:42:55 +0000951 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +0000952 PendingExports);
Dan Gohman575fad32008-09-03 16:12:24 +0000953 PendingExports.clear();
954 DAG.setRoot(Root);
955 return Root;
956}
957
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000958void SelectionDAGBuilder::visit(const Instruction &I) {
Dan Gohman5b43aa02010-04-22 20:55:53 +0000959 // Set up outgoing PHI node register values before emitting the terminator.
960 if (isa<TerminatorInst>(&I))
961 HandlePHINodesInSuccessorBlocks(I.getParent());
962
Andrew Tricke2431c62013-05-25 03:08:10 +0000963 ++SDNodeOrder;
964
Andrew Trick175143b2013-05-25 02:20:36 +0000965 CurInst = &I;
Dan Gohmane450d742010-04-20 00:48:35 +0000966
Dan Gohman575fad32008-09-03 16:12:24 +0000967 visit(I.getOpcode(), I);
Dan Gohmane450d742010-04-20 00:48:35 +0000968
Dan Gohman950fe782010-04-20 15:03:56 +0000969 if (!isa<TerminatorInst>(&I) && !HasTailCall)
970 CopyToExportRegsIfNeeded(&I);
971
Craig Topperc0196b12014-04-14 00:51:57 +0000972 CurInst = nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +0000973}
974
Dan Gohmanf41ad472010-04-20 15:00:41 +0000975void SelectionDAGBuilder::visitPHI(const PHINode &) {
976 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
977}
978
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000979void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +0000980 // Note: this doesn't use InstVisitor, because it has to work with
981 // ConstantExpr's in addition to instructions.
982 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000983 default: llvm_unreachable("Unknown instruction type encountered!");
Dan Gohman575fad32008-09-03 16:12:24 +0000984 // Build the switch statement using the Instruction.def file.
985#define HANDLE_INST(NUM, OPCODE, CLASS) \
Galina Kistanovaaaf97352012-07-19 04:50:12 +0000986 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000987#include "llvm/IR/Instruction.def"
Dan Gohman575fad32008-09-03 16:12:24 +0000988 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +0000989}
Dan Gohman575fad32008-09-03 16:12:24 +0000990
Dale Johannesenbfd4fd72010-07-16 00:02:08 +0000991// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
992// generate the debug data structures now that we've seen its definition.
993void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
994 SDValue Val) {
995 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
Devang Patelb12ff592010-08-26 23:35:15 +0000996 if (DDI.getDI()) {
997 const DbgValueInst *DI = DDI.getDI();
Dale Johannesenbfd4fd72010-07-16 00:02:08 +0000998 DebugLoc dl = DDI.getdl();
999 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
Devang Patelb12ff592010-08-26 23:35:15 +00001000 MDNode *Variable = DI->getVariable();
Adrian Prantl87b7eb92014-10-01 18:55:02 +00001001 MDNode *Expr = DI->getExpression();
Devang Patelb12ff592010-08-26 23:35:15 +00001002 uint64_t Offset = DI->getOffset();
Adrian Prantl32da8892014-04-25 20:49:25 +00001003 // A dbg.value for an alloca is always indirect.
1004 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00001005 SDDbgValue *SDV;
1006 if (Val.getNode()) {
Adrian Prantl87b7eb92014-10-01 18:55:02 +00001007 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, Offset, IsIndirect,
1008 Val)) {
1009 SDV = DAG.getDbgValue(Variable, Expr, Val.getNode(), Val.getResNo(),
1010 IsIndirect, Offset, dl, DbgSDNodeOrder);
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00001011 DAG.AddDbgValue(SDV, Val.getNode(), false);
1012 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00001013 } else
Adrian Prantl0d1e5592013-05-22 18:02:19 +00001014 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00001015 DanglingDebugInfoMap[V] = DanglingDebugInfo();
1016 }
1017}
1018
Nick Lewyckyf40df1d2011-09-30 22:19:53 +00001019/// getValue - Return an SDValue for the given Value.
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001020SDValue SelectionDAGBuilder::getValue(const Value *V) {
Dan Gohmand4322232010-07-01 01:59:43 +00001021 // If we already have an SDValue for this value, use it. It's important
1022 // to do this first, so that we don't create a CopyFromReg if we already
1023 // have a regular SDValue.
Dan Gohman575fad32008-09-03 16:12:24 +00001024 SDValue &N = NodeMap[V];
1025 if (N.getNode()) return N;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001026
Dan Gohmand4322232010-07-01 01:59:43 +00001027 // If there's a virtual register allocated and initialized for this
1028 // value, use it.
Igor Laevsky8d0851f2015-03-05 15:41:14 +00001029 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1030 if (It != FuncInfo.ValueMap.end()) {
1031 unsigned InReg = It->second;
1032 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), InReg,
1033 V->getType());
1034 SDValue Chain = DAG.getEntryNode();
1035 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1036 resolveDanglingDebugInfo(V, N);
1037 return N;
Dan Gohmand4322232010-07-01 01:59:43 +00001038 }
1039
1040 // Otherwise create a new SDValue and remember it.
1041 SDValue Val = getValueImpl(V);
1042 NodeMap[V] = Val;
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00001043 resolveDanglingDebugInfo(V, Val);
Dan Gohmand4322232010-07-01 01:59:43 +00001044 return Val;
1045}
1046
1047/// getNonRegisterValue - Return an SDValue for the given Value, but
1048/// don't look in FuncInfo.ValueMap for a virtual register.
1049SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1050 // If we already have an SDValue for this value, use it.
1051 SDValue &N = NodeMap[V];
1052 if (N.getNode()) return N;
1053
1054 // Otherwise create a new SDValue and remember it.
1055 SDValue Val = getValueImpl(V);
1056 NodeMap[V] = Val;
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00001057 resolveDanglingDebugInfo(V, Val);
Dan Gohmand4322232010-07-01 01:59:43 +00001058 return Val;
1059}
1060
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00001061/// getValueImpl - Helper function for getValue and getNonRegisterValue.
Dan Gohmand4322232010-07-01 01:59:43 +00001062/// Create an SDValue for the given value.
1063SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
Eric Christopher58a24612014-10-08 09:50:54 +00001064 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001065
Dan Gohman8422e572010-04-17 15:32:28 +00001066 if (const Constant *C = dyn_cast<Constant>(V)) {
Eric Christopher58a24612014-10-08 09:50:54 +00001067 EVT VT = TLI.getValueType(V->getType(), true);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001068
Dan Gohman8422e572010-04-17 15:32:28 +00001069 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohmand4322232010-07-01 01:59:43 +00001070 return DAG.getConstant(*CI, VT);
Dan Gohman575fad32008-09-03 16:12:24 +00001071
Dan Gohman8422e572010-04-17 15:32:28 +00001072 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001073 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001074
Matt Arsenault19231e62013-11-16 20:24:41 +00001075 if (isa<ConstantPointerNull>(C)) {
1076 unsigned AS = V->getType()->getPointerAddressSpace();
Eric Christopher58a24612014-10-08 09:50:54 +00001077 return DAG.getConstant(0, TLI.getPointerTy(AS));
Matt Arsenault19231e62013-11-16 20:24:41 +00001078 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001079
Dan Gohman8422e572010-04-17 15:32:28 +00001080 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohmand4322232010-07-01 01:59:43 +00001081 return DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001082
Nate Begeman8d6d4b92009-04-27 18:41:29 +00001083 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
Dan Gohmand4322232010-07-01 01:59:43 +00001084 return DAG.getUNDEF(VT);
Dan Gohman575fad32008-09-03 16:12:24 +00001085
Dan Gohman8422e572010-04-17 15:32:28 +00001086 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Dan Gohman575fad32008-09-03 16:12:24 +00001087 visit(CE->getOpcode(), *CE);
1088 SDValue N1 = NodeMap[V];
Dan Gohman5664b9f2010-04-16 16:55:18 +00001089 assert(N1.getNode() && "visit didn't populate the NodeMap!");
Dan Gohman575fad32008-09-03 16:12:24 +00001090 return N1;
1091 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001092
Dan Gohman575fad32008-09-03 16:12:24 +00001093 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1094 SmallVector<SDValue, 4> Constants;
1095 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1096 OI != OE; ++OI) {
1097 SDNode *Val = getValue(*OI).getNode();
Dan Gohmanf4a0f0f2009-09-08 01:44:02 +00001098 // If the operand is an empty aggregate, there are no values.
1099 if (!Val) continue;
1100 // Add each leaf value from the operand to the Constants list
1101 // to form a flattened list of all the values.
Dan Gohman575fad32008-09-03 16:12:24 +00001102 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1103 Constants.push_back(SDValue(Val, i));
1104 }
Bill Wendlingc6b47342009-12-21 23:47:40 +00001105
Craig Topper64941d92014-04-27 19:20:57 +00001106 return DAG.getMergeValues(Constants, getCurSDLoc());
Dan Gohman575fad32008-09-03 16:12:24 +00001107 }
Stephen Lincfe7f352013-07-08 00:37:03 +00001108
Chris Lattner00245f42012-01-24 13:41:11 +00001109 if (const ConstantDataSequential *CDS =
1110 dyn_cast<ConstantDataSequential>(C)) {
1111 SmallVector<SDValue, 4> Ops;
Chris Lattner9be59592012-01-25 01:27:20 +00001112 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Chris Lattner00245f42012-01-24 13:41:11 +00001113 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1114 // Add each leaf value from the operand to the Constants list
1115 // to form a flattened list of all the values.
1116 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1117 Ops.push_back(SDValue(Val, i));
1118 }
1119
1120 if (isa<ArrayType>(CDS->getType()))
Craig Topper64941d92014-04-27 19:20:57 +00001121 return DAG.getMergeValues(Ops, getCurSDLoc());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001122 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00001123 VT, Ops);
Chris Lattner00245f42012-01-24 13:41:11 +00001124 }
Dan Gohman575fad32008-09-03 16:12:24 +00001125
Duncan Sands19d0b472010-02-16 11:11:14 +00001126 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
Dan Gohman575fad32008-09-03 16:12:24 +00001127 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1128 "Unknown struct or array constant!");
1129
Owen Anderson53aa7a92009-08-10 22:56:29 +00001130 SmallVector<EVT, 4> ValueVTs;
Eric Christopher58a24612014-10-08 09:50:54 +00001131 ComputeValueVTs(TLI, C->getType(), ValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00001132 unsigned NumElts = ValueVTs.size();
1133 if (NumElts == 0)
1134 return SDValue(); // empty struct
1135 SmallVector<SDValue, 4> Constants(NumElts);
1136 for (unsigned i = 0; i != NumElts; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001137 EVT EltVT = ValueVTs[i];
Dan Gohman575fad32008-09-03 16:12:24 +00001138 if (isa<UndefValue>(C))
Dale Johannesen84935752009-02-06 23:05:02 +00001139 Constants[i] = DAG.getUNDEF(EltVT);
Dan Gohman575fad32008-09-03 16:12:24 +00001140 else if (EltVT.isFloatingPoint())
1141 Constants[i] = DAG.getConstantFP(0, EltVT);
1142 else
1143 Constants[i] = DAG.getConstant(0, EltVT);
1144 }
Bill Wendlingc6b47342009-12-21 23:47:40 +00001145
Craig Topper64941d92014-04-27 19:20:57 +00001146 return DAG.getMergeValues(Constants, getCurSDLoc());
Dan Gohman575fad32008-09-03 16:12:24 +00001147 }
1148
Dan Gohman8422e572010-04-17 15:32:28 +00001149 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
Dan Gohman7a6611792009-11-20 23:18:13 +00001150 return DAG.getBlockAddress(BA, VT);
Dan Gohman6c938802009-10-30 01:27:03 +00001151
Chris Lattner229907c2011-07-18 04:54:35 +00001152 VectorType *VecTy = cast<VectorType>(V->getType());
Dan Gohman575fad32008-09-03 16:12:24 +00001153 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001154
Dan Gohman575fad32008-09-03 16:12:24 +00001155 // Now that we know the number and type of the elements, get that number of
1156 // elements into the Ops array based on what kind of constant it is.
1157 SmallVector<SDValue, 16> Ops;
Chris Lattner00245f42012-01-24 13:41:11 +00001158 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
Dan Gohman575fad32008-09-03 16:12:24 +00001159 for (unsigned i = 0; i != NumElements; ++i)
Chris Lattner00245f42012-01-24 13:41:11 +00001160 Ops.push_back(getValue(CV->getOperand(i)));
Dan Gohman575fad32008-09-03 16:12:24 +00001161 } else {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00001162 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Eric Christopher58a24612014-10-08 09:50:54 +00001163 EVT EltVT = TLI.getValueType(VecTy->getElementType());
Dan Gohman575fad32008-09-03 16:12:24 +00001164
1165 SDValue Op;
Nate Begeman8d6d4b92009-04-27 18:41:29 +00001166 if (EltVT.isFloatingPoint())
Dan Gohman575fad32008-09-03 16:12:24 +00001167 Op = DAG.getConstantFP(0, EltVT);
1168 else
1169 Op = DAG.getConstant(0, EltVT);
1170 Ops.assign(NumElements, Op);
1171 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001172
Dan Gohman575fad32008-09-03 16:12:24 +00001173 // Create a BUILD_VECTOR node.
Craig Topper48d114b2014-04-26 18:35:24 +00001174 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
Dan Gohman575fad32008-09-03 16:12:24 +00001175 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001176
Dan Gohman575fad32008-09-03 16:12:24 +00001177 // If this is a static alloca, generate it as the frameindex instead of
1178 // computation.
1179 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1180 DenseMap<const AllocaInst*, int>::iterator SI =
1181 FuncInfo.StaticAllocaMap.find(AI);
1182 if (SI != FuncInfo.StaticAllocaMap.end())
Eric Christopher58a24612014-10-08 09:50:54 +00001183 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
Dan Gohman575fad32008-09-03 16:12:24 +00001184 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001185
Dan Gohmand4322232010-07-01 01:59:43 +00001186 // If this is an instruction which fast-isel has deferred, select it now.
1187 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +00001188 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
Eric Christopher58a24612014-10-08 09:50:54 +00001189 RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
Dan Gohmand7b5ce32010-07-10 09:00:22 +00001190 SDValue Chain = DAG.getEntryNode();
Craig Topperc0196b12014-04-14 00:51:57 +00001191 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
Dan Gohmand4322232010-07-01 01:59:43 +00001192 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001193
Dan Gohmand4322232010-07-01 01:59:43 +00001194 llvm_unreachable("Can't get register for value!");
Dan Gohman575fad32008-09-03 16:12:24 +00001195}
1196
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001197void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
Eric Christopher58a24612014-10-08 09:50:54 +00001198 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00001199 SDValue Chain = getControlRoot();
1200 SmallVector<ISD::OutputArg, 8> Outs;
Dan Gohmanfe7532a2010-07-07 15:54:55 +00001201 SmallVector<SDValue, 8> OutVals;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00001202
Dan Gohmand16aa542010-05-29 17:03:36 +00001203 if (!FuncInfo.CanLowerReturn) {
1204 unsigned DemoteReg = FuncInfo.DemoteRegister;
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001205 const Function *F = I.getParent()->getParent();
1206
1207 // Emit a store of the return value through the virtual register.
1208 // Leave Outs empty so that LowerReturn won't try to load return
1209 // registers the usual way.
1210 SmallVector<EVT, 1> PtrValueVTs;
Eric Christopher58a24612014-10-08 09:50:54 +00001211 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001212 PtrValueVTs);
1213
1214 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1215 SDValue RetOp = getValue(I.getOperand(0));
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00001216
Owen Anderson53aa7a92009-08-10 22:56:29 +00001217 SmallVector<EVT, 4> ValueVTs;
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001218 SmallVector<uint64_t, 4> Offsets;
Eric Christopher58a24612014-10-08 09:50:54 +00001219 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
Dan Gohman8b44b882008-10-21 20:00:42 +00001220 unsigned NumValues = ValueVTs.size();
Dan Gohman8b44b882008-10-21 20:00:42 +00001221
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001222 SmallVector<SDValue, 4> Chains(NumValues);
Bill Wendlingc6b47342009-12-21 23:47:40 +00001223 for (unsigned i = 0; i != NumValues; ++i) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001224 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
Chris Lattner96a77eb2010-08-24 23:10:06 +00001225 RetPtr.getValueType(), RetPtr,
1226 DAG.getIntPtrConstant(Offsets[i]));
Bill Wendlingc6b47342009-12-21 23:47:40 +00001227 Chains[i] =
Andrew Trickef9de2a2013-05-25 02:42:55 +00001228 DAG.getStore(Chain, getCurSDLoc(),
Bill Wendlingc6b47342009-12-21 23:47:40 +00001229 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
Chris Lattnera4f19972010-09-21 18:58:22 +00001230 // FIXME: better loc info would be nice.
1231 Add, MachinePointerInfo(), false, false, 0);
Bill Wendlingc6b47342009-12-21 23:47:40 +00001232 }
1233
Andrew Trickef9de2a2013-05-25 02:42:55 +00001234 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00001235 MVT::Other, Chains);
Chris Lattnerb1af8652010-02-28 18:53:13 +00001236 } else if (I.getNumOperands() != 0) {
1237 SmallVector<EVT, 4> ValueVTs;
Eric Christopher58a24612014-10-08 09:50:54 +00001238 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
Chris Lattnerb1af8652010-02-28 18:53:13 +00001239 unsigned NumValues = ValueVTs.size();
1240 if (NumValues) {
1241 SDValue RetOp = getValue(I.getOperand(0));
Mehdi Aminif3721bf2015-01-06 18:20:04 +00001242
1243 const Function *F = I.getParent()->getParent();
1244
1245 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1246 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1247 Attribute::SExt))
1248 ExtendKind = ISD::SIGN_EXTEND;
1249 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1250 Attribute::ZExt))
1251 ExtendKind = ISD::ZERO_EXTEND;
1252
1253 LLVMContext &Context = F->getContext();
1254 bool RetInReg = F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1255 Attribute::InReg);
1256
1257 for (unsigned j = 0; j != NumValues; ++j) {
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001258 EVT VT = ValueVTs[j];
Dan Gohman575fad32008-09-03 16:12:24 +00001259
Cameron Zwarich2ef0c692011-03-17 14:53:37 +00001260 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
Mehdi Aminif3721bf2015-01-06 18:20:04 +00001261 VT = TLI.getTypeForExtArgOrReturn(Context, VT, ExtendKind);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001262
Mehdi Aminif3721bf2015-01-06 18:20:04 +00001263 unsigned NumParts = TLI.getNumRegisters(Context, VT);
1264 MVT PartVT = TLI.getRegisterType(Context, VT);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001265 SmallVector<SDValue, 4> Parts(NumParts);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001266 getCopyToParts(DAG, getCurSDLoc(),
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001267 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
Bill Wendling5def8912012-09-26 06:16:18 +00001268 &Parts[0], NumParts, PartVT, &I, ExtendKind);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001269
1270 // 'inreg' on function refers to return value
1271 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Mehdi Aminif3721bf2015-01-06 18:20:04 +00001272 if (RetInReg)
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001273 Flags.setInReg();
1274
1275 // Propagate extension type if any
Cameron Zwarichd1ad9bc2011-03-16 22:20:07 +00001276 if (ExtendKind == ISD::SIGN_EXTEND)
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001277 Flags.setSExt();
Cameron Zwarichd1ad9bc2011-03-16 22:20:07 +00001278 else if (ExtendKind == ISD::ZERO_EXTEND)
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001279 Flags.setZExt();
1280
Dan Gohmanfe7532a2010-07-07 15:54:55 +00001281 for (unsigned i = 0; i < NumParts; ++i) {
1282 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
Tom Stellard8d7d4de2013-10-23 00:44:24 +00001283 VT, /*isfixed=*/true, 0, 0));
Dan Gohmanfe7532a2010-07-07 15:54:55 +00001284 OutVals.push_back(Parts[i]);
1285 }
Evan Cheng2e9f42b2009-03-25 20:20:11 +00001286 }
Dan Gohman575fad32008-09-03 16:12:24 +00001287 }
1288 }
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00001289
1290 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
Sandeep Patel68c5f472009-09-02 08:44:58 +00001291 CallingConv::ID CallConv =
1292 DAG.getMachineFunction().getFunction()->getCallingConv();
Eric Christopher58a24612014-10-08 09:50:54 +00001293 Chain = DAG.getTargetLoweringInfo().LowerReturn(
Eric Christopherd9134482014-08-04 21:25:23 +00001294 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
Dan Gohman695d8112009-08-06 15:37:27 +00001295
1296 // Verify that the target's LowerReturn behaved as expected.
Owen Anderson9f944592009-08-11 20:47:22 +00001297 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman695d8112009-08-06 15:37:27 +00001298 "LowerReturn didn't return a valid chain!");
1299
1300 // Update the DAG with the new chain value resulting from return lowering.
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00001301 DAG.setRoot(Chain);
Dan Gohman575fad32008-09-03 16:12:24 +00001302}
1303
Dan Gohman9478c3f2009-04-23 23:13:24 +00001304/// CopyToExportRegsIfNeeded - If the given value has virtual registers
1305/// created for it, emit nodes to copy the value into the virtual
1306/// registers.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001307void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
Rafael Espindolae53b7d12011-05-13 15:18:06 +00001308 // Skip empty types
1309 if (V->getType()->isEmptyTy())
1310 return;
1311
Dan Gohman3a7ee8e2010-04-16 17:15:02 +00001312 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1313 if (VMI != FuncInfo.ValueMap.end()) {
1314 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1315 CopyValueToVirtualRegister(V, VMI->second);
Dan Gohman9478c3f2009-04-23 23:13:24 +00001316 }
1317}
1318
Dan Gohman575fad32008-09-03 16:12:24 +00001319/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1320/// the current basic block, add it to ValueMap now so that we'll get a
1321/// CopyTo/FromReg.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001322void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
Dan Gohman575fad32008-09-03 16:12:24 +00001323 // No need to export constants.
1324 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001325
Dan Gohman575fad32008-09-03 16:12:24 +00001326 // Already exported?
1327 if (FuncInfo.isExportedInst(V)) return;
1328
1329 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1330 CopyValueToVirtualRegister(V, Reg);
1331}
1332
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001333bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001334 const BasicBlock *FromBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00001335 // The operands of the setcc have to be in this block. We don't know
1336 // how to export them from some other block.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001337 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
Dan Gohman575fad32008-09-03 16:12:24 +00001338 // Can export from current BB.
1339 if (VI->getParent() == FromBB)
1340 return true;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001341
Dan Gohman575fad32008-09-03 16:12:24 +00001342 // Is already exported, noop.
1343 return FuncInfo.isExportedInst(V);
1344 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001345
Dan Gohman575fad32008-09-03 16:12:24 +00001346 // If this is an argument, we can export it if the BB is the entry block or
1347 // if it is already exported.
1348 if (isa<Argument>(V)) {
1349 if (FromBB == &FromBB->getParent()->getEntryBlock())
1350 return true;
1351
1352 // Otherwise, can only export this if it is already exported.
1353 return FuncInfo.isExportedInst(V);
1354 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001355
Dan Gohman575fad32008-09-03 16:12:24 +00001356 // Otherwise, constants can always be exported.
1357 return true;
1358}
1359
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001360/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
Jakub Staszak96f8c552011-12-20 20:03:10 +00001361uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1362 const MachineBasicBlock *Dst) const {
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001363 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1364 if (!BPI)
1365 return 0;
Jakub Staszak539db982011-07-29 20:05:36 +00001366 const BasicBlock *SrcBB = Src->getBasicBlock();
1367 const BasicBlock *DstBB = Dst->getBasicBlock();
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001368 return BPI->getEdgeWeight(SrcBB, DstBB);
1369}
1370
Jakub Staszak0480a8f2011-07-29 22:25:21 +00001371void SelectionDAGBuilder::
1372addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1373 uint32_t Weight /* = 0 */) {
1374 if (!Weight)
1375 Weight = getEdgeWeight(Src, Dst);
1376 Src->addSuccessor(Dst, Weight);
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001377}
1378
1379
Dan Gohman575fad32008-09-03 16:12:24 +00001380static bool InBlock(const Value *V, const BasicBlock *BB) {
1381 if (const Instruction *I = dyn_cast<Instruction>(V))
1382 return I->getParent() == BB;
1383 return true;
1384}
1385
Dan Gohmand01ddb52008-10-17 21:16:08 +00001386/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1387/// This function emits a branch and is used at the leaves of an OR or an
1388/// AND operator tree.
1389///
1390void
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001391SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001392 MachineBasicBlock *TBB,
1393 MachineBasicBlock *FBB,
Dan Gohman7c0303a2010-04-19 22:41:47 +00001394 MachineBasicBlock *CurBB,
Manman Ren4ece7452014-01-31 00:42:44 +00001395 MachineBasicBlock *SwitchBB,
1396 uint32_t TWeight,
1397 uint32_t FWeight) {
Dan Gohmand01ddb52008-10-17 21:16:08 +00001398 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohman575fad32008-09-03 16:12:24 +00001399
Dan Gohmand01ddb52008-10-17 21:16:08 +00001400 // If the leaf of the tree is a comparison, merge the condition into
1401 // the caseblock.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001402 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
Dan Gohmand01ddb52008-10-17 21:16:08 +00001403 // The operands of the cmp have to be in this block. We don't know
1404 // how to export them from some other block. If this is the first block
1405 // of the sequence, no exporting is needed.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001406 if (CurBB == SwitchBB ||
Dan Gohmand01ddb52008-10-17 21:16:08 +00001407 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1408 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohman575fad32008-09-03 16:12:24 +00001409 ISD::CondCode Condition;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001410 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman293abcc2008-10-17 18:18:45 +00001411 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001412 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman293abcc2008-10-17 18:18:45 +00001413 Condition = getFCmpCondCode(FC->getPredicate());
Nick Lewycky50f02cb2011-12-02 22:16:29 +00001414 if (TM.Options.NoNaNsFPMath)
1415 Condition = getFCmpCodeWithoutNaN(Condition);
Dan Gohman575fad32008-09-03 16:12:24 +00001416 } else {
Michael Ilsemanaddddc42014-12-15 18:48:43 +00001417 (void)Condition; // silence warning.
Torok Edwinfbcc6632009-07-14 16:55:14 +00001418 llvm_unreachable("Unknown compare instruction");
Dan Gohman575fad32008-09-03 16:12:24 +00001419 }
Dan Gohmand01ddb52008-10-17 21:16:08 +00001420
Craig Topperc0196b12014-04-14 00:51:57 +00001421 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1422 TBB, FBB, CurBB, TWeight, FWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001423 SwitchCases.push_back(CB);
1424 return;
1425 }
Dan Gohmand01ddb52008-10-17 21:16:08 +00001426 }
1427
1428 // Create a CaseBlock record representing this branch.
Owen Anderson23a204d2009-07-31 17:39:07 +00001429 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
Craig Topperc0196b12014-04-14 00:51:57 +00001430 nullptr, TBB, FBB, CurBB, TWeight, FWeight);
Dan Gohmand01ddb52008-10-17 21:16:08 +00001431 SwitchCases.push_back(CB);
1432}
1433
Manman Ren4ece7452014-01-31 00:42:44 +00001434/// Scale down both weights to fit into uint32_t.
1435static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
1436 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1437 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1438 NewTrue = NewTrue / Scale;
1439 NewFalse = NewFalse / Scale;
1440}
1441
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001442/// FindMergedConditions - If Cond is an expression like
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001443void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001444 MachineBasicBlock *TBB,
1445 MachineBasicBlock *FBB,
1446 MachineBasicBlock *CurBB,
Dan Gohman7c0303a2010-04-19 22:41:47 +00001447 MachineBasicBlock *SwitchBB,
Manman Ren4ece7452014-01-31 00:42:44 +00001448 unsigned Opc, uint32_t TWeight,
1449 uint32_t FWeight) {
Dan Gohmand01ddb52008-10-17 21:16:08 +00001450 // If this node is not part of the or/and tree, emit it as a branch.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001451 const Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001452 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmand01ddb52008-10-17 21:16:08 +00001453 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1454 BOp->getParent() != CurBB->getBasicBlock() ||
1455 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1456 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Manman Ren4ece7452014-01-31 00:42:44 +00001457 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1458 TWeight, FWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001459 return;
1460 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001461
Dan Gohman575fad32008-09-03 16:12:24 +00001462 // Create TmpBB after CurBB.
1463 MachineFunction::iterator BBI = CurBB;
1464 MachineFunction &MF = DAG.getMachineFunction();
1465 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1466 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001467
Dan Gohman575fad32008-09-03 16:12:24 +00001468 if (Opc == Instruction::Or) {
1469 // Codegen X | Y as:
Manman Ren4ece7452014-01-31 00:42:44 +00001470 // BB1:
Dan Gohman575fad32008-09-03 16:12:24 +00001471 // jmp_if_X TBB
1472 // jmp TmpBB
1473 // TmpBB:
1474 // jmp_if_Y TBB
1475 // jmp FBB
1476 //
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001477
Manman Ren4ece7452014-01-31 00:42:44 +00001478 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1479 // The requirement is that
1480 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1481 // = TrueProb for orignal BB.
1482 // Assuming the orignal weights are A and B, one choice is to set BB1's
1483 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
1484 // assumes that
1485 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1486 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1487 // TmpBB, but the math is more complicated.
Manman Ren104e0c82014-01-30 00:24:37 +00001488
Manman Ren4ece7452014-01-31 00:42:44 +00001489 uint64_t NewTrueWeight = TWeight;
1490 uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
1491 ScaleWeights(NewTrueWeight, NewFalseWeight);
1492 // Emit the LHS condition.
1493 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1494 NewTrueWeight, NewFalseWeight);
1495
1496 NewTrueWeight = TWeight;
1497 NewFalseWeight = 2 * (uint64_t)FWeight;
1498 ScaleWeights(NewTrueWeight, NewFalseWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001499 // Emit the RHS condition into TmpBB.
Manman Ren4ece7452014-01-31 00:42:44 +00001500 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1501 NewTrueWeight, NewFalseWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001502 } else {
1503 assert(Opc == Instruction::And && "Unknown merge op!");
1504 // Codegen X & Y as:
Manman Ren4ece7452014-01-31 00:42:44 +00001505 // BB1:
Dan Gohman575fad32008-09-03 16:12:24 +00001506 // jmp_if_X TmpBB
1507 // jmp FBB
1508 // TmpBB:
1509 // jmp_if_Y TBB
1510 // jmp FBB
1511 //
1512 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001513
Manman Ren4ece7452014-01-31 00:42:44 +00001514 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1515 // The requirement is that
1516 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1517 // = FalseProb for orignal BB.
1518 // Assuming the orignal weights are A and B, one choice is to set BB1's
1519 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
1520 // assumes that
1521 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
Manman Ren104e0c82014-01-30 00:24:37 +00001522
Manman Ren4ece7452014-01-31 00:42:44 +00001523 uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
1524 uint64_t NewFalseWeight = FWeight;
1525 ScaleWeights(NewTrueWeight, NewFalseWeight);
1526 // Emit the LHS condition.
1527 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1528 NewTrueWeight, NewFalseWeight);
1529
1530 NewTrueWeight = 2 * (uint64_t)TWeight;
1531 NewFalseWeight = FWeight;
1532 ScaleWeights(NewTrueWeight, NewFalseWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001533 // Emit the RHS condition into TmpBB.
Manman Ren4ece7452014-01-31 00:42:44 +00001534 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1535 NewTrueWeight, NewFalseWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001536 }
1537}
1538
1539/// If the set of cases should be emitted as a series of branches, return true.
1540/// If we should emit this as a bunch of and/or'd together conditions, return
1541/// false.
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001542bool
Stephen Lin6d715e82013-07-06 21:44:25 +00001543SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
Dan Gohman575fad32008-09-03 16:12:24 +00001544 if (Cases.size() != 2) return true;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001545
Dan Gohman575fad32008-09-03 16:12:24 +00001546 // If this is two comparisons of the same values or'd or and'd together, they
1547 // will get folded into a single comparison, so don't emit two blocks.
1548 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1549 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1550 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1551 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1552 return false;
1553 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001554
Chris Lattner1eea3b02010-01-02 00:00:03 +00001555 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1556 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1557 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1558 Cases[0].CC == Cases[1].CC &&
1559 isa<Constant>(Cases[0].CmpRHS) &&
1560 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1561 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1562 return false;
1563 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1564 return false;
1565 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00001566
Dan Gohman575fad32008-09-03 16:12:24 +00001567 return true;
1568}
1569
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001570void SelectionDAGBuilder::visitBr(const BranchInst &I) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +00001571 MachineBasicBlock *BrMBB = FuncInfo.MBB;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001572
Dan Gohman575fad32008-09-03 16:12:24 +00001573 // Update machine-CFG edges.
1574 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1575
1576 // Figure out which block is immediately after the current one.
Craig Topperc0196b12014-04-14 00:51:57 +00001577 MachineBasicBlock *NextBlock = nullptr;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001578 MachineFunction::iterator BBI = BrMBB;
Dan Gohmane8c913e2009-08-15 02:06:22 +00001579 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00001580 NextBlock = BBI;
1581
1582 if (I.isUnconditional()) {
1583 // Update machine-CFG edges.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001584 BrMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001585
Eric Christopherbfb38ba2014-04-03 12:11:51 +00001586 // If this is not a fall-through branch or optimizations are switched off,
1587 // emit the branch.
1588 if (Succ0MBB != NextBlock || TM.getOptLevel() == CodeGenOpt::None)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001589 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
Owen Anderson9f944592009-08-11 20:47:22 +00001590 MVT::Other, getControlRoot(),
Bill Wendling954cb182010-01-28 21:51:40 +00001591 DAG.getBasicBlock(Succ0MBB)));
Bill Wendling7f5eb532009-12-21 19:59:38 +00001592
Dan Gohman575fad32008-09-03 16:12:24 +00001593 return;
1594 }
1595
1596 // If this condition is one of the special cases we handle, do special stuff
1597 // now.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001598 const Value *CondVal = I.getCondition();
Dan Gohman575fad32008-09-03 16:12:24 +00001599 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1600
1601 // If this is a series of conditions that are or'd or and'd together, emit
1602 // this as a sequence of branches instead of setcc's with and/or operations.
Chris Lattnerea41dfe2010-11-30 18:12:52 +00001603 // As long as jumps are not expensive, this should improve performance.
Dan Gohman575fad32008-09-03 16:12:24 +00001604 // For example, instead of something like:
1605 // cmp A, B
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001606 // C = seteq
Dan Gohman575fad32008-09-03 16:12:24 +00001607 // cmp D, E
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001608 // F = setle
Dan Gohman575fad32008-09-03 16:12:24 +00001609 // or C, F
1610 // jnz foo
1611 // Emit:
1612 // cmp A, B
1613 // je foo
1614 // cmp D, E
1615 // jle foo
1616 //
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001617 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Eric Christopher58a24612014-10-08 09:50:54 +00001618 if (!DAG.getTargetLoweringInfo().isJumpExpensive() &&
Eric Christopherd9134482014-08-04 21:25:23 +00001619 BOp->hasOneUse() && (BOp->getOpcode() == Instruction::And ||
1620 BOp->getOpcode() == Instruction::Or)) {
Dan Gohman7c0303a2010-04-19 22:41:47 +00001621 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
Manman Ren4ece7452014-01-31 00:42:44 +00001622 BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB),
1623 getEdgeWeight(BrMBB, Succ1MBB));
Dan Gohman575fad32008-09-03 16:12:24 +00001624 // If the compares in later blocks need to use values not currently
1625 // exported from this block, export them now. This block should always
1626 // be the first entry.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001627 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001628
Dan Gohman575fad32008-09-03 16:12:24 +00001629 // Allow some cases to be rejected.
1630 if (ShouldEmitAsBranches(SwitchCases)) {
1631 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1632 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1633 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1634 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001635
Dan Gohman575fad32008-09-03 16:12:24 +00001636 // Emit the branch for this block.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001637 visitSwitchCase(SwitchCases[0], BrMBB);
Dan Gohman575fad32008-09-03 16:12:24 +00001638 SwitchCases.erase(SwitchCases.begin());
1639 return;
1640 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001641
Dan Gohman575fad32008-09-03 16:12:24 +00001642 // Okay, we decided not to do this, remove any inserted MBB's and clear
1643 // SwitchCases.
1644 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
Dan Gohmane8c913e2009-08-15 02:06:22 +00001645 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001646
Dan Gohman575fad32008-09-03 16:12:24 +00001647 SwitchCases.clear();
1648 }
1649 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001650
Dan Gohman575fad32008-09-03 16:12:24 +00001651 // Create a CaseBlock record representing this branch.
Owen Anderson23a204d2009-07-31 17:39:07 +00001652 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
Craig Topperc0196b12014-04-14 00:51:57 +00001653 nullptr, Succ0MBB, Succ1MBB, BrMBB);
Bill Wendling7f5eb532009-12-21 19:59:38 +00001654
Dan Gohman575fad32008-09-03 16:12:24 +00001655 // Use visitSwitchCase to actually insert the fast branch sequence for this
1656 // cond branch.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001657 visitSwitchCase(CB, BrMBB);
Dan Gohman575fad32008-09-03 16:12:24 +00001658}
1659
1660/// visitSwitchCase - Emits the necessary code to represent a single node in
1661/// the binary search tree resulting from lowering a switch instruction.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001662void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1663 MachineBasicBlock *SwitchBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00001664 SDValue Cond;
1665 SDValue CondLHS = getValue(CB.CmpLHS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001666 SDLoc dl = getCurSDLoc();
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001667
1668 // Build the setcc now.
Craig Topperc0196b12014-04-14 00:51:57 +00001669 if (!CB.CmpMHS) {
Dan Gohman575fad32008-09-03 16:12:24 +00001670 // Fold "(X == true)" to X and "(X == false)" to !X to
1671 // handle common cases produced by branch lowering.
Owen Anderson23a204d2009-07-31 17:39:07 +00001672 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
Owen Anderson2ad52172009-07-21 02:47:59 +00001673 CB.CC == ISD::SETEQ)
Dan Gohman575fad32008-09-03 16:12:24 +00001674 Cond = CondLHS;
Owen Anderson23a204d2009-07-31 17:39:07 +00001675 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
Owen Anderson2ad52172009-07-21 02:47:59 +00001676 CB.CC == ISD::SETEQ) {
Dan Gohman575fad32008-09-03 16:12:24 +00001677 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf2bb6f02009-02-04 01:48:28 +00001678 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohman575fad32008-09-03 16:12:24 +00001679 } else
Owen Anderson9f944592009-08-11 20:47:22 +00001680 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohman575fad32008-09-03 16:12:24 +00001681 } else {
Bob Wilsone4077362013-09-09 19:14:35 +00001682 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Dan Gohman575fad32008-09-03 16:12:24 +00001683
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001684 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1685 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohman575fad32008-09-03 16:12:24 +00001686
1687 SDValue CmpOp = getValue(CB.CmpMHS);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001688 EVT VT = CmpOp.getValueType();
Stephen Lincfe7f352013-07-08 00:37:03 +00001689
Bob Wilsone4077362013-09-09 19:14:35 +00001690 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Owen Anderson9f944592009-08-11 20:47:22 +00001691 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Bob Wilsone4077362013-09-09 19:14:35 +00001692 ISD::SETLE);
Dan Gohman575fad32008-09-03 16:12:24 +00001693 } else {
Dale Johannesenf2bb6f02009-02-04 01:48:28 +00001694 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesened255b32009-01-30 01:34:22 +00001695 VT, CmpOp, DAG.getConstant(Low, VT));
Owen Anderson9f944592009-08-11 20:47:22 +00001696 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohman575fad32008-09-03 16:12:24 +00001697 DAG.getConstant(High-Low, VT), ISD::SETULE);
1698 }
1699 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001700
Dan Gohman575fad32008-09-03 16:12:24 +00001701 // Update successor info
Jakub Staszak0480a8f2011-07-29 22:25:21 +00001702 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
Jakob Stoklund Olesen7d33c572012-08-20 21:39:52 +00001703 // TrueBB and FalseBB are always different unless the incoming IR is
1704 // degenerate. This only happens when running llc on weird IR.
1705 if (CB.TrueBB != CB.FalseBB)
1706 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001707
Dan Gohman575fad32008-09-03 16:12:24 +00001708 // Set NextBlock to be the MBB immediately after the current one, if any.
1709 // This is used to avoid emitting unnecessary branches to the next block.
Craig Topperc0196b12014-04-14 00:51:57 +00001710 MachineBasicBlock *NextBlock = nullptr;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001711 MachineFunction::iterator BBI = SwitchBB;
Dan Gohmane8c913e2009-08-15 02:06:22 +00001712 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00001713 NextBlock = BBI;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001714
Dan Gohman575fad32008-09-03 16:12:24 +00001715 // If the lhs block is the next block, invert the condition so that we can
1716 // fall through to the lhs instead of the rhs block.
1717 if (CB.TrueBB == NextBlock) {
1718 std::swap(CB.TrueBB, CB.FalseBB);
1719 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf2bb6f02009-02-04 01:48:28 +00001720 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohman575fad32008-09-03 16:12:24 +00001721 }
Bill Wendling7f5eb532009-12-21 19:59:38 +00001722
Dale Johannesenf2bb6f02009-02-04 01:48:28 +00001723 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Owen Anderson9f944592009-08-11 20:47:22 +00001724 MVT::Other, getControlRoot(), Cond,
Dale Johannesened255b32009-01-30 01:34:22 +00001725 DAG.getBasicBlock(CB.TrueBB));
Bill Wendlingc6b47342009-12-21 23:47:40 +00001726
Evan Cheng79687dd2010-09-23 06:51:55 +00001727 // Insert the false branch. Do this even if it's a fall through branch,
1728 // this makes it easier to do DAG optimizations which require inverting
1729 // the branch condition.
1730 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1731 DAG.getBasicBlock(CB.FalseBB));
Bill Wendling7f5eb532009-12-21 19:59:38 +00001732
1733 DAG.setRoot(BrCond);
Dan Gohman575fad32008-09-03 16:12:24 +00001734}
1735
1736/// visitJumpTable - Emit JumpTable node in the current MBB
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001737void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
Dan Gohman575fad32008-09-03 16:12:24 +00001738 // Emit the code for the jump table
1739 assert(JT.Reg != -1U && "Should lower JT Header first!");
Eric Christopher58a24612014-10-08 09:50:54 +00001740 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001741 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
Dale Johannesen3a09f552009-02-03 23:04:43 +00001742 JT.Reg, PTy);
Dan Gohman575fad32008-09-03 16:12:24 +00001743 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001744 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
Bill Wendling7f5eb532009-12-21 19:59:38 +00001745 MVT::Other, Index.getValue(1),
1746 Table, Index);
1747 DAG.setRoot(BrJumpTable);
Dan Gohman575fad32008-09-03 16:12:24 +00001748}
1749
1750/// visitJumpTableHeader - This function emits necessary code to produce index
1751/// in the JumpTable from switch case.
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001752void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
Dan Gohman7c0303a2010-04-19 22:41:47 +00001753 JumpTableHeader &JTH,
1754 MachineBasicBlock *SwitchBB) {
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001755 // Subtract the lowest switch case value from the value being switched on and
1756 // conditional branch to default mbb if the result is greater than the
Dan Gohman575fad32008-09-03 16:12:24 +00001757 // difference between smallest and largest cases.
1758 SDValue SwitchOp = getValue(JTH.SValue);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001759 EVT VT = SwitchOp.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001760 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001761 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001762
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001763 // The SDNode we just created, which holds the value being switched on minus
Dan Gohman4a618822010-02-10 16:03:48 +00001764 // the smallest case value, needs to be copied to a virtual register so it
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001765 // can be used as an index into the jump table in a subsequent basic block.
1766 // This value may be smaller or larger than the target's pointer type, and
1767 // therefore require extension or truncating.
Eric Christopher58a24612014-10-08 09:50:54 +00001768 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1769 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI.getPointerTy());
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001770
Eric Christopher58a24612014-10-08 09:50:54 +00001771 unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001772 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
Dale Johannesen3a09f552009-02-03 23:04:43 +00001773 JumpTableReg, SwitchOp);
Dan Gohman575fad32008-09-03 16:12:24 +00001774 JT.Reg = JumpTableReg;
1775
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001776 // Emit the range check for the jump table, and branch to the default block
1777 // for the switch statement if the value being switched on exceeds the largest
1778 // case in the switch.
Eric Christopher58a24612014-10-08 09:50:54 +00001779 SDValue CMP =
1780 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1781 Sub.getValueType()),
1782 Sub, DAG.getConstant(JTH.Last - JTH.First, VT), ISD::SETUGT);
Dan Gohman575fad32008-09-03 16:12:24 +00001783
1784 // Set NextBlock to be the MBB immediately after the current one, if any.
1785 // This is used to avoid emitting unnecessary branches to the next block.
Craig Topperc0196b12014-04-14 00:51:57 +00001786 MachineBasicBlock *NextBlock = nullptr;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001787 MachineFunction::iterator BBI = SwitchBB;
Bill Wendlingc6b47342009-12-21 23:47:40 +00001788
Dan Gohmane8c913e2009-08-15 02:06:22 +00001789 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00001790 NextBlock = BBI;
1791
Andrew Trickef9de2a2013-05-25 02:42:55 +00001792 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
Owen Anderson9f944592009-08-11 20:47:22 +00001793 MVT::Other, CopyTo, CMP,
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001794 DAG.getBasicBlock(JT.Default));
Dan Gohman575fad32008-09-03 16:12:24 +00001795
Bill Wendling954cb182010-01-28 21:51:40 +00001796 if (JT.MBB != NextBlock)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001797 BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
Bill Wendling7f5eb532009-12-21 19:59:38 +00001798 DAG.getBasicBlock(JT.MBB));
Bill Wendling7f5eb532009-12-21 19:59:38 +00001799
Bill Wendlingc6b47342009-12-21 23:47:40 +00001800 DAG.setRoot(BrCond);
Dan Gohman575fad32008-09-03 16:12:24 +00001801}
1802
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00001803/// Codegen a new tail for a stack protector check ParentMBB which has had its
1804/// tail spliced into a stack protector check success bb.
1805///
1806/// For a high level explanation of how this fits into the stack protector
1807/// generation see the comment on the declaration of class
1808/// StackProtectorDescriptor.
1809void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1810 MachineBasicBlock *ParentBB) {
1811
1812 // First create the loads to the guard/stack slot for the comparison.
Eric Christopher58a24612014-10-08 09:50:54 +00001813 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1814 EVT PtrTy = TLI.getPointerTy();
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00001815
1816 MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1817 int FI = MFI->getStackProtectorIndex();
1818
1819 const Value *IRGuard = SPD.getGuard();
1820 SDValue GuardPtr = getValue(IRGuard);
1821 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1822
1823 unsigned Align =
Eric Christopher58a24612014-10-08 09:50:54 +00001824 TLI.getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00001825
1826 SDValue Guard;
1827
Akira Hatanaka5acc58f2014-08-07 23:08:24 +00001828 // If GuardReg is set and useLoadStackGuardNode returns true, retrieve the
1829 // guard value from the virtual register holding the value. Otherwise, emit a
1830 // volatile load to retrieve the stack guard value.
1831 unsigned GuardReg = SPD.getGuardReg();
1832
Eric Christopher58a24612014-10-08 09:50:54 +00001833 if (GuardReg && TLI.useLoadStackGuardNode())
Akira Hatanaka5acc58f2014-08-07 23:08:24 +00001834 Guard = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), GuardReg,
1835 PtrTy);
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00001836 else
1837 Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1838 GuardPtr, MachinePointerInfo(IRGuard, 0),
1839 true, false, false, Align);
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00001840
1841 SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1842 StackSlotPtr,
1843 MachinePointerInfo::getFixedStack(FI),
1844 true, false, false, Align);
1845
1846 // Perform the comparison via a subtract/getsetcc.
1847 EVT VT = Guard.getValueType();
1848 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
1849
Eric Christopher58a24612014-10-08 09:50:54 +00001850 SDValue Cmp =
1851 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1852 Sub.getValueType()),
1853 Sub, DAG.getConstant(0, VT), ISD::SETNE);
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00001854
1855 // If the sub is not 0, then we know the guard/stackslot do not equal, so
1856 // branch to failure MBB.
1857 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1858 MVT::Other, StackSlot.getOperand(0),
1859 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1860 // Otherwise branch to success MBB.
1861 SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
1862 MVT::Other, BrCond,
1863 DAG.getBasicBlock(SPD.getSuccessMBB()));
1864
1865 DAG.setRoot(Br);
1866}
1867
1868/// Codegen the failure basic block for a stack protector check.
1869///
1870/// A failure stack protector machine basic block consists simply of a call to
1871/// __stack_chk_fail().
1872///
1873/// For a high level explanation of how this fits into the stack protector
1874/// generation see the comment on the declaration of class
1875/// StackProtectorDescriptor.
1876void
1877SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
Eric Christopher58a24612014-10-08 09:50:54 +00001878 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1879 SDValue Chain =
1880 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
1881 nullptr, 0, false, getCurSDLoc(), false, false).second;
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00001882 DAG.setRoot(Chain);
1883}
1884
Dan Gohman575fad32008-09-03 16:12:24 +00001885/// visitBitTestHeader - This function emits necessary code to produce value
1886/// suitable for "bit tests"
Dan Gohman7c0303a2010-04-19 22:41:47 +00001887void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1888 MachineBasicBlock *SwitchBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00001889 // Subtract the minimum value
1890 SDValue SwitchOp = getValue(B.SValue);
Patrik Hagglunde98b7a02012-12-11 11:14:33 +00001891 EVT VT = SwitchOp.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001892 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001893 DAG.getConstant(B.First, VT));
Dan Gohman575fad32008-09-03 16:12:24 +00001894
1895 // Check range
Eric Christopher58a24612014-10-08 09:50:54 +00001896 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1897 SDValue RangeCmp =
1898 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
Matt Arsenault758659232013-05-18 00:21:46 +00001899 Sub.getValueType()),
Eric Christopher58a24612014-10-08 09:50:54 +00001900 Sub, DAG.getConstant(B.Range, VT), ISD::SETUGT);
Dan Gohman575fad32008-09-03 16:12:24 +00001901
Evan Chengac730dd2011-01-06 01:02:44 +00001902 // Determine the type of the test operands.
1903 bool UsePtrType = false;
Eric Christopher58a24612014-10-08 09:50:54 +00001904 if (!TLI.isTypeLegal(VT))
Evan Chengac730dd2011-01-06 01:02:44 +00001905 UsePtrType = true;
1906 else {
1907 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
Eli Friedman979009e2011-10-12 22:46:45 +00001908 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
Evan Chengac730dd2011-01-06 01:02:44 +00001909 // Switch table case range are encoded into series of masks.
1910 // Just use pointer type, it's guaranteed to fit.
1911 UsePtrType = true;
1912 break;
1913 }
1914 }
1915 if (UsePtrType) {
Eric Christopher58a24612014-10-08 09:50:54 +00001916 VT = TLI.getPointerTy();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001917 Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
Evan Chengac730dd2011-01-06 01:02:44 +00001918 }
Dan Gohman575fad32008-09-03 16:12:24 +00001919
Patrik Hagglund5e6c3612012-12-13 06:34:11 +00001920 B.RegVT = VT.getSimpleVT();
Patrik Hagglund4e0f8282012-12-19 12:23:01 +00001921 B.Reg = FuncInfo.CreateReg(B.RegVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001922 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
Evan Chengac730dd2011-01-06 01:02:44 +00001923 B.Reg, Sub);
Dan Gohman575fad32008-09-03 16:12:24 +00001924
1925 // Set NextBlock to be the MBB immediately after the current one, if any.
1926 // This is used to avoid emitting unnecessary branches to the next block.
Craig Topperc0196b12014-04-14 00:51:57 +00001927 MachineBasicBlock *NextBlock = nullptr;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001928 MachineFunction::iterator BBI = SwitchBB;
Dan Gohmane8c913e2009-08-15 02:06:22 +00001929 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00001930 NextBlock = BBI;
1931
1932 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1933
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001934 addSuccessorWithWeight(SwitchBB, B.Default);
1935 addSuccessorWithWeight(SwitchBB, MBB);
Dan Gohman575fad32008-09-03 16:12:24 +00001936
Andrew Trickef9de2a2013-05-25 02:42:55 +00001937 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
Owen Anderson9f944592009-08-11 20:47:22 +00001938 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001939 DAG.getBasicBlock(B.Default));
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001940
Evan Cheng6b8b2b72010-09-23 18:32:19 +00001941 if (MBB != NextBlock)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001942 BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
Evan Cheng6b8b2b72010-09-23 18:32:19 +00001943 DAG.getBasicBlock(MBB));
Bill Wendling7f5eb532009-12-21 19:59:38 +00001944
Bill Wendlingc6b47342009-12-21 23:47:40 +00001945 DAG.setRoot(BrRange);
Dan Gohman575fad32008-09-03 16:12:24 +00001946}
1947
1948/// visitBitTestCase - this function produces one "bit test"
Evan Chengac730dd2011-01-06 01:02:44 +00001949void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1950 MachineBasicBlock* NextMBB,
Manman Rencf104462012-08-24 18:14:27 +00001951 uint32_t BranchWeightToNext,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001952 unsigned Reg,
Dan Gohman7c0303a2010-04-19 22:41:47 +00001953 BitTestCase &B,
1954 MachineBasicBlock *SwitchBB) {
Patrik Hagglund4e0f8282012-12-19 12:23:01 +00001955 MVT VT = BB.RegVT;
Andrew Trickef9de2a2013-05-25 02:42:55 +00001956 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
Evan Chengac730dd2011-01-06 01:02:44 +00001957 Reg, VT);
Dan Gohman0695e092010-06-24 02:06:24 +00001958 SDValue Cmp;
Benjamin Kramer5f6a9072015-02-12 15:35:40 +00001959 unsigned PopCount = countPopulation(B.Mask);
Eric Christopher58a24612014-10-08 09:50:54 +00001960 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Benjamin Kramer15cd5a32011-07-14 01:38:42 +00001961 if (PopCount == 1) {
Dan Gohman0695e092010-06-24 02:06:24 +00001962 // Testing for a single bit; just compare the shift count with what it
1963 // would need to be to shift a 1 bit in that position.
Eric Christopher58a24612014-10-08 09:50:54 +00001964 Cmp = DAG.getSetCC(
1965 getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1966 DAG.getConstant(countTrailingZeros(B.Mask), VT), ISD::SETEQ);
Benjamin Kramer15cd5a32011-07-14 01:38:42 +00001967 } else if (PopCount == BB.Range) {
1968 // There is only one zero bit in the range, test for it directly.
Eric Christopher58a24612014-10-08 09:50:54 +00001969 Cmp = DAG.getSetCC(
1970 getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
Benjamin Kramer5f6a9072015-02-12 15:35:40 +00001971 DAG.getConstant(countTrailingOnes(B.Mask), VT), ISD::SETNE);
Dan Gohman0695e092010-06-24 02:06:24 +00001972 } else {
1973 // Make desired shift
Andrew Trickef9de2a2013-05-25 02:42:55 +00001974 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
Evan Chengac730dd2011-01-06 01:02:44 +00001975 DAG.getConstant(1, VT), ShiftOp);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001976
Dan Gohman0695e092010-06-24 02:06:24 +00001977 // Emit bit tests and jumps
Andrew Trickef9de2a2013-05-25 02:42:55 +00001978 SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
Evan Chengac730dd2011-01-06 01:02:44 +00001979 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001980 Cmp = DAG.getSetCC(getCurSDLoc(),
Eric Christopher58a24612014-10-08 09:50:54 +00001981 TLI.getSetCCResultType(*DAG.getContext(), VT), AndOp,
1982 DAG.getConstant(0, VT), ISD::SETNE);
Dan Gohman0695e092010-06-24 02:06:24 +00001983 }
Dan Gohman575fad32008-09-03 16:12:24 +00001984
Manman Rencf104462012-08-24 18:14:27 +00001985 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
1986 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
1987 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
1988 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001989
Andrew Trickef9de2a2013-05-25 02:42:55 +00001990 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
Owen Anderson9f944592009-08-11 20:47:22 +00001991 MVT::Other, getControlRoot(),
Dan Gohman0695e092010-06-24 02:06:24 +00001992 Cmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohman575fad32008-09-03 16:12:24 +00001993
1994 // Set NextBlock to be the MBB immediately after the current one, if any.
1995 // This is used to avoid emitting unnecessary branches to the next block.
Craig Topperc0196b12014-04-14 00:51:57 +00001996 MachineBasicBlock *NextBlock = nullptr;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001997 MachineFunction::iterator BBI = SwitchBB;
Dan Gohmane8c913e2009-08-15 02:06:22 +00001998 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00001999 NextBlock = BBI;
2000
Evan Cheng6b8b2b72010-09-23 18:32:19 +00002001 if (NextMBB != NextBlock)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002002 BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
Evan Cheng6b8b2b72010-09-23 18:32:19 +00002003 DAG.getBasicBlock(NextMBB));
Bill Wendling28727f32009-12-21 21:59:52 +00002004
Bill Wendlingc6b47342009-12-21 23:47:40 +00002005 DAG.setRoot(BrAnd);
Dan Gohman575fad32008-09-03 16:12:24 +00002006}
2007
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002008void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +00002009 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
Dan Gohman7c0303a2010-04-19 22:41:47 +00002010
Dan Gohman575fad32008-09-03 16:12:24 +00002011 // Retrieve successors.
2012 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2013 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
2014
Gabor Greif08a4c282009-01-15 11:10:44 +00002015 const Value *Callee(I.getCalledValue());
Nuno Lopesec9653b2012-06-28 22:30:12 +00002016 const Function *Fn = dyn_cast<Function>(Callee);
Gabor Greif08a4c282009-01-15 11:10:44 +00002017 if (isa<InlineAsm>(Callee))
Dan Gohman575fad32008-09-03 16:12:24 +00002018 visitInlineAsm(&I);
Nuno Lopesec9653b2012-06-28 22:30:12 +00002019 else if (Fn && Fn->isIntrinsic()) {
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00002020 switch (Fn->getIntrinsicID()) {
2021 default:
2022 llvm_unreachable("Cannot invoke this intrinsic");
2023 case Intrinsic::donothing:
2024 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2025 break;
2026 case Intrinsic::experimental_patchpoint_void:
2027 case Intrinsic::experimental_patchpoint_i64:
2028 visitPatchpoint(&I, LandingPad);
2029 break;
2030 }
Nuno Lopesec9653b2012-06-28 22:30:12 +00002031 } else
Gabor Greif08a4c282009-01-15 11:10:44 +00002032 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohman575fad32008-09-03 16:12:24 +00002033
2034 // If the value of the invoke is used outside of its defining block, make it
2035 // available as a virtual register.
Igor Laevsky8d0851f2015-03-05 15:41:14 +00002036 CopyToExportRegsIfNeeded(&I);
Dan Gohman575fad32008-09-03 16:12:24 +00002037
2038 // Update successor info
Chandler Carruthe2530dc2011-11-22 11:37:46 +00002039 addSuccessorWithWeight(InvokeMBB, Return);
2040 addSuccessorWithWeight(InvokeMBB, LandingPad);
Dan Gohman575fad32008-09-03 16:12:24 +00002041
2042 // Drop into normal successor.
Andrew Trickef9de2a2013-05-25 02:42:55 +00002043 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00002044 MVT::Other, getControlRoot(),
2045 DAG.getBasicBlock(Return)));
Dan Gohman575fad32008-09-03 16:12:24 +00002046}
2047
Bill Wendlingf891bf82011-07-31 06:30:59 +00002048void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2049 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2050}
2051
Bill Wendling247fd3b2011-08-17 21:56:44 +00002052void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2053 assert(FuncInfo.MBB->isLandingPad() &&
2054 "Call to landingpad not in landing pad!");
2055
2056 MachineBasicBlock *MBB = FuncInfo.MBB;
2057 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
2058 AddLandingPadInfo(LP, MMI, MBB);
2059
Bill Wendling05d6f2f2012-02-13 23:47:16 +00002060 // If there aren't registers to copy the values into (e.g., during SjLj
2061 // exceptions), then don't bother to create these DAG nodes.
Eric Christopher58a24612014-10-08 09:50:54 +00002062 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2063 if (TLI.getExceptionPointerRegister() == 0 &&
2064 TLI.getExceptionSelectorRegister() == 0)
Bill Wendling05d6f2f2012-02-13 23:47:16 +00002065 return;
2066
Bill Wendling247fd3b2011-08-17 21:56:44 +00002067 SmallVector<EVT, 2> ValueVTs;
Eric Christopher58a24612014-10-08 09:50:54 +00002068 ComputeValueVTs(TLI, LP.getType(), ValueVTs);
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002069 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
Bill Wendling247fd3b2011-08-17 21:56:44 +00002070
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002071 // Get the two live-in registers as SDValues. The physregs have already been
2072 // copied into virtual registers.
Bill Wendling247fd3b2011-08-17 21:56:44 +00002073 SDValue Ops[2];
Reid Kleckner0a57f652015-01-14 01:05:27 +00002074 if (FuncInfo.ExceptionPointerVirtReg) {
2075 Ops[0] = DAG.getZExtOrTrunc(
2076 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2077 FuncInfo.ExceptionPointerVirtReg, TLI.getPointerTy()),
2078 getCurSDLoc(), ValueVTs[0]);
2079 } else {
2080 Ops[0] = DAG.getConstant(0, TLI.getPointerTy());
2081 }
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002082 Ops[1] = DAG.getZExtOrTrunc(
Eric Christopher58a24612014-10-08 09:50:54 +00002083 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2084 FuncInfo.ExceptionSelectorVirtReg, TLI.getPointerTy()),
2085 getCurSDLoc(), ValueVTs[1]);
Bill Wendling247fd3b2011-08-17 21:56:44 +00002086
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002087 // Merge into one.
Andrew Trickef9de2a2013-05-25 02:42:55 +00002088 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00002089 DAG.getVTList(ValueVTs), Ops);
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002090 setValue(&LP, Res);
Bill Wendling247fd3b2011-08-17 21:56:44 +00002091}
2092
Reid Kleckner0a57f652015-01-14 01:05:27 +00002093unsigned
2094SelectionDAGBuilder::visitLandingPadClauseBB(GlobalValue *ClauseGV,
2095 MachineBasicBlock *LPadBB) {
2096 SDValue Chain = getControlRoot();
2097
2098 // Get the typeid that we will dispatch on later.
2099 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2100 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy());
2101 unsigned VReg = FuncInfo.MF->getRegInfo().createVirtualRegister(RC);
2102 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(ClauseGV);
2103 SDValue Sel = DAG.getConstant(TypeID, TLI.getPointerTy());
2104 Chain = DAG.getCopyToReg(Chain, getCurSDLoc(), VReg, Sel);
2105
2106 // Branch to the main landing pad block.
2107 MachineBasicBlock *ClauseMBB = FuncInfo.MBB;
2108 ClauseMBB->addSuccessor(LPadBB);
2109 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, Chain,
2110 DAG.getBasicBlock(LPadBB)));
2111 return VReg;
2112}
2113
Dan Gohman575fad32008-09-03 16:12:24 +00002114/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
2115/// small case ranges).
Dan Gohman1a6c47f2009-11-23 18:04:58 +00002116bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
2117 CaseRecVector& WorkList,
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002118 const Value* SV,
Dan Gohman7c0303a2010-04-19 22:41:47 +00002119 MachineBasicBlock *Default,
2120 MachineBasicBlock *SwitchBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00002121 // Size is the number of Cases represented by this range.
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002122 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohman575fad32008-09-03 16:12:24 +00002123 if (Size > 3)
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002124 return false;
2125
Dan Gohman575fad32008-09-03 16:12:24 +00002126 // Get the MachineFunction which holds the current MBB. This is used when
2127 // inserting any additional MBBs necessary to represent the switch.
Dan Gohmane8c913e2009-08-15 02:06:22 +00002128 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohman575fad32008-09-03 16:12:24 +00002129
2130 // Figure out which block is immediately after the current one.
Craig Topperc0196b12014-04-14 00:51:57 +00002131 MachineBasicBlock *NextBlock = nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00002132 MachineFunction::iterator BBI = CR.CaseBB;
2133
Dan Gohmane8c913e2009-08-15 02:06:22 +00002134 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00002135 NextBlock = BBI;
2136
Manman Rencf104462012-08-24 18:14:27 +00002137 BranchProbabilityInfo *BPI = FuncInfo.BPI;
Benjamin Kramer24656c92010-11-22 09:45:38 +00002138 // If any two of the cases has the same destination, and if one value
Dan Gohman575fad32008-09-03 16:12:24 +00002139 // is the same as the other, but has one bit unset that the other has set,
2140 // use bit manipulation to do two compares at once. For example:
2141 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Benjamin Kramer24656c92010-11-22 09:45:38 +00002142 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
2143 // TODO: Handle cases where CR.CaseBB != SwitchBB.
2144 if (Size == 2 && CR.CaseBB == SwitchBB) {
2145 Case &Small = *CR.Range.first;
2146 Case &Big = *(CR.Range.second-1);
2147
2148 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
2149 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
2150 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
2151
2152 // Check that there is only one bit different.
2153 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
2154 (SmallValue | BigValue) == BigValue) {
2155 // Isolate the common bit.
2156 APInt CommonBit = BigValue & ~SmallValue;
2157 assert((SmallValue | CommonBit) == BigValue &&
2158 CommonBit.countPopulation() == 1 && "Not a common bit?");
2159
2160 SDValue CondLHS = getValue(SV);
2161 EVT VT = CondLHS.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002162 SDLoc DL = getCurSDLoc();
Benjamin Kramer24656c92010-11-22 09:45:38 +00002163
2164 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
2165 DAG.getConstant(CommonBit, VT));
2166 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
2167 Or, DAG.getConstant(BigValue, VT),
2168 ISD::SETEQ);
2169
2170 // Update successor info.
Manman Rencf104462012-08-24 18:14:27 +00002171 // Both Small and Big will jump to Small.BB, so we sum up the weights.
2172 addSuccessorWithWeight(SwitchBB, Small.BB,
2173 Small.ExtraWeight + Big.ExtraWeight);
2174 addSuccessorWithWeight(SwitchBB, Default,
2175 // The default destination is the first successor in IR.
2176 BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
Benjamin Kramer24656c92010-11-22 09:45:38 +00002177
2178 // Insert the true branch.
2179 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
2180 getControlRoot(), Cond,
2181 DAG.getBasicBlock(Small.BB));
2182
2183 // Insert the false branch.
2184 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
2185 DAG.getBasicBlock(Default));
2186
2187 DAG.setRoot(BrCond);
2188 return true;
2189 }
2190 }
2191 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002192
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002193 // Order cases by weight so the most likely case will be checked first.
Manman Rencf104462012-08-24 18:14:27 +00002194 uint32_t UnhandledWeights = 0;
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002195 if (BPI) {
2196 for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
Manman Rencf104462012-08-24 18:14:27 +00002197 uint32_t IWeight = I->ExtraWeight;
2198 UnhandledWeights += IWeight;
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002199 for (CaseItr J = CR.Range.first; J < I; ++J) {
Manman Rencf104462012-08-24 18:14:27 +00002200 uint32_t JWeight = J->ExtraWeight;
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002201 if (IWeight > JWeight)
2202 std::swap(*I, *J);
2203 }
2204 }
2205 }
Dan Gohman575fad32008-09-03 16:12:24 +00002206 // Rearrange the case blocks so that the last one falls through if possible.
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002207 Case &BackCase = *(CR.Range.second-1);
Benjamin Kramer5aad8722012-05-26 21:19:12 +00002208 if (Size > 1 &&
2209 NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Dan Gohman575fad32008-09-03 16:12:24 +00002210 // The last case block won't fall through into 'NextBlock' if we emit the
2211 // branches in this order. See if rearranging a case value would help.
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002212 // We start at the bottom as it's the case with the least weight.
Stephen Lin6d715e82013-07-06 21:44:25 +00002213 for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
Dan Gohman575fad32008-09-03 16:12:24 +00002214 if (I->BB == NextBlock) {
2215 std::swap(*I, BackCase);
2216 break;
2217 }
Dan Gohman575fad32008-09-03 16:12:24 +00002218 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002219
Dan Gohman575fad32008-09-03 16:12:24 +00002220 // Create a CaseBlock record representing a conditional branch to
2221 // the Case's target mbb if the value being switched on SV is equal
2222 // to C.
2223 MachineBasicBlock *CurBlock = CR.CaseBB;
2224 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2225 MachineBasicBlock *FallThrough;
2226 if (I != E-1) {
2227 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2228 CurMF->insert(BBI, FallThrough);
Dan Gohmane6db8ca2009-04-09 02:33:36 +00002229
2230 // Put SV in a virtual register to make it available from the new blocks.
2231 ExportFromCurrentBlock(SV);
Dan Gohman575fad32008-09-03 16:12:24 +00002232 } else {
2233 // If the last case doesn't match, go to the default block.
2234 FallThrough = Default;
2235 }
2236
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002237 const Value *RHS, *LHS, *MHS;
Dan Gohman575fad32008-09-03 16:12:24 +00002238 ISD::CondCode CC;
2239 if (I->High == I->Low) {
2240 // This is just small small case range :) containing exactly 1 case
2241 CC = ISD::SETEQ;
Craig Topperc0196b12014-04-14 00:51:57 +00002242 LHS = SV; RHS = I->High; MHS = nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00002243 } else {
Bob Wilsone4077362013-09-09 19:14:35 +00002244 CC = ISD::SETLE;
Dan Gohman575fad32008-09-03 16:12:24 +00002245 LHS = I->Low; MHS = SV; RHS = I->High;
2246 }
Jakub Staszak0480a8f2011-07-29 22:25:21 +00002247
Manman Rencf104462012-08-24 18:14:27 +00002248 // The false weight should be sum of all un-handled cases.
2249 UnhandledWeights -= I->ExtraWeight;
Jakub Staszak0480a8f2011-07-29 22:25:21 +00002250 CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
2251 /* me */ CurBlock,
Manman Rencf104462012-08-24 18:14:27 +00002252 /* trueweight */ I->ExtraWeight,
2253 /* falseweight */ UnhandledWeights);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002254
Dan Gohman575fad32008-09-03 16:12:24 +00002255 // If emitting the first comparison, just call visitSwitchCase to emit the
2256 // code into the current block. Otherwise, push the CaseBlock onto the
2257 // vector to be later processed by SDISel, and insert the node's MBB
2258 // before the next MBB.
Dan Gohman7c0303a2010-04-19 22:41:47 +00002259 if (CurBlock == SwitchBB)
2260 visitSwitchCase(CB, SwitchBB);
Dan Gohman575fad32008-09-03 16:12:24 +00002261 else
2262 SwitchCases.push_back(CB);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002263
Dan Gohman575fad32008-09-03 16:12:24 +00002264 CurBlock = FallThrough;
2265 }
2266
2267 return true;
2268}
2269
2270static inline bool areJTsAllowed(const TargetLowering &TLI) {
Eric Christopher79cc1e32014-09-02 22:28:02 +00002271 return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
2272 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
Dan Gohman575fad32008-09-03 16:12:24 +00002273}
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002274
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002275static APInt ComputeRange(const APInt &First, const APInt &Last) {
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002276 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
Bob Wilsone4077362013-09-09 19:14:35 +00002277 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002278 return (LastExt - FirstExt + 1ULL);
2279}
2280
Dan Gohman575fad32008-09-03 16:12:24 +00002281/// handleJTSwitchCase - Emit jumptable for current switch case range
Chris Lattnere74e0c82011-09-09 22:06:59 +00002282bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
2283 CaseRecVector &WorkList,
2284 const Value *SV,
2285 MachineBasicBlock *Default,
Dan Gohman7c0303a2010-04-19 22:41:47 +00002286 MachineBasicBlock *SwitchBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00002287 Case& FrontCase = *CR.Range.first;
2288 Case& BackCase = *(CR.Range.second-1);
2289
Chris Lattner8e1d7222009-11-07 07:50:34 +00002290 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2291 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohman575fad32008-09-03 16:12:24 +00002292
Chris Lattner8e1d7222009-11-07 07:50:34 +00002293 APInt TSize(First.getBitWidth(), 0);
Chris Lattnere74e0c82011-09-09 22:06:59 +00002294 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
Dan Gohman575fad32008-09-03 16:12:24 +00002295 TSize += I->size();
2296
Eric Christopher58a24612014-10-08 09:50:54 +00002297 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2298 if (!areJTsAllowed(TLI) || TSize.ult(TLI.getMinimumJumpTableEntries()))
Dan Gohman575fad32008-09-03 16:12:24 +00002299 return false;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002300
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002301 APInt Range = ComputeRange(First, Last);
Jakob Stoklund Olesene8261a22011-10-26 01:47:48 +00002302 // The density is TSize / Range. Require at least 40%.
2303 // It should not be possible for IntTSize to saturate for sane code, but make
2304 // sure we handle Range saturation correctly.
2305 uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
2306 uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
2307 if (IntTSize * 10 < IntRange * 4)
Dan Gohman575fad32008-09-03 16:12:24 +00002308 return false;
2309
David Greene5730f202010-01-05 01:24:57 +00002310 DEBUG(dbgs() << "Lowering jump table\n"
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002311 << "First entry: " << First << ". Last entry: " << Last << '\n'
Jakob Stoklund Olesene8261a22011-10-26 01:47:48 +00002312 << "Range: " << Range << ". Size: " << TSize << ".\n\n");
Dan Gohman575fad32008-09-03 16:12:24 +00002313
2314 // Get the MachineFunction which holds the current MBB. This is used when
2315 // inserting any additional MBBs necessary to represent the switch.
Dan Gohmane8c913e2009-08-15 02:06:22 +00002316 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohman575fad32008-09-03 16:12:24 +00002317
2318 // Figure out which block is immediately after the current one.
Dan Gohman575fad32008-09-03 16:12:24 +00002319 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands3ee3c172009-09-06 18:03:32 +00002320 ++BBI;
Dan Gohman575fad32008-09-03 16:12:24 +00002321
2322 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2323
2324 // Create a new basic block to hold the code for loading the address
2325 // of the jump table, and jumping to it. Update successor information;
2326 // we will either branch to the default case for the switch, or the jump
2327 // table.
2328 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2329 CurMF->insert(BBI, JumpTableBB);
Jakub Staszak12a43bd2011-06-16 20:22:37 +00002330
2331 addSuccessorWithWeight(CR.CaseBB, Default);
2332 addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002333
Dan Gohman575fad32008-09-03 16:12:24 +00002334 // Build a vector of destination BBs, corresponding to each target
2335 // of the jump table. If the value of the jump table slot corresponds to
2336 // a case statement, push the case's BB onto the vector, otherwise, push
2337 // the default BB.
2338 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002339 APInt TEI = First;
Dan Gohman575fad32008-09-03 16:12:24 +00002340 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Chris Lattnerb6db2c62010-01-25 23:26:13 +00002341 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
2342 const APInt &High = cast<ConstantInt>(I->High)->getValue();
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002343
Bob Wilsone4077362013-09-09 19:14:35 +00002344 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohman575fad32008-09-03 16:12:24 +00002345 DestBBs.push_back(I->BB);
2346 if (TEI==High)
2347 ++I;
2348 } else {
2349 DestBBs.push_back(Default);
2350 }
2351 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002352
Manman Rencf104462012-08-24 18:14:27 +00002353 // Calculate weight for each unique destination in CR.
2354 DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
2355 if (FuncInfo.BPI)
2356 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2357 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2358 DestWeights.find(I->BB);
Stephen Lincfe7f352013-07-08 00:37:03 +00002359 if (Itr != DestWeights.end())
Manman Rencf104462012-08-24 18:14:27 +00002360 Itr->second += I->ExtraWeight;
2361 else
2362 DestWeights[I->BB] = I->ExtraWeight;
2363 }
2364
Dan Gohman575fad32008-09-03 16:12:24 +00002365 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002366 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2367 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohman575fad32008-09-03 16:12:24 +00002368 E = DestBBs.end(); I != E; ++I) {
2369 if (!SuccsHandled[(*I)->getNumber()]) {
2370 SuccsHandled[(*I)->getNumber()] = true;
Manman Rencf104462012-08-24 18:14:27 +00002371 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2372 DestWeights.find(*I);
2373 addSuccessorWithWeight(JumpTableBB, *I,
2374 Itr != DestWeights.end() ? Itr->second : 0);
Dan Gohman575fad32008-09-03 16:12:24 +00002375 }
2376 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002377
Bob Wilson3c7cde42010-03-18 18:42:41 +00002378 // Create a jump table index for this jump table.
Eric Christopher58a24612014-10-08 09:50:54 +00002379 unsigned JTEncoding = TLI.getJumpTableEncoding();
Chris Lattnerb6db2c62010-01-25 23:26:13 +00002380 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
Bob Wilson3c7cde42010-03-18 18:42:41 +00002381 ->createJumpTableIndex(DestBBs);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002382
Dan Gohman575fad32008-09-03 16:12:24 +00002383 // Set the jump table information so that we can codegen it as a second
2384 // MachineBasicBlock
2385 JumpTable JT(-1U, JTI, JumpTableBB, Default);
Dan Gohman7c0303a2010-04-19 22:41:47 +00002386 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2387 if (CR.CaseBB == SwitchBB)
2388 visitJumpTableHeader(JT, JTH, SwitchBB);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002389
Dan Gohman575fad32008-09-03 16:12:24 +00002390 JTCases.push_back(JumpTableBlock(JTH, JT));
Dan Gohman575fad32008-09-03 16:12:24 +00002391 return true;
2392}
2393
2394/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2395/// 2 subtrees.
Dan Gohman1a6c47f2009-11-23 18:04:58 +00002396bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2397 CaseRecVector& WorkList,
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002398 const Value* SV,
Stephen Lin6d715e82013-07-06 21:44:25 +00002399 MachineBasicBlock* SwitchBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00002400 Case& FrontCase = *CR.Range.first;
2401 Case& BackCase = *(CR.Range.second-1);
Dan Gohman575fad32008-09-03 16:12:24 +00002402
2403 // Size is the number of Cases represented by this range.
2404 unsigned Size = CR.Range.second - CR.Range.first;
2405
Chris Lattner8e1d7222009-11-07 07:50:34 +00002406 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2407 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohman575fad32008-09-03 16:12:24 +00002408 double FMetric = 0;
2409 CaseItr Pivot = CR.Range.first + Size/2;
2410
2411 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2412 // (heuristically) allow us to emit JumpTable's later.
Chris Lattner8e1d7222009-11-07 07:50:34 +00002413 APInt TSize(First.getBitWidth(), 0);
Dan Gohman575fad32008-09-03 16:12:24 +00002414 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2415 I!=E; ++I)
2416 TSize += I->size();
2417
Chris Lattner8e1d7222009-11-07 07:50:34 +00002418 APInt LSize = FrontCase.size();
2419 APInt RSize = TSize-LSize;
David Greene5730f202010-01-05 01:24:57 +00002420 DEBUG(dbgs() << "Selecting best pivot: \n"
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002421 << "First: " << First << ", Last: " << Last <<'\n'
2422 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Daniel Jasper6b774552015-01-20 19:43:33 +00002423 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman575fad32008-09-03 16:12:24 +00002424 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2425 J!=E; ++I, ++J) {
Chris Lattner8e1d7222009-11-07 07:50:34 +00002426 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2427 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002428 APInt Range = ComputeRange(LEnd, RBegin);
Stepan Dyatkovskiye01e9862012-05-15 06:50:18 +00002429 assert((Range - 2ULL).isNonNegative() &&
2430 "Invalid case distance");
Chris Lattnercfe5aa62011-04-09 06:57:13 +00002431 // Use volatile double here to avoid excess precision issues on some hosts,
2432 // e.g. that use 80-bit X87 registers.
Daniel Jasper6b774552015-01-20 19:43:33 +00002433 // Only consider the density of sub-ranges that actually have sufficient
2434 // entries to be lowered as a jump table.
Chris Lattnercfe5aa62011-04-09 06:57:13 +00002435 volatile double LDensity =
Daniel Jasper6b774552015-01-20 19:43:33 +00002436 LSize.ult(TLI.getMinimumJumpTableEntries())
2437 ? 0.0
2438 : LSize.roundToDouble() / (LEnd - First + 1ULL).roundToDouble();
Chris Lattnercfe5aa62011-04-09 06:57:13 +00002439 volatile double RDensity =
Daniel Jasper6b774552015-01-20 19:43:33 +00002440 RSize.ult(TLI.getMinimumJumpTableEntries())
2441 ? 0.0
2442 : RSize.roundToDouble() / (Last - RBegin + 1ULL).roundToDouble();
Daniel Jasperd106b732015-01-20 08:57:44 +00002443 volatile double Metric = Range.logBase2() * (LDensity + RDensity);
Dan Gohman575fad32008-09-03 16:12:24 +00002444 // Should always split in some non-trivial place
David Greene5730f202010-01-05 01:24:57 +00002445 DEBUG(dbgs() <<"=>Step\n"
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002446 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2447 << "LDensity: " << LDensity
2448 << ", RDensity: " << RDensity << '\n'
2449 << "Metric: " << Metric << '\n');
Dan Gohman575fad32008-09-03 16:12:24 +00002450 if (FMetric < Metric) {
2451 Pivot = J;
2452 FMetric = Metric;
David Greene5730f202010-01-05 01:24:57 +00002453 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
Dan Gohman575fad32008-09-03 16:12:24 +00002454 }
2455
2456 LSize += J->size();
2457 RSize -= J->size();
2458 }
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002459
Daniel Jasper6b774552015-01-20 19:43:33 +00002460 if (FMetric == 0 || !areJTsAllowed(TLI))
Dan Gohman575fad32008-09-03 16:12:24 +00002461 Pivot = CR.Range.first + Size/2;
Daniel Jasperd106b732015-01-20 08:57:44 +00002462 splitSwitchCase(CR, Pivot, WorkList, SV, SwitchBB);
2463 return true;
2464}
2465
2466void SelectionDAGBuilder::splitSwitchCase(CaseRec &CR, CaseItr Pivot,
2467 CaseRecVector &WorkList,
2468 const Value *SV,
2469 MachineBasicBlock *SwitchBB) {
2470 // Get the MachineFunction which holds the current MBB. This is used when
2471 // inserting any additional MBBs necessary to represent the switch.
2472 MachineFunction *CurMF = FuncInfo.MF;
2473
2474 // Figure out which block is immediately after the current one.
2475 MachineFunction::iterator BBI = CR.CaseBB;
2476 ++BBI;
2477
2478 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002479
Dan Gohman575fad32008-09-03 16:12:24 +00002480 CaseRange LHSR(CR.Range.first, Pivot);
2481 CaseRange RHSR(Pivot, CR.Range.second);
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002482 const Constant *C = Pivot->Low;
Craig Topperc0196b12014-04-14 00:51:57 +00002483 MachineBasicBlock *FalseBB = nullptr, *TrueBB = nullptr;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002484
Dan Gohman575fad32008-09-03 16:12:24 +00002485 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00002486 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohman575fad32008-09-03 16:12:24 +00002487 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00002488 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohman575fad32008-09-03 16:12:24 +00002489 // Pivot's Value, then we can branch directly to the LHS's Target,
2490 // rather than creating a leaf node for it.
Daniel Jasperd106b732015-01-20 08:57:44 +00002491 if ((LHSR.second - LHSR.first) == 1 && LHSR.first->High == CR.GE &&
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002492 cast<ConstantInt>(C)->getValue() ==
Daniel Jasperd106b732015-01-20 08:57:44 +00002493 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohman575fad32008-09-03 16:12:24 +00002494 TrueBB = LHSR.first->BB;
2495 } else {
2496 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2497 CurMF->insert(BBI, TrueBB);
2498 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Dan Gohmane6db8ca2009-04-09 02:33:36 +00002499
2500 // Put SV in a virtual register to make it available from the new blocks.
2501 ExportFromCurrentBlock(SV);
Dan Gohman575fad32008-09-03 16:12:24 +00002502 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002503
Dan Gohman575fad32008-09-03 16:12:24 +00002504 // Similar to the optimization above, if the Value being switched on is
2505 // known to be less than the Constant CR.LT, and the current Case Value
2506 // is CR.LT - 1, then we can branch directly to the target block for
2507 // the current Case Value, rather than emitting a RHS leaf node for it.
2508 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002509 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
Daniel Jasperd106b732015-01-20 08:57:44 +00002510 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohman575fad32008-09-03 16:12:24 +00002511 FalseBB = RHSR.first->BB;
2512 } else {
2513 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2514 CurMF->insert(BBI, FalseBB);
Daniel Jasperd106b732015-01-20 08:57:44 +00002515 WorkList.push_back(CaseRec(FalseBB, CR.LT, C, RHSR));
Dan Gohmane6db8ca2009-04-09 02:33:36 +00002516
2517 // Put SV in a virtual register to make it available from the new blocks.
2518 ExportFromCurrentBlock(SV);
Dan Gohman575fad32008-09-03 16:12:24 +00002519 }
2520
2521 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00002522 // the LHS node if the value being switched on SV is less than C.
Dan Gohman575fad32008-09-03 16:12:24 +00002523 // Otherwise, branch to LHS.
Craig Topperc0196b12014-04-14 00:51:57 +00002524 CaseBlock CB(ISD::SETLT, SV, C, nullptr, TrueBB, FalseBB, CR.CaseBB);
Dan Gohman575fad32008-09-03 16:12:24 +00002525
Dan Gohman7c0303a2010-04-19 22:41:47 +00002526 if (CR.CaseBB == SwitchBB)
2527 visitSwitchCase(CB, SwitchBB);
Dan Gohman575fad32008-09-03 16:12:24 +00002528 else
2529 SwitchCases.push_back(CB);
Dan Gohman575fad32008-09-03 16:12:24 +00002530}
2531
2532/// handleBitTestsSwitchCase - if current case range has few destination and
2533/// range span less, than machine word bitwidth, encode case range into series
2534/// of masks and emit bit tests with these masks.
Dan Gohman1a6c47f2009-11-23 18:04:58 +00002535bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2536 CaseRecVector& WorkList,
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002537 const Value* SV,
Dan Gohman7c0303a2010-04-19 22:41:47 +00002538 MachineBasicBlock* Default,
Stephen Lin6d715e82013-07-06 21:44:25 +00002539 MachineBasicBlock* SwitchBB) {
Eric Christopher58a24612014-10-08 09:50:54 +00002540 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2541 EVT PTy = TLI.getPointerTy();
Owen Andersonc30530d2009-08-10 18:56:59 +00002542 unsigned IntPtrBits = PTy.getSizeInBits();
Dan Gohman575fad32008-09-03 16:12:24 +00002543
2544 Case& FrontCase = *CR.Range.first;
2545 Case& BackCase = *(CR.Range.second-1);
2546
2547 // Get the MachineFunction which holds the current MBB. This is used when
2548 // inserting any additional MBBs necessary to represent the switch.
Dan Gohmane8c913e2009-08-15 02:06:22 +00002549 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohman575fad32008-09-03 16:12:24 +00002550
Anton Korobeynikovc94dbf52009-05-08 18:51:34 +00002551 // If target does not have legal shift left, do not emit bit tests at all.
Eric Christopher58a24612014-10-08 09:50:54 +00002552 if (!TLI.isOperationLegal(ISD::SHL, PTy))
Anton Korobeynikovc94dbf52009-05-08 18:51:34 +00002553 return false;
2554
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002555 size_t numCmps = 0;
Hans Wennborg6dfb0412014-11-29 21:24:12 +00002556 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002557 // Single case counts one, case range - two.
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002558 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohman575fad32008-09-03 16:12:24 +00002559 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002560
Dan Gohman575fad32008-09-03 16:12:24 +00002561 // Count unique destinations
2562 SmallSet<MachineBasicBlock*, 4> Dests;
Hans Wennborg6dfb0412014-11-29 21:24:12 +00002563 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002564 Dests.insert(I->BB);
2565 if (Dests.size() > 3)
2566 // Don't bother the code below, if there are too much unique destinations
2567 return false;
2568 }
David Greene5730f202010-01-05 01:24:57 +00002569 DEBUG(dbgs() << "Total number of unique destinations: "
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00002570 << Dests.size() << '\n'
2571 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002572
Dan Gohman575fad32008-09-03 16:12:24 +00002573 // Compute span of values.
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002574 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2575 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002576 APInt cmpRange = maxValue - minValue;
2577
David Greene5730f202010-01-05 01:24:57 +00002578 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002579 << "Low bound: " << minValue << '\n'
2580 << "High bound: " << maxValue << '\n');
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002581
Dan Gohman4ce1fb12010-04-08 23:03:40 +00002582 if (cmpRange.uge(IntPtrBits) ||
Dan Gohman575fad32008-09-03 16:12:24 +00002583 (!(Dests.size() == 1 && numCmps >= 3) &&
2584 !(Dests.size() == 2 && numCmps >= 5) &&
2585 !(Dests.size() >= 3 && numCmps >= 6)))
2586 return false;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002587
David Greene5730f202010-01-05 01:24:57 +00002588 DEBUG(dbgs() << "Emitting bit tests\n");
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002589 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2590
Dan Gohman575fad32008-09-03 16:12:24 +00002591 // Optimize the case where all the case values fit in a
2592 // word without having to subtract minValue. In this case,
2593 // we can optimize away the subtraction.
Bob Wilsone4077362013-09-09 19:14:35 +00002594 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002595 cmpRange = maxValue;
Dan Gohman575fad32008-09-03 16:12:24 +00002596 } else {
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002597 lowBound = minValue;
Dan Gohman575fad32008-09-03 16:12:24 +00002598 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002599
Dan Gohman575fad32008-09-03 16:12:24 +00002600 CaseBitsVector CasesBits;
2601 unsigned i, count = 0;
2602
2603 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2604 MachineBasicBlock* Dest = I->BB;
2605 for (i = 0; i < count; ++i)
2606 if (Dest == CasesBits[i].BB)
2607 break;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002608
Dan Gohman575fad32008-09-03 16:12:24 +00002609 if (i == count) {
2610 assert((count < 3) && "Too much destinations to test!");
Manman Rencf104462012-08-24 18:14:27 +00002611 CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
Dan Gohman575fad32008-09-03 16:12:24 +00002612 count++;
2613 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002614
2615 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2616 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2617
2618 uint64_t lo = (lowValue - lowBound).getZExtValue();
2619 uint64_t hi = (highValue - lowBound).getZExtValue();
Manman Rencf104462012-08-24 18:14:27 +00002620 CasesBits[i].ExtraWeight += I->ExtraWeight;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002621
Dan Gohman575fad32008-09-03 16:12:24 +00002622 for (uint64_t j = lo; j <= hi; j++) {
2623 CasesBits[i].Mask |= 1ULL << j;
2624 CasesBits[i].Bits++;
2625 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002626
Dan Gohman575fad32008-09-03 16:12:24 +00002627 }
2628 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002629
Dan Gohman575fad32008-09-03 16:12:24 +00002630 BitTestInfo BTC;
2631
2632 // Figure out which block is immediately after the current one.
2633 MachineFunction::iterator BBI = CR.CaseBB;
2634 ++BBI;
2635
2636 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2637
David Greene5730f202010-01-05 01:24:57 +00002638 DEBUG(dbgs() << "Cases:\n");
Dan Gohman575fad32008-09-03 16:12:24 +00002639 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
David Greene5730f202010-01-05 01:24:57 +00002640 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002641 << ", Bits: " << CasesBits[i].Bits
2642 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohman575fad32008-09-03 16:12:24 +00002643
2644 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2645 CurMF->insert(BBI, CaseBB);
2646 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2647 CaseBB,
Manman Rencf104462012-08-24 18:14:27 +00002648 CasesBits[i].BB, CasesBits[i].ExtraWeight));
Dan Gohmane6db8ca2009-04-09 02:33:36 +00002649
2650 // Put SV in a virtual register to make it available from the new blocks.
2651 ExportFromCurrentBlock(SV);
Dan Gohman575fad32008-09-03 16:12:24 +00002652 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002653
2654 BitTestBlock BTB(lowBound, cmpRange, SV,
Evan Chengac730dd2011-01-06 01:02:44 +00002655 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +00002656 CR.CaseBB, Default, std::move(BTC));
Dan Gohman575fad32008-09-03 16:12:24 +00002657
Dan Gohman7c0303a2010-04-19 22:41:47 +00002658 if (CR.CaseBB == SwitchBB)
2659 visitBitTestHeader(BTB, SwitchBB);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002660
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +00002661 BitTestCases.push_back(std::move(BTB));
Dan Gohman575fad32008-09-03 16:12:24 +00002662
2663 return true;
2664}
2665
Dan Gohman575fad32008-09-03 16:12:24 +00002666/// Clusterify - Transform simple list of Cases into list of CaseRange's
Chad Rosierdf82a332014-10-13 19:46:39 +00002667void SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2668 const SwitchInst& SI) {
Manman Rencf104462012-08-24 18:14:27 +00002669 BranchProbabilityInfo *BPI = FuncInfo.BPI;
Hans Wennborg6dfb0412014-11-29 21:24:12 +00002670 // Start with "simple" cases.
2671 for (SwitchInst::ConstCaseIt i : SI.cases()) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002672 const BasicBlock *SuccBB = i.getCaseSuccessor();
Jakub Staszak0480a8f2011-07-29 22:25:21 +00002673 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
2674
Bob Wilsone4077362013-09-09 19:14:35 +00002675 uint32_t ExtraWeight =
2676 BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0;
2677
2678 Cases.push_back(Case(i.getCaseValue(), i.getCaseValue(),
2679 SMBB, ExtraWeight));
Dan Gohman575fad32008-09-03 16:12:24 +00002680 }
Bob Wilsone4077362013-09-09 19:14:35 +00002681 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Stephen Lincfe7f352013-07-08 00:37:03 +00002682
Bob Wilsone4077362013-09-09 19:14:35 +00002683 // Merge case into clusters
2684 if (Cases.size() >= 2)
2685 // Must recompute end() each iteration because it may be
2686 // invalidated by erase if we hold on to it
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002687 for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
Bob Wilsone4077362013-09-09 19:14:35 +00002688 J != Cases.end(); ) {
2689 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2690 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2691 MachineBasicBlock* nextBB = J->BB;
2692 MachineBasicBlock* currentBB = I->BB;
Stephen Lincfe7f352013-07-08 00:37:03 +00002693
Bob Wilsone4077362013-09-09 19:14:35 +00002694 // If the two neighboring cases go to the same destination, merge them
2695 // into a single case.
2696 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2697 I->High = J->High;
2698 I->ExtraWeight += J->ExtraWeight;
2699 J = Cases.erase(J);
2700 } else {
2701 I = J++;
2702 }
2703 }
Dan Gohman575fad32008-09-03 16:12:24 +00002704
Chad Rosierdf82a332014-10-13 19:46:39 +00002705 DEBUG({
2706 size_t numCmps = 0;
2707 for (auto &I : Cases)
2708 // A range counts double, since it requires two compares.
2709 numCmps += I.Low != I.High ? 2 : 1;
Dan Gohman575fad32008-09-03 16:12:24 +00002710
Chad Rosierdf82a332014-10-13 19:46:39 +00002711 dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2712 << ". Total compares: " << numCmps << '\n';
2713 });
Dan Gohman575fad32008-09-03 16:12:24 +00002714}
2715
Jakob Stoklund Olesen665aa6e2010-09-30 19:44:31 +00002716void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2717 MachineBasicBlock *Last) {
2718 // Update JTCases.
2719 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2720 if (JTCases[i].first.HeaderBB == First)
2721 JTCases[i].first.HeaderBB = Last;
2722
2723 // Update BitTestCases.
2724 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2725 if (BitTestCases[i].Parent == First)
2726 BitTestCases[i].Parent = Last;
2727}
2728
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002729void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +00002730 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
Dan Gohman7c0303a2010-04-19 22:41:47 +00002731
Dan Gohman575fad32008-09-03 16:12:24 +00002732 // Figure out which block is immediately after the current one.
Craig Topperc0196b12014-04-14 00:51:57 +00002733 MachineBasicBlock *NextBlock = nullptr;
Hans Wennborg6c42d1a2014-11-29 21:17:05 +00002734 if (SwitchMBB + 1 != FuncInfo.MF->end())
2735 NextBlock = SwitchMBB + 1;
2736
Hans Wennborg08de8332014-12-06 01:28:50 +00002737
2738 // Create a vector of Cases, sorted so that we can efficiently create a binary
2739 // search tree from them.
2740 CaseVector Cases;
2741 Clusterify(Cases, SI);
2742
2743 // Get the default destination MBB.
Dan Gohman575fad32008-09-03 16:12:24 +00002744 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2745
Hans Wennborg08de8332014-12-06 01:28:50 +00002746 if (isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()) &&
2747 !Cases.empty()) {
2748 // Replace an unreachable default destination with the most popular case
2749 // destination.
Hans Wennborg224cb822014-12-16 23:41:59 +00002750 DenseMap<const BasicBlock *, unsigned> Popularity;
2751 unsigned MaxPop = 0;
Hans Wennborg08de8332014-12-06 01:28:50 +00002752 const BasicBlock *MaxBB = nullptr;
2753 for (auto I : SI.cases()) {
2754 const BasicBlock *BB = I.getCaseSuccessor();
2755 if (++Popularity[BB] > MaxPop) {
2756 MaxPop = Popularity[BB];
2757 MaxBB = BB;
2758 }
2759 }
2760
2761 // Set new default.
2762 assert(MaxPop > 0);
2763 assert(MaxBB);
2764 Default = FuncInfo.MBBMap[MaxBB];
2765
2766 // Remove cases that were pointing to the destination that is now the default.
2767 Cases.erase(std::remove_if(Cases.begin(), Cases.end(),
2768 [&](const Case &C) { return C.BB == Default; }),
2769 Cases.end());
2770 }
2771
2772 // If there is only the default destination, go there directly.
2773 if (Cases.empty()) {
Dan Gohman575fad32008-09-03 16:12:24 +00002774 // Update machine-CFG edges.
Hans Wennborg6dfb0412014-11-29 21:24:12 +00002775 SwitchMBB->addSuccessor(Default);
Dan Gohman575fad32008-09-03 16:12:24 +00002776
2777 // If this is not a fall-through branch, emit the branch.
Hans Wennborg08de8332014-12-06 01:28:50 +00002778 if (Default != NextBlock) {
2779 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2780 getControlRoot(), DAG.getBasicBlock(Default)));
2781 }
Dan Gohman575fad32008-09-03 16:12:24 +00002782 return;
2783 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002784
Hans Wennborg08de8332014-12-06 01:28:50 +00002785 // Get the Value to be switched on.
Eli Friedman95031ed2011-09-29 20:21:17 +00002786 const Value *SV = SI.getCondition();
Dan Gohman575fad32008-09-03 16:12:24 +00002787
2788 // Push the initial CaseRec onto the worklist
2789 CaseRecVector WorkList;
Craig Topperc0196b12014-04-14 00:51:57 +00002790 WorkList.push_back(CaseRec(SwitchMBB,nullptr,nullptr,
Dan Gohman7c0303a2010-04-19 22:41:47 +00002791 CaseRange(Cases.begin(),Cases.end())));
Dan Gohman575fad32008-09-03 16:12:24 +00002792
2793 while (!WorkList.empty()) {
2794 // Grab a record representing a case range to process off the worklist
2795 CaseRec CR = WorkList.back();
2796 WorkList.pop_back();
2797
Dan Gohman7c0303a2010-04-19 22:41:47 +00002798 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohman575fad32008-09-03 16:12:24 +00002799 continue;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002800
Dan Gohman575fad32008-09-03 16:12:24 +00002801 // If the range has few cases (two or less) emit a series of specific
2802 // tests.
Dan Gohman7c0303a2010-04-19 22:41:47 +00002803 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohman575fad32008-09-03 16:12:24 +00002804 continue;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002805
Sebastian Popedb31fa2012-09-25 20:35:36 +00002806 // If the switch has more than N blocks, and is at least 40% dense, and the
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002807 // target supports indirect branches, then emit a jump table rather than
Dan Gohman575fad32008-09-03 16:12:24 +00002808 // lowering the switch to a binary tree of conditional branches.
Sebastian Popedb31fa2012-09-25 20:35:36 +00002809 // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
Dan Gohman7c0303a2010-04-19 22:41:47 +00002810 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohman575fad32008-09-03 16:12:24 +00002811 continue;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002812
Dan Gohman575fad32008-09-03 16:12:24 +00002813 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2814 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
Chad Rosierdf82a332014-10-13 19:46:39 +00002815 handleBTSplitSwitchCase(CR, WorkList, SV, SwitchMBB);
Dan Gohman575fad32008-09-03 16:12:24 +00002816 }
2817}
2818
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002819void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +00002820 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
Dan Gohman7c0303a2010-04-19 22:41:47 +00002821
Jakob Stoklund Olesen896428d2010-02-11 00:34:18 +00002822 // Update machine-CFG edges with unique successors.
Nadav Rotem33e034a2012-10-23 21:05:33 +00002823 SmallSet<BasicBlock*, 32> Done;
2824 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2825 BasicBlock *BB = I.getSuccessor(i);
David Blaikie70573dc2014-11-19 07:49:26 +00002826 bool Inserted = Done.insert(BB).second;
Nadav Rotem33e034a2012-10-23 21:05:33 +00002827 if (!Inserted)
2828 continue;
2829
2830 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
Jakub Staszak12a43bd2011-06-16 20:22:37 +00002831 addSuccessorWithWeight(IndirectBrMBB, Succ);
2832 }
Dan Gohmana5e078b2009-10-27 22:10:34 +00002833
Andrew Trickef9de2a2013-05-25 02:42:55 +00002834 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00002835 MVT::Other, getControlRoot(),
2836 getValue(I.getAddress())));
Bill Wendling443d0722009-12-21 22:30:11 +00002837}
Dan Gohman575fad32008-09-03 16:12:24 +00002838
Yaron Kerend7ba46b2014-04-19 13:47:43 +00002839void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2840 if (DAG.getTarget().Options.TrapUnreachable)
2841 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2842}
2843
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002844void SelectionDAGBuilder::visitFSub(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002845 // -0.0 - X --> fneg
Chris Lattner229907c2011-07-18 04:54:35 +00002846 Type *Ty = I.getType();
Chris Lattner69229312011-02-15 00:14:00 +00002847 if (isa<Constant>(I.getOperand(0)) &&
2848 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2849 SDValue Op2 = getValue(I.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002850 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
Chris Lattner69229312011-02-15 00:14:00 +00002851 Op2.getValueType(), Op2));
2852 return;
Dan Gohman575fad32008-09-03 16:12:24 +00002853 }
Bill Wendling443d0722009-12-21 22:30:11 +00002854
Dan Gohmana5b96452009-06-04 22:49:04 +00002855 visitBinary(I, ISD::FSUB);
Dan Gohman575fad32008-09-03 16:12:24 +00002856}
2857
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002858void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
Dan Gohman575fad32008-09-03 16:12:24 +00002859 SDValue Op1 = getValue(I.getOperand(0));
2860 SDValue Op2 = getValue(I.getOperand(1));
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00002861
2862 bool nuw = false;
2863 bool nsw = false;
2864 bool exact = false;
2865 if (const OverflowingBinaryOperator *OFBinOp =
2866 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2867 nuw = OFBinOp->hasNoUnsignedWrap();
2868 nsw = OFBinOp->hasNoSignedWrap();
2869 }
2870 if (const PossiblyExactOperator *ExactOp =
2871 dyn_cast<const PossiblyExactOperator>(&I))
2872 exact = ExactOp->isExact();
2873
2874 SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2875 Op1, Op2, nuw, nsw, exact);
2876 setValue(&I, BinNodeValue);
Dan Gohman575fad32008-09-03 16:12:24 +00002877}
2878
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002879void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
Dan Gohman575fad32008-09-03 16:12:24 +00002880 SDValue Op1 = getValue(I.getOperand(0));
2881 SDValue Op2 = getValue(I.getOperand(1));
Owen Andersonb2c80da2011-02-25 21:41:48 +00002882
Eric Christopher58a24612014-10-08 09:50:54 +00002883 EVT ShiftTy =
2884 DAG.getTargetLoweringInfo().getShiftAmountTy(Op2.getValueType());
Owen Andersonb2c80da2011-02-25 21:41:48 +00002885
Chris Lattner2a720d92011-02-13 09:02:52 +00002886 // Coerce the shift amount to the right type if we can.
2887 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
Chris Lattnerd5f0b112011-02-13 09:10:56 +00002888 unsigned ShiftSize = ShiftTy.getSizeInBits();
2889 unsigned Op2Size = Op2.getValueType().getSizeInBits();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002890 SDLoc DL = getCurSDLoc();
Owen Andersonb2c80da2011-02-25 21:41:48 +00002891
Dan Gohman0e8d1992009-04-09 03:51:29 +00002892 // If the operand is smaller than the shift count type, promote it.
Chris Lattner2a720d92011-02-13 09:02:52 +00002893 if (ShiftSize > Op2Size)
2894 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002895
Dan Gohman0e8d1992009-04-09 03:51:29 +00002896 // If the operand is larger than the shift count type but the shift
2897 // count type has enough bits to represent any shift value, truncate
2898 // it now. This is a common case and it exposes the truncate to
2899 // optimization early.
Chris Lattner2a720d92011-02-13 09:02:52 +00002900 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2901 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2902 // Otherwise we'll need to temporarily settle for some other convenient
Chris Lattnere95d1952011-02-13 19:09:16 +00002903 // type. Type legalization will make adjustments once the shiftee is split.
Chris Lattner2a720d92011-02-13 09:02:52 +00002904 else
Chris Lattnere95d1952011-02-13 19:09:16 +00002905 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
Dan Gohman575fad32008-09-03 16:12:24 +00002906 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00002907
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00002908 bool nuw = false;
2909 bool nsw = false;
2910 bool exact = false;
2911
2912 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2913
2914 if (const OverflowingBinaryOperator *OFBinOp =
2915 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2916 nuw = OFBinOp->hasNoUnsignedWrap();
2917 nsw = OFBinOp->hasNoSignedWrap();
2918 }
2919 if (const PossiblyExactOperator *ExactOp =
2920 dyn_cast<const PossiblyExactOperator>(&I))
2921 exact = ExactOp->isExact();
2922 }
2923
2924 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2925 nuw, nsw, exact);
2926 setValue(&I, Res);
Dan Gohman575fad32008-09-03 16:12:24 +00002927}
2928
Benjamin Kramer9960a252011-07-08 10:31:30 +00002929void SelectionDAGBuilder::visitSDiv(const User &I) {
Benjamin Kramer9960a252011-07-08 10:31:30 +00002930 SDValue Op1 = getValue(I.getOperand(0));
2931 SDValue Op2 = getValue(I.getOperand(1));
2932
2933 // Turn exact SDivs into multiplications.
2934 // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2935 // exact bit.
Benjamin Kramer2bb8b262011-07-08 12:08:24 +00002936 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2937 !isa<ConstantSDNode>(Op1) &&
Benjamin Kramer9960a252011-07-08 10:31:30 +00002938 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
Eric Christopher58a24612014-10-08 09:50:54 +00002939 setValue(&I, DAG.getTargetLoweringInfo()
2940 .BuildExactSDIV(Op1, Op2, getCurSDLoc(), DAG));
Benjamin Kramer9960a252011-07-08 10:31:30 +00002941 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00002942 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
Benjamin Kramer9960a252011-07-08 10:31:30 +00002943 Op1, Op2));
2944}
2945
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002946void SelectionDAGBuilder::visitICmp(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002947 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002948 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
Dan Gohman575fad32008-09-03 16:12:24 +00002949 predicate = IC->getPredicate();
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002950 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
Dan Gohman575fad32008-09-03 16:12:24 +00002951 predicate = ICmpInst::Predicate(IC->getPredicate());
2952 SDValue Op1 = getValue(I.getOperand(0));
2953 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman293abcc2008-10-17 18:18:45 +00002954 ISD::CondCode Opcode = getICmpCondCode(predicate);
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00002955
Eric Christopher58a24612014-10-08 09:50:54 +00002956 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002957 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
Dan Gohman575fad32008-09-03 16:12:24 +00002958}
2959
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002960void SelectionDAGBuilder::visitFCmp(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002961 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002962 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
Dan Gohman575fad32008-09-03 16:12:24 +00002963 predicate = FC->getPredicate();
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002964 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
Dan Gohman575fad32008-09-03 16:12:24 +00002965 predicate = FCmpInst::Predicate(FC->getPredicate());
2966 SDValue Op1 = getValue(I.getOperand(0));
2967 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman293abcc2008-10-17 18:18:45 +00002968 ISD::CondCode Condition = getFCmpCondCode(predicate);
Nick Lewycky50f02cb2011-12-02 22:16:29 +00002969 if (TM.Options.NoNaNsFPMath)
2970 Condition = getFCmpCodeWithoutNaN(Condition);
Eric Christopher58a24612014-10-08 09:50:54 +00002971 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002972 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
Dan Gohman575fad32008-09-03 16:12:24 +00002973}
2974
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002975void SelectionDAGBuilder::visitSelect(const User &I) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002976 SmallVector<EVT, 4> ValueVTs;
Eric Christopher58a24612014-10-08 09:50:54 +00002977 ComputeValueVTs(DAG.getTargetLoweringInfo(), I.getType(), ValueVTs);
Dan Gohman8b44b882008-10-21 20:00:42 +00002978 unsigned NumValues = ValueVTs.size();
Bill Wendling443d0722009-12-21 22:30:11 +00002979 if (NumValues == 0) return;
Dan Gohman8b44b882008-10-21 20:00:42 +00002980
Bill Wendling443d0722009-12-21 22:30:11 +00002981 SmallVector<SDValue, 4> Values(NumValues);
2982 SDValue Cond = getValue(I.getOperand(0));
2983 SDValue TrueVal = getValue(I.getOperand(1));
2984 SDValue FalseVal = getValue(I.getOperand(2));
Duncan Sandsf2641e12011-09-06 19:07:46 +00002985 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2986 ISD::VSELECT : ISD::SELECT;
Dan Gohman8b44b882008-10-21 20:00:42 +00002987
Bill Wendling954cb182010-01-28 21:51:40 +00002988 for (unsigned i = 0; i != NumValues; ++i)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002989 Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
Duncan Sandsf2641e12011-09-06 19:07:46 +00002990 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
Chris Lattner53ebf8a2010-03-12 07:15:36 +00002991 Cond,
Bill Wendling443d0722009-12-21 22:30:11 +00002992 SDValue(TrueVal.getNode(),
2993 TrueVal.getResNo() + i),
2994 SDValue(FalseVal.getNode(),
2995 FalseVal.getResNo() + i));
2996
Andrew Trickef9de2a2013-05-25 02:42:55 +00002997 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00002998 DAG.getVTList(ValueVTs), Values));
Bill Wendling443d0722009-12-21 22:30:11 +00002999}
Dan Gohman575fad32008-09-03 16:12:24 +00003000
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003001void SelectionDAGBuilder::visitTrunc(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003002 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3003 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00003004 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003005 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00003006}
3007
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003008void SelectionDAGBuilder::visitZExt(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003009 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3010 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3011 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00003012 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003013 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00003014}
3015
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003016void SelectionDAGBuilder::visitSExt(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003017 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3018 // SExt also can't be a cast to bool for same reason. So, nothing much to do
3019 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00003020 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003021 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00003022}
3023
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003024void SelectionDAGBuilder::visitFPTrunc(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003025 // FPTrunc is never a no-op cast, no need to check
3026 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00003027 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3028 EVT DestVT = TLI.getValueType(I.getType());
3029 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(), DestVT, N,
3030 DAG.getTargetConstant(0, TLI.getPointerTy())));
Dan Gohman575fad32008-09-03 16:12:24 +00003031}
3032
Stephen Lin6d715e82013-07-06 21:44:25 +00003033void SelectionDAGBuilder::visitFPExt(const User &I) {
Hal Finkelbab66782011-10-18 03:51:57 +00003034 // FPExt is never a no-op cast, no need to check
Dan Gohman575fad32008-09-03 16:12:24 +00003035 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00003036 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003037 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00003038}
3039
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003040void SelectionDAGBuilder::visitFPToUI(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003041 // FPToUI is never a no-op cast, no need to check
3042 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00003043 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003044 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00003045}
3046
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003047void SelectionDAGBuilder::visitFPToSI(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003048 // FPToSI is never a no-op cast, no need to check
3049 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00003050 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003051 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00003052}
3053
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003054void SelectionDAGBuilder::visitUIToFP(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003055 // UIToFP is never a no-op cast, no need to check
3056 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00003057 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003058 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00003059}
3060
Stephen Lin6d715e82013-07-06 21:44:25 +00003061void SelectionDAGBuilder::visitSIToFP(const User &I) {
Bill Wendling6c87bfc2008-10-19 20:34:04 +00003062 // SIToFP is never a no-op cast, no need to check
Dan Gohman575fad32008-09-03 16:12:24 +00003063 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00003064 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003065 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00003066}
3067
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003068void SelectionDAGBuilder::visitPtrToInt(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003069 // What to do depends on the size of the integer and the size of the pointer.
3070 // We can either truncate, zero extend, or no-op, accordingly.
3071 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00003072 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003073 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
Dan Gohman575fad32008-09-03 16:12:24 +00003074}
3075
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003076void SelectionDAGBuilder::visitIntToPtr(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003077 // What to do depends on the size of the integer and the size of the pointer.
3078 // We can either truncate, zero extend, or no-op, accordingly.
3079 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00003080 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003081 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
Dan Gohman575fad32008-09-03 16:12:24 +00003082}
3083
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003084void SelectionDAGBuilder::visitBitCast(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003085 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00003086 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Dan Gohman575fad32008-09-03 16:12:24 +00003087
Bill Wendling443d0722009-12-21 22:30:11 +00003088 // BitCast assures us that source and destination are the same size so this is
Wesley Peck527da1b2010-11-23 03:31:01 +00003089 // either a BITCAST or a no-op.
Bill Wendling954cb182010-01-28 21:51:40 +00003090 if (DestVT != N.getValueType())
Andrew Trickef9de2a2013-05-25 02:42:55 +00003091 setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00003092 DestVT, N)); // convert types.
Juergen Ributzka2b97f9b2014-02-13 04:19:26 +00003093 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3094 // might fold any kind of constant expression to an integer constant and that
3095 // is not what we are looking for. Only regcognize a bitcast of a genuine
3096 // constant integer as an opaque constant.
3097 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3098 setValue(&I, DAG.getConstant(C->getValue(), DestVT, /*isTarget=*/false,
3099 /*isOpaque*/true));
Bill Wendling954cb182010-01-28 21:51:40 +00003100 else
Bill Wendling443d0722009-12-21 22:30:11 +00003101 setValue(&I, N); // noop cast.
Dan Gohman575fad32008-09-03 16:12:24 +00003102}
3103
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003104void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3105 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3106 const Value *SV = I.getOperand(0);
3107 SDValue N = getValue(SV);
Eric Christopher58a24612014-10-08 09:50:54 +00003108 EVT DestVT = TLI.getValueType(I.getType());
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003109
3110 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3111 unsigned DestAS = I.getType()->getPointerAddressSpace();
3112
3113 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3114 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3115
3116 setValue(&I, N);
3117}
3118
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003119void SelectionDAGBuilder::visitInsertElement(const User &I) {
Tom Stellardd42c5942013-08-05 22:22:01 +00003120 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman575fad32008-09-03 16:12:24 +00003121 SDValue InVec = getValue(I.getOperand(0));
3122 SDValue InVal = getValue(I.getOperand(1));
Tom Stellardd42c5942013-08-05 22:22:01 +00003123 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
3124 getCurSDLoc(), TLI.getVectorIdxTy());
Eric Christopher58a24612014-10-08 09:50:54 +00003125 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3126 TLI.getValueType(I.getType()), InVec, InVal, InIdx));
Dan Gohman575fad32008-09-03 16:12:24 +00003127}
3128
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003129void SelectionDAGBuilder::visitExtractElement(const User &I) {
Tom Stellardd42c5942013-08-05 22:22:01 +00003130 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman575fad32008-09-03 16:12:24 +00003131 SDValue InVec = getValue(I.getOperand(0));
Tom Stellardd42c5942013-08-05 22:22:01 +00003132 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
3133 getCurSDLoc(), TLI.getVectorIdxTy());
Eric Christopher58a24612014-10-08 09:50:54 +00003134 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3135 TLI.getValueType(I.getType()), InVec, InIdx));
Dan Gohman575fad32008-09-03 16:12:24 +00003136}
3137
Craig Topperf726e152012-01-04 09:23:09 +00003138// Utility for visitShuffleVector - Return true if every element in Mask,
Benjamin Kramerbde91762012-06-02 10:20:22 +00003139// beginning from position Pos and ending in Pos+Size, falls within the
Craig Topperf726e152012-01-04 09:23:09 +00003140// specified sequential range [L, L+Pos). or is undef.
3141static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
Craig Topper3ef01cd2012-04-11 03:06:35 +00003142 unsigned Pos, unsigned Size, int Low) {
3143 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
Craig Topperf726e152012-01-04 09:23:09 +00003144 if (Mask[i] >= 0 && Mask[i] != Low)
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003145 return false;
Mon P Wang25f01062008-11-10 04:46:22 +00003146 return true;
3147}
3148
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003149void SelectionDAGBuilder::visitShuffleVector(const User &I) {
Mon P Wangc3113602008-11-21 04:25:21 +00003150 SDValue Src1 = getValue(I.getOperand(0));
3151 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohman575fad32008-09-03 16:12:24 +00003152
Chris Lattnercf129702012-01-26 02:51:13 +00003153 SmallVector<int, 8> Mask;
3154 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3155 unsigned MaskNumElts = Mask.size();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003156
Eric Christopher58a24612014-10-08 09:50:54 +00003157 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3158 EVT VT = TLI.getValueType(I.getType());
Owen Anderson53aa7a92009-08-10 22:56:29 +00003159 EVT SrcVT = Src1.getValueType();
Nate Begeman5f829d82009-04-29 05:20:52 +00003160 unsigned SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wang25f01062008-11-10 04:46:22 +00003161
Mon P Wang7a824742008-11-16 05:06:27 +00003162 if (SrcNumElts == MaskNumElts) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003163 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
Bill Wendling954cb182010-01-28 21:51:40 +00003164 &Mask[0]));
Mon P Wang25f01062008-11-10 04:46:22 +00003165 return;
3166 }
3167
3168 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wang7a824742008-11-16 05:06:27 +00003169 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
3170 // Mask is longer than the source vectors and is a multiple of the source
3171 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wangc3113602008-11-21 04:25:21 +00003172 // lengths match.
Craig Topperf726e152012-01-04 09:23:09 +00003173 if (SrcNumElts*2 == MaskNumElts) {
3174 // First check for Src1 in low and Src2 in high
3175 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
3176 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
3177 // The shuffle is concatenating two vectors together.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003178 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
Craig Topperf726e152012-01-04 09:23:09 +00003179 VT, Src1, Src2));
3180 return;
3181 }
3182 // Then check for Src2 in low and Src1 in high
3183 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
3184 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
3185 // The shuffle is concatenating two vectors together.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003186 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
Craig Topperf726e152012-01-04 09:23:09 +00003187 VT, Src2, Src1));
3188 return;
3189 }
Mon P Wang25f01062008-11-10 04:46:22 +00003190 }
3191
Mon P Wang7a824742008-11-16 05:06:27 +00003192 // Pad both vectors with undefs to make them the same length as the mask.
3193 unsigned NumConcat = MaskNumElts / SrcNumElts;
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003194 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
3195 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
Dale Johannesen84935752009-02-06 23:05:02 +00003196 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wang25f01062008-11-10 04:46:22 +00003197
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003198 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3199 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
Mon P Wangc3113602008-11-21 04:25:21 +00003200 MOps1[0] = Src1;
3201 MOps2[0] = Src2;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00003202
3203 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
Craig Topper48d114b2014-04-26 18:35:24 +00003204 getCurSDLoc(), VT, MOps1);
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003205 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
Craig Topper48d114b2014-04-26 18:35:24 +00003206 getCurSDLoc(), VT, MOps2);
Mon P Wangc3113602008-11-21 04:25:21 +00003207
Mon P Wang25f01062008-11-10 04:46:22 +00003208 // Readjust mask for new input vector length.
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003209 SmallVector<int, 8> MappedOps;
Nate Begeman5f829d82009-04-29 05:20:52 +00003210 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003211 int Idx = Mask[i];
Craig Topper3ef01cd2012-04-11 03:06:35 +00003212 if (Idx >= (int)SrcNumElts)
3213 Idx -= SrcNumElts - MaskNumElts;
3214 MappedOps.push_back(Idx);
Mon P Wang25f01062008-11-10 04:46:22 +00003215 }
Bill Wendlingfff99f02009-12-21 22:42:14 +00003216
Andrew Trickef9de2a2013-05-25 02:42:55 +00003217 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
Bill Wendling954cb182010-01-28 21:51:40 +00003218 &MappedOps[0]));
Mon P Wang25f01062008-11-10 04:46:22 +00003219 return;
3220 }
3221
Mon P Wang7a824742008-11-16 05:06:27 +00003222 if (SrcNumElts > MaskNumElts) {
Mon P Wang7a824742008-11-16 05:06:27 +00003223 // Analyze the access pattern of the vector to see if we can extract
3224 // two subvectors and do the shuffle. The analysis is done by calculating
3225 // the range of elements the mask access on both vectors.
Craig Topper6148fe62012-04-08 23:15:04 +00003226 int MinRange[2] = { static_cast<int>(SrcNumElts),
3227 static_cast<int>(SrcNumElts)};
Mon P Wang7a824742008-11-16 05:06:27 +00003228 int MaxRange[2] = {-1, -1};
3229
Nate Begeman5f829d82009-04-29 05:20:52 +00003230 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003231 int Idx = Mask[i];
Craig Topper6148fe62012-04-08 23:15:04 +00003232 unsigned Input = 0;
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003233 if (Idx < 0)
3234 continue;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00003235
Nate Begeman5f829d82009-04-29 05:20:52 +00003236 if (Idx >= (int)SrcNumElts) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003237 Input = 1;
3238 Idx -= SrcNumElts;
Mon P Wang25f01062008-11-10 04:46:22 +00003239 }
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003240 if (Idx > MaxRange[Input])
3241 MaxRange[Input] = Idx;
3242 if (Idx < MinRange[Input])
3243 MinRange[Input] = Idx;
Mon P Wang25f01062008-11-10 04:46:22 +00003244 }
Mon P Wang25f01062008-11-10 04:46:22 +00003245
Mon P Wang7a824742008-11-16 05:06:27 +00003246 // Check if the access is smaller than the vector size and can we find
3247 // a reasonable extract index.
Craig Topper6148fe62012-04-08 23:15:04 +00003248 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
3249 // Extract.
Mon P Wang7a824742008-11-16 05:06:27 +00003250 int StartIdx[2]; // StartIdx to extract from
Craig Topper6148fe62012-04-08 23:15:04 +00003251 for (unsigned Input = 0; Input < 2; ++Input) {
3252 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
Mon P Wang7a824742008-11-16 05:06:27 +00003253 RangeUse[Input] = 0; // Unused
3254 StartIdx[Input] = 0;
Craig Topperc8e2d912012-04-08 17:53:33 +00003255 continue;
Mon P Wangc3113602008-11-21 04:25:21 +00003256 }
Craig Topperc8e2d912012-04-08 17:53:33 +00003257
3258 // Find a good start index that is a multiple of the mask length. Then
3259 // see if the rest of the elements are in range.
3260 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
3261 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
3262 StartIdx[Input] + MaskNumElts <= SrcNumElts)
3263 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wang7a824742008-11-16 05:06:27 +00003264 }
3265
Bill Wendlingdff54ef2009-08-21 18:16:06 +00003266 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
Bill Wendling954cb182010-01-28 21:51:40 +00003267 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wang7a824742008-11-16 05:06:27 +00003268 return;
3269 }
Craig Topper6148fe62012-04-08 23:15:04 +00003270 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
Mon P Wang7a824742008-11-16 05:06:27 +00003271 // Extract appropriate subvector and generate a vector shuffle
Craig Topper6148fe62012-04-08 23:15:04 +00003272 for (unsigned Input = 0; Input < 2; ++Input) {
Bill Wendlingc6b47342009-12-21 23:47:40 +00003273 SDValue &Src = Input == 0 ? Src1 : Src2;
Bill Wendlingfff99f02009-12-21 22:42:14 +00003274 if (RangeUse[Input] == 0)
Dale Johannesen84935752009-02-06 23:05:02 +00003275 Src = DAG.getUNDEF(VT);
Bill Wendlingfff99f02009-12-21 22:42:14 +00003276 else
Eric Christopher58a24612014-10-08 09:50:54 +00003277 Src = DAG.getNode(
3278 ISD::EXTRACT_SUBVECTOR, getCurSDLoc(), VT, Src,
3279 DAG.getConstant(StartIdx[Input], TLI.getVectorIdxTy()));
Mon P Wang25f01062008-11-10 04:46:22 +00003280 }
Bill Wendlingfff99f02009-12-21 22:42:14 +00003281
Mon P Wang7a824742008-11-16 05:06:27 +00003282 // Calculate new mask.
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003283 SmallVector<int, 8> MappedOps;
Nate Begeman5f829d82009-04-29 05:20:52 +00003284 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003285 int Idx = Mask[i];
Craig Topper3ef01cd2012-04-11 03:06:35 +00003286 if (Idx >= 0) {
3287 if (Idx < (int)SrcNumElts)
3288 Idx -= StartIdx[0];
3289 else
3290 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3291 }
3292 MappedOps.push_back(Idx);
Mon P Wang7a824742008-11-16 05:06:27 +00003293 }
Bill Wendlingfff99f02009-12-21 22:42:14 +00003294
Andrew Trickef9de2a2013-05-25 02:42:55 +00003295 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
Bill Wendling954cb182010-01-28 21:51:40 +00003296 &MappedOps[0]));
Mon P Wang7a824742008-11-16 05:06:27 +00003297 return;
Mon P Wang25f01062008-11-10 04:46:22 +00003298 }
3299 }
3300
Mon P Wang7a824742008-11-16 05:06:27 +00003301 // We can't use either concat vectors or extract subvectors so fall back to
3302 // replacing the shuffle with extract and build vector.
3303 // to insert and build vector.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003304 EVT EltVT = VT.getVectorElementType();
Eric Christopher58a24612014-10-08 09:50:54 +00003305 EVT IdxVT = TLI.getVectorIdxTy();
Mon P Wang25f01062008-11-10 04:46:22 +00003306 SmallVector<SDValue,8> Ops;
Nate Begeman5f829d82009-04-29 05:20:52 +00003307 for (unsigned i = 0; i != MaskNumElts; ++i) {
Craig Topper3ef01cd2012-04-11 03:06:35 +00003308 int Idx = Mask[i];
3309 SDValue Res;
3310
3311 if (Idx < 0) {
3312 Res = DAG.getUNDEF(EltVT);
Mon P Wang25f01062008-11-10 04:46:22 +00003313 } else {
Craig Topper3ef01cd2012-04-11 03:06:35 +00003314 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3315 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
Bill Wendlingfff99f02009-12-21 22:42:14 +00003316
Andrew Trickef9de2a2013-05-25 02:42:55 +00003317 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
Tom Stellardd42c5942013-08-05 22:22:01 +00003318 EltVT, Src, DAG.getConstant(Idx, IdxVT));
Mon P Wang25f01062008-11-10 04:46:22 +00003319 }
Craig Topper3ef01cd2012-04-11 03:06:35 +00003320
3321 Ops.push_back(Res);
Mon P Wang25f01062008-11-10 04:46:22 +00003322 }
Bill Wendlingfff99f02009-12-21 22:42:14 +00003323
Craig Topper48d114b2014-04-26 18:35:24 +00003324 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops));
Dan Gohman575fad32008-09-03 16:12:24 +00003325}
3326
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003327void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003328 const Value *Op0 = I.getOperand(0);
3329 const Value *Op1 = I.getOperand(1);
Chris Lattner229907c2011-07-18 04:54:35 +00003330 Type *AggTy = I.getType();
3331 Type *ValTy = Op1->getType();
Dan Gohman575fad32008-09-03 16:12:24 +00003332 bool IntoUndef = isa<UndefValue>(Op0);
3333 bool FromUndef = isa<UndefValue>(Op1);
3334
Jay Foad57aa6362011-07-13 10:26:04 +00003335 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
Dan Gohman575fad32008-09-03 16:12:24 +00003336
Eric Christopher58a24612014-10-08 09:50:54 +00003337 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Owen Anderson53aa7a92009-08-10 22:56:29 +00003338 SmallVector<EVT, 4> AggValueVTs;
Eric Christopher58a24612014-10-08 09:50:54 +00003339 ComputeValueVTs(TLI, AggTy, AggValueVTs);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003340 SmallVector<EVT, 4> ValValueVTs;
Eric Christopher58a24612014-10-08 09:50:54 +00003341 ComputeValueVTs(TLI, ValTy, ValValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00003342
3343 unsigned NumAggValues = AggValueVTs.size();
3344 unsigned NumValValues = ValValueVTs.size();
3345 SmallVector<SDValue, 4> Values(NumAggValues);
3346
Peter Collingbourne97572632014-09-20 00:10:47 +00003347 // Ignore an insertvalue that produces an empty object
3348 if (!NumAggValues) {
3349 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3350 return;
3351 }
3352
Dan Gohman575fad32008-09-03 16:12:24 +00003353 SDValue Agg = getValue(Op0);
Dan Gohman575fad32008-09-03 16:12:24 +00003354 unsigned i = 0;
3355 // Copy the beginning value(s) from the original aggregate.
3356 for (; i != LinearIndex; ++i)
Dale Johannesen84935752009-02-06 23:05:02 +00003357 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohman575fad32008-09-03 16:12:24 +00003358 SDValue(Agg.getNode(), Agg.getResNo() + i);
3359 // Copy values from the inserted value(s).
Rafael Espindolae53b7d12011-05-13 15:18:06 +00003360 if (NumValValues) {
3361 SDValue Val = getValue(Op1);
3362 for (; i != LinearIndex + NumValValues; ++i)
3363 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3364 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3365 }
Dan Gohman575fad32008-09-03 16:12:24 +00003366 // Copy remaining value(s) from the original aggregate.
3367 for (; i != NumAggValues; ++i)
Dale Johannesen84935752009-02-06 23:05:02 +00003368 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohman575fad32008-09-03 16:12:24 +00003369 SDValue(Agg.getNode(), Agg.getResNo() + i);
3370
Andrew Trickef9de2a2013-05-25 02:42:55 +00003371 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00003372 DAG.getVTList(AggValueVTs), Values));
Dan Gohman575fad32008-09-03 16:12:24 +00003373}
3374
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003375void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003376 const Value *Op0 = I.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00003377 Type *AggTy = Op0->getType();
3378 Type *ValTy = I.getType();
Dan Gohman575fad32008-09-03 16:12:24 +00003379 bool OutOfUndef = isa<UndefValue>(Op0);
3380
Jay Foad57aa6362011-07-13 10:26:04 +00003381 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
Dan Gohman575fad32008-09-03 16:12:24 +00003382
Eric Christopher58a24612014-10-08 09:50:54 +00003383 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Owen Anderson53aa7a92009-08-10 22:56:29 +00003384 SmallVector<EVT, 4> ValValueVTs;
Eric Christopher58a24612014-10-08 09:50:54 +00003385 ComputeValueVTs(TLI, ValTy, ValValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00003386
3387 unsigned NumValValues = ValValueVTs.size();
Rafael Espindolae53b7d12011-05-13 15:18:06 +00003388
3389 // Ignore a extractvalue that produces an empty object
3390 if (!NumValValues) {
3391 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3392 return;
3393 }
3394
Dan Gohman575fad32008-09-03 16:12:24 +00003395 SmallVector<SDValue, 4> Values(NumValValues);
3396
3397 SDValue Agg = getValue(Op0);
3398 // Copy out the selected value(s).
3399 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3400 Values[i - LinearIndex] =
Bill Wendling165b45d2008-11-20 07:24:30 +00003401 OutOfUndef ?
Dale Johannesen84935752009-02-06 23:05:02 +00003402 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendling165b45d2008-11-20 07:24:30 +00003403 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohman575fad32008-09-03 16:12:24 +00003404
Andrew Trickef9de2a2013-05-25 02:42:55 +00003405 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00003406 DAG.getVTList(ValValueVTs), Values));
Dan Gohman575fad32008-09-03 16:12:24 +00003407}
3408
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003409void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
Matt Arsenaultb7689122013-10-21 20:03:54 +00003410 Value *Op0 = I.getOperand(0);
Nadav Rotem1d666092012-02-28 14:13:19 +00003411 // Note that the pointer operand may be a vector of pointers. Take the scalar
3412 // element which holds a pointer.
Matt Arsenaultb7689122013-10-21 20:03:54 +00003413 Type *Ty = Op0->getType()->getScalarType();
3414 unsigned AS = Ty->getPointerAddressSpace();
3415 SDValue N = getValue(Op0);
Dan Gohman575fad32008-09-03 16:12:24 +00003416
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003417 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
Dan Gohman575fad32008-09-03 16:12:24 +00003418 OI != E; ++OI) {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003419 const Value *Idx = *OI;
Chris Lattner229907c2011-07-18 04:54:35 +00003420 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
Duncan Sandsb8d3caf2012-11-13 13:01:58 +00003421 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
Dan Gohman575fad32008-09-03 16:12:24 +00003422 if (Field) {
3423 // N = N + Offset
Rafael Espindola5f57f462014-02-21 18:34:28 +00003424 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003425 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
Duncan Sandsb8d3caf2012-11-13 13:01:58 +00003426 DAG.getConstant(Offset, N.getValueType()));
Dan Gohman575fad32008-09-03 16:12:24 +00003427 }
Bill Wendlinge79105b2009-12-21 23:10:19 +00003428
Dan Gohman575fad32008-09-03 16:12:24 +00003429 Ty = StTy->getElementType(Field);
3430 } else {
3431 Ty = cast<SequentialType>(Ty)->getElementType();
3432
3433 // If this is a constant subscript, handle it quickly.
Eric Christopher58a24612014-10-08 09:50:54 +00003434 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003435 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Dan Gohmanf1d83042010-06-18 14:22:04 +00003436 if (CI->isZero()) continue;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003437 uint64_t Offs =
Rafael Espindola5f57f462014-02-21 18:34:28 +00003438 DL->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Chengfe174df2009-02-09 21:01:06 +00003439 SDValue OffsVal;
Eric Christopher58a24612014-10-08 09:50:54 +00003440 EVT PTy = TLI.getPointerTy(AS);
Owen Andersonc30530d2009-08-10 18:56:59 +00003441 unsigned PtrBits = PTy.getSizeInBits();
Bill Wendlinge79105b2009-12-21 23:10:19 +00003442 if (PtrBits < 64)
Tom Stellardfd155822013-08-26 15:05:36 +00003443 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), PTy,
Owen Anderson9f944592009-08-11 20:47:22 +00003444 DAG.getConstant(Offs, MVT::i64));
Bill Wendlinge79105b2009-12-21 23:10:19 +00003445 else
Tom Stellardfd155822013-08-26 15:05:36 +00003446 OffsVal = DAG.getConstant(Offs, PTy);
Bill Wendlinge79105b2009-12-21 23:10:19 +00003447
Andrew Trickef9de2a2013-05-25 02:42:55 +00003448 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
Evan Cheng020588c2009-02-09 20:54:38 +00003449 OffsVal);
Dan Gohman575fad32008-09-03 16:12:24 +00003450 continue;
3451 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003452
Dan Gohman575fad32008-09-03 16:12:24 +00003453 // N = N + Idx * ElementSize;
Eric Christopher58a24612014-10-08 09:50:54 +00003454 APInt ElementSize =
3455 APInt(TLI.getPointerSizeInBits(AS), DL->getTypeAllocSize(Ty));
Dan Gohman575fad32008-09-03 16:12:24 +00003456 SDValue IdxN = getValue(Idx);
3457
3458 // If the index is smaller or larger than intptr_t, truncate or extend
3459 // it.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003460 IdxN = DAG.getSExtOrTrunc(IdxN, getCurSDLoc(), N.getValueType());
Dan Gohman575fad32008-09-03 16:12:24 +00003461
3462 // If this is a multiply by a power of two, turn it into a shl
3463 // immediately. This is a very common case.
3464 if (ElementSize != 1) {
Dan Gohman4ef112b2009-10-23 17:57:43 +00003465 if (ElementSize.isPowerOf2()) {
3466 unsigned Amt = ElementSize.logBase2();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003467 IdxN = DAG.getNode(ISD::SHL, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00003468 N.getValueType(), IdxN,
Nadav Rotem3924cb02011-12-05 06:29:09 +00003469 DAG.getConstant(Amt, IdxN.getValueType()));
Dan Gohman575fad32008-09-03 16:12:24 +00003470 } else {
Duncan Sandsb8d3caf2012-11-13 13:01:58 +00003471 SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003472 IdxN = DAG.getNode(ISD::MUL, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00003473 N.getValueType(), IdxN, Scale);
Dan Gohman575fad32008-09-03 16:12:24 +00003474 }
3475 }
3476
Andrew Trickef9de2a2013-05-25 02:42:55 +00003477 N = DAG.getNode(ISD::ADD, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00003478 N.getValueType(), N, IdxN);
Dan Gohman575fad32008-09-03 16:12:24 +00003479 }
3480 }
Bill Wendlinge79105b2009-12-21 23:10:19 +00003481
Dan Gohman575fad32008-09-03 16:12:24 +00003482 setValue(&I, N);
3483}
3484
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003485void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003486 // If this is a fixed sized alloca in the entry block of the function,
3487 // allocate it statically on the stack.
3488 if (FuncInfo.StaticAllocaMap.count(&I))
3489 return; // getValue will auto-populate this.
3490
Chris Lattner229907c2011-07-18 04:54:35 +00003491 Type *Ty = I.getAllocatedType();
Eric Christopher58a24612014-10-08 09:50:54 +00003492 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3493 uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
Dan Gohman575fad32008-09-03 16:12:24 +00003494 unsigned Align =
Eric Christopher58a24612014-10-08 09:50:54 +00003495 std::max((unsigned)TLI.getDataLayout()->getPrefTypeAlignment(Ty),
3496 I.getAlignment());
Dan Gohman575fad32008-09-03 16:12:24 +00003497
3498 SDValue AllocSize = getValue(I.getArraySize());
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00003499
Eric Christopher58a24612014-10-08 09:50:54 +00003500 EVT IntPtr = TLI.getPointerTy();
Dan Gohman2140a742010-05-28 01:14:11 +00003501 if (AllocSize.getValueType() != IntPtr)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003502 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurSDLoc(), IntPtr);
Dan Gohman2140a742010-05-28 01:14:11 +00003503
Andrew Trickef9de2a2013-05-25 02:42:55 +00003504 AllocSize = DAG.getNode(ISD::MUL, getCurSDLoc(), IntPtr,
Dan Gohman2140a742010-05-28 01:14:11 +00003505 AllocSize,
3506 DAG.getConstant(TySize, IntPtr));
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00003507
Dan Gohman575fad32008-09-03 16:12:24 +00003508 // Handle alignment. If the requested alignment is less than or equal to
3509 // the stack alignment, ignore it. If the size is greater than or equal to
3510 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Eric Christopherd9134482014-08-04 21:25:23 +00003511 unsigned StackAlign =
Eric Christopher85de8f92014-10-09 01:35:27 +00003512 DAG.getSubtarget().getFrameLowering()->getStackAlignment();
Dan Gohman575fad32008-09-03 16:12:24 +00003513 if (Align <= StackAlign)
3514 Align = 0;
3515
3516 // Round the size of the allocation up to the stack alignment size
3517 // by add SA-1 to the size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003518 AllocSize = DAG.getNode(ISD::ADD, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00003519 AllocSize.getValueType(), AllocSize,
Dan Gohman575fad32008-09-03 16:12:24 +00003520 DAG.getIntPtrConstant(StackAlign-1));
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003521
Dan Gohman575fad32008-09-03 16:12:24 +00003522 // Mask out the low bits for alignment purposes.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003523 AllocSize = DAG.getNode(ISD::AND, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00003524 AllocSize.getValueType(), AllocSize,
Dan Gohman575fad32008-09-03 16:12:24 +00003525 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
3526
3527 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Owen Anderson9f944592009-08-11 20:47:22 +00003528 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
Craig Topper48d114b2014-04-26 18:35:24 +00003529 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurSDLoc(), VTs, Ops);
Dan Gohman575fad32008-09-03 16:12:24 +00003530 setValue(&I, DSA);
3531 DAG.setRoot(DSA.getValue(1));
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003532
Hans Wennborgacb842d2014-03-05 02:43:26 +00003533 assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
Dan Gohman575fad32008-09-03 16:12:24 +00003534}
3535
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003536void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
Eli Friedman342e8df2011-08-24 20:50:09 +00003537 if (I.isAtomic())
3538 return visitAtomicLoad(I);
3539
Dan Gohman575fad32008-09-03 16:12:24 +00003540 const Value *SV = I.getOperand(0);
3541 SDValue Ptr = getValue(SV);
3542
Chris Lattner229907c2011-07-18 04:54:35 +00003543 Type *Ty = I.getType();
David Greene39c6d012010-02-15 17:00:31 +00003544
Dan Gohman575fad32008-09-03 16:12:24 +00003545 bool isVolatile = I.isVolatile();
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00003546 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3547 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00003548 unsigned Alignment = I.getAlignment();
Hal Finkelcc39b672014-07-24 12:16:19 +00003549
3550 AAMDNodes AAInfo;
3551 I.getAAMetadata(AAInfo);
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00003552 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
Dan Gohman575fad32008-09-03 16:12:24 +00003553
Eric Christopher58a24612014-10-08 09:50:54 +00003554 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Owen Anderson53aa7a92009-08-10 22:56:29 +00003555 SmallVector<EVT, 4> ValueVTs;
Dan Gohman575fad32008-09-03 16:12:24 +00003556 SmallVector<uint64_t, 4> Offsets;
Eric Christopher58a24612014-10-08 09:50:54 +00003557 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
Dan Gohman575fad32008-09-03 16:12:24 +00003558 unsigned NumValues = ValueVTs.size();
3559 if (NumValues == 0)
3560 return;
3561
3562 SDValue Root;
3563 bool ConstantMemory = false;
Richard Sandiford9afe6132013-12-10 10:36:34 +00003564 if (isVolatile || NumValues > MaxParallelChains)
Dan Gohman575fad32008-09-03 16:12:24 +00003565 // Serialize volatile loads with other side effects.
3566 Root = getRoot();
Dan Gohmana94cc6d2010-10-20 00:31:05 +00003567 else if (AA->pointsToConstantMemory(
Hal Finkelcc39b672014-07-24 12:16:19 +00003568 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), AAInfo))) {
Dan Gohman575fad32008-09-03 16:12:24 +00003569 // Do not serialize (non-volatile) loads of constant memory with anything.
3570 Root = DAG.getEntryNode();
3571 ConstantMemory = true;
3572 } else {
3573 // Do not serialize non-volatile loads against each other.
3574 Root = DAG.getRoot();
3575 }
Wesley Peck527da1b2010-11-23 03:31:01 +00003576
Richard Sandiford9afe6132013-12-10 10:36:34 +00003577 if (isVolatile)
Eric Christopher58a24612014-10-08 09:50:54 +00003578 Root = TLI.prepareVolatileOrAtomicLoad(Root, getCurSDLoc(), DAG);
Richard Sandiford9afe6132013-12-10 10:36:34 +00003579
Dan Gohman575fad32008-09-03 16:12:24 +00003580 SmallVector<SDValue, 4> Values(NumValues);
Andrew Trick116efac2010-11-12 17:50:46 +00003581 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3582 NumValues));
Owen Anderson53aa7a92009-08-10 22:56:29 +00003583 EVT PtrVT = Ptr.getValueType();
Andrew Trick116efac2010-11-12 17:50:46 +00003584 unsigned ChainI = 0;
3585 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3586 // Serializing loads here may result in excessive register pressure, and
3587 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3588 // could recover a bit by hoisting nodes upward in the chain by recognizing
3589 // they are side-effect free or do not alias. The optimizer should really
3590 // avoid this case by converting large object/array copies to llvm.memcpy
3591 // (MaxParallelChains should always remain as failsafe).
3592 if (ChainI == MaxParallelChains) {
3593 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
Craig Topper48d114b2014-04-26 18:35:24 +00003594 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Craig Topper2d2aa0c2014-04-30 07:17:30 +00003595 makeArrayRef(Chains.data(), ChainI));
Andrew Trick116efac2010-11-12 17:50:46 +00003596 Root = Chain;
3597 ChainI = 0;
3598 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00003599 SDValue A = DAG.getNode(ISD::ADD, getCurSDLoc(),
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003600 PtrVT, Ptr,
3601 DAG.getConstant(Offsets[i], PtrVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003602 SDValue L = DAG.getLoad(ValueVTs[i], getCurSDLoc(), Root,
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00003603 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
Hal Finkelcc39b672014-07-24 12:16:19 +00003604 isNonTemporal, isInvariant, Alignment, AAInfo,
Rafael Espindola80c540e2012-03-31 18:14:00 +00003605 Ranges);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003606
Dan Gohman575fad32008-09-03 16:12:24 +00003607 Values[i] = L;
Andrew Trick116efac2010-11-12 17:50:46 +00003608 Chains[ChainI] = L.getValue(1);
Dan Gohman575fad32008-09-03 16:12:24 +00003609 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003610
Dan Gohman575fad32008-09-03 16:12:24 +00003611 if (!ConstantMemory) {
Craig Topper48d114b2014-04-26 18:35:24 +00003612 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Craig Topper2d2aa0c2014-04-30 07:17:30 +00003613 makeArrayRef(Chains.data(), ChainI));
Dan Gohman575fad32008-09-03 16:12:24 +00003614 if (isVolatile)
3615 DAG.setRoot(Chain);
3616 else
3617 PendingLoads.push_back(Chain);
3618 }
3619
Andrew Trickef9de2a2013-05-25 02:42:55 +00003620 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00003621 DAG.getVTList(ValueVTs), Values));
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003622}
Dan Gohman575fad32008-09-03 16:12:24 +00003623
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003624void SelectionDAGBuilder::visitStore(const StoreInst &I) {
Eli Friedman342e8df2011-08-24 20:50:09 +00003625 if (I.isAtomic())
3626 return visitAtomicStore(I);
3627
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003628 const Value *SrcV = I.getOperand(0);
3629 const Value *PtrV = I.getOperand(1);
Dan Gohman575fad32008-09-03 16:12:24 +00003630
Owen Anderson53aa7a92009-08-10 22:56:29 +00003631 SmallVector<EVT, 4> ValueVTs;
Dan Gohman575fad32008-09-03 16:12:24 +00003632 SmallVector<uint64_t, 4> Offsets;
Eric Christopher58a24612014-10-08 09:50:54 +00003633 ComputeValueVTs(DAG.getTargetLoweringInfo(), SrcV->getType(),
Eric Christopherd9134482014-08-04 21:25:23 +00003634 ValueVTs, &Offsets);
Dan Gohman575fad32008-09-03 16:12:24 +00003635 unsigned NumValues = ValueVTs.size();
3636 if (NumValues == 0)
3637 return;
3638
3639 // Get the lowered operands. Note that we do this after
3640 // checking if NumResults is zero, because with zero results
3641 // the operands won't have values in the map.
3642 SDValue Src = getValue(SrcV);
3643 SDValue Ptr = getValue(PtrV);
3644
3645 SDValue Root = getRoot();
Andrew Trick116efac2010-11-12 17:50:46 +00003646 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3647 NumValues));
Owen Anderson53aa7a92009-08-10 22:56:29 +00003648 EVT PtrVT = Ptr.getValueType();
Dan Gohman575fad32008-09-03 16:12:24 +00003649 bool isVolatile = I.isVolatile();
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00003650 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00003651 unsigned Alignment = I.getAlignment();
Hal Finkelcc39b672014-07-24 12:16:19 +00003652
3653 AAMDNodes AAInfo;
3654 I.getAAMetadata(AAInfo);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003655
Andrew Trick116efac2010-11-12 17:50:46 +00003656 unsigned ChainI = 0;
3657 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3658 // See visitLoad comments.
3659 if (ChainI == MaxParallelChains) {
Craig Topper48d114b2014-04-26 18:35:24 +00003660 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Craig Topper2d2aa0c2014-04-30 07:17:30 +00003661 makeArrayRef(Chains.data(), ChainI));
Andrew Trick116efac2010-11-12 17:50:46 +00003662 Root = Chain;
3663 ChainI = 0;
3664 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00003665 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, Ptr,
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003666 DAG.getConstant(Offsets[i], PtrVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003667 SDValue St = DAG.getStore(Root, getCurSDLoc(),
Andrew Trick116efac2010-11-12 17:50:46 +00003668 SDValue(Src.getNode(), Src.getResNo() + i),
3669 Add, MachinePointerInfo(PtrV, Offsets[i]),
Hal Finkelcc39b672014-07-24 12:16:19 +00003670 isVolatile, isNonTemporal, Alignment, AAInfo);
Andrew Trick116efac2010-11-12 17:50:46 +00003671 Chains[ChainI] = St;
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003672 }
3673
Craig Topper48d114b2014-04-26 18:35:24 +00003674 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Craig Topper2d2aa0c2014-04-30 07:17:30 +00003675 makeArrayRef(Chains.data(), ChainI));
Devang Patel05561e82010-10-26 22:14:52 +00003676 DAG.setRoot(StoreNode);
Dan Gohman575fad32008-09-03 16:12:24 +00003677}
3678
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00003679void SelectionDAGBuilder::visitMaskedStore(const CallInst &I) {
3680 SDLoc sdl = getCurSDLoc();
3681
Elena Demikhovskyfb81b932014-12-25 07:49:20 +00003682 // llvm.masked.store.*(Src0, Ptr, alignemt, Mask)
3683 Value *PtrOperand = I.getArgOperand(1);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00003684 SDValue Ptr = getValue(PtrOperand);
Elena Demikhovskyfb81b932014-12-25 07:49:20 +00003685 SDValue Src0 = getValue(I.getArgOperand(0));
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00003686 SDValue Mask = getValue(I.getArgOperand(3));
3687 EVT VT = Src0.getValueType();
3688 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3689 if (!Alignment)
3690 Alignment = DAG.getEVTAlignment(VT);
3691
3692 AAMDNodes AAInfo;
3693 I.getAAMetadata(AAInfo);
3694
3695 MachineMemOperand *MMO =
3696 DAG.getMachineFunction().
3697 getMachineMemOperand(MachinePointerInfo(PtrOperand),
3698 MachineMemOperand::MOStore, VT.getStoreSize(),
3699 Alignment, AAInfo);
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00003700 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
3701 MMO, false);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00003702 DAG.setRoot(StoreNode);
3703 setValue(&I, StoreNode);
3704}
3705
3706void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I) {
3707 SDLoc sdl = getCurSDLoc();
3708
Elena Demikhovskyfb81b932014-12-25 07:49:20 +00003709 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00003710 Value *PtrOperand = I.getArgOperand(0);
3711 SDValue Ptr = getValue(PtrOperand);
Elena Demikhovskyfb81b932014-12-25 07:49:20 +00003712 SDValue Src0 = getValue(I.getArgOperand(3));
3713 SDValue Mask = getValue(I.getArgOperand(2));
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00003714
3715 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3716 EVT VT = TLI.getValueType(I.getType());
Elena Demikhovskyfb81b932014-12-25 07:49:20 +00003717 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00003718 if (!Alignment)
3719 Alignment = DAG.getEVTAlignment(VT);
3720
3721 AAMDNodes AAInfo;
3722 I.getAAMetadata(AAInfo);
3723 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3724
3725 SDValue InChain = DAG.getRoot();
3726 if (AA->pointsToConstantMemory(
3727 AliasAnalysis::Location(PtrOperand,
3728 AA->getTypeStoreSize(I.getType()),
3729 AAInfo))) {
3730 // Do not serialize (non-volatile) loads of constant memory with anything.
3731 InChain = DAG.getEntryNode();
3732 }
3733
3734 MachineMemOperand *MMO =
3735 DAG.getMachineFunction().
3736 getMachineMemOperand(MachinePointerInfo(PtrOperand),
3737 MachineMemOperand::MOLoad, VT.getStoreSize(),
3738 Alignment, AAInfo, Ranges);
3739
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00003740 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
3741 ISD::NON_EXTLOAD);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00003742 SDValue OutChain = Load.getValue(1);
3743 DAG.setRoot(OutChain);
3744 setValue(&I, Load);
3745}
3746
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003747void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003748 SDLoc dl = getCurSDLoc();
Tim Northovere94a5182014-03-11 10:48:52 +00003749 AtomicOrdering SuccessOrder = I.getSuccessOrdering();
3750 AtomicOrdering FailureOrder = I.getFailureOrdering();
Eli Friedman342e8df2011-08-24 20:50:09 +00003751 SynchronizationScope Scope = I.getSynchScope();
Eli Friedman30a49e92011-08-03 21:06:02 +00003752
3753 SDValue InChain = getRoot();
3754
Tim Northover420a2162014-06-13 14:24:07 +00003755 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
3756 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
3757 SDValue L = DAG.getAtomicCmpSwap(
3758 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
3759 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
3760 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
Robin Morissete2de06b2014-10-16 20:34:57 +00003761 /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope);
Eli Friedman30a49e92011-08-03 21:06:02 +00003762
Tim Northover420a2162014-06-13 14:24:07 +00003763 SDValue OutChain = L.getValue(2);
Eli Friedman30a49e92011-08-03 21:06:02 +00003764
Eli Friedmanadec5872011-07-29 03:05:32 +00003765 setValue(&I, L);
Eli Friedman30a49e92011-08-03 21:06:02 +00003766 DAG.setRoot(OutChain);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003767}
3768
3769void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003770 SDLoc dl = getCurSDLoc();
Eli Friedmanadec5872011-07-29 03:05:32 +00003771 ISD::NodeType NT;
3772 switch (I.getOperation()) {
David Blaikie46a9f012012-01-20 21:51:11 +00003773 default: llvm_unreachable("Unknown atomicrmw operation");
Eli Friedmanadec5872011-07-29 03:05:32 +00003774 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3775 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
3776 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
3777 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
3778 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3779 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
3780 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
3781 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
3782 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
3783 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3784 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3785 }
Eli Friedman30a49e92011-08-03 21:06:02 +00003786 AtomicOrdering Order = I.getOrdering();
Eli Friedman342e8df2011-08-24 20:50:09 +00003787 SynchronizationScope Scope = I.getSynchScope();
Eli Friedman30a49e92011-08-03 21:06:02 +00003788
3789 SDValue InChain = getRoot();
3790
Robin Morissete2de06b2014-10-16 20:34:57 +00003791 SDValue L =
3792 DAG.getAtomic(NT, dl,
3793 getValue(I.getValOperand()).getSimpleValueType(),
3794 InChain,
3795 getValue(I.getPointerOperand()),
3796 getValue(I.getValOperand()),
3797 I.getPointerOperand(),
3798 /* Alignment=*/ 0, Order, Scope);
Eli Friedman30a49e92011-08-03 21:06:02 +00003799
3800 SDValue OutChain = L.getValue(1);
3801
Eli Friedmanadec5872011-07-29 03:05:32 +00003802 setValue(&I, L);
Eli Friedman30a49e92011-08-03 21:06:02 +00003803 DAG.setRoot(OutChain);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003804}
3805
Eli Friedmanfee02c62011-07-25 23:16:38 +00003806void SelectionDAGBuilder::visitFence(const FenceInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003807 SDLoc dl = getCurSDLoc();
Eric Christopher58a24612014-10-08 09:50:54 +00003808 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Eli Friedman26a48482011-07-27 22:21:52 +00003809 SDValue Ops[3];
3810 Ops[0] = getRoot();
Eric Christopher58a24612014-10-08 09:50:54 +00003811 Ops[1] = DAG.getConstant(I.getOrdering(), TLI.getPointerTy());
3812 Ops[2] = DAG.getConstant(I.getSynchScope(), TLI.getPointerTy());
Craig Topper48d114b2014-04-26 18:35:24 +00003813 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
Eli Friedmanfee02c62011-07-25 23:16:38 +00003814}
3815
Eli Friedman342e8df2011-08-24 20:50:09 +00003816void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003817 SDLoc dl = getCurSDLoc();
Eli Friedman342e8df2011-08-24 20:50:09 +00003818 AtomicOrdering Order = I.getOrdering();
3819 SynchronizationScope Scope = I.getSynchScope();
3820
3821 SDValue InChain = getRoot();
3822
Eric Christopher58a24612014-10-08 09:50:54 +00003823 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3824 EVT VT = TLI.getValueType(I.getType());
Eli Friedman342e8df2011-08-24 20:50:09 +00003825
Evan Chenga72b9702013-02-06 02:06:33 +00003826 if (I.getAlignment() < VT.getSizeInBits() / 8)
Eli Friedmanf1518212011-09-13 20:50:54 +00003827 report_fatal_error("Cannot generate unaligned atomic load");
3828
Nick Lewyckyaad475b2014-04-15 07:22:52 +00003829 MachineMemOperand *MMO =
3830 DAG.getMachineFunction().
3831 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
3832 MachineMemOperand::MOVolatile |
3833 MachineMemOperand::MOLoad,
3834 VT.getStoreSize(),
3835 I.getAlignment() ? I.getAlignment() :
3836 DAG.getEVTAlignment(VT));
3837
Eric Christopher58a24612014-10-08 09:50:54 +00003838 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
Robin Morissete2de06b2014-10-16 20:34:57 +00003839 SDValue L =
3840 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3841 getValue(I.getPointerOperand()), MMO,
3842 Order, Scope);
Eli Friedman342e8df2011-08-24 20:50:09 +00003843
3844 SDValue OutChain = L.getValue(1);
3845
Eli Friedman342e8df2011-08-24 20:50:09 +00003846 setValue(&I, L);
3847 DAG.setRoot(OutChain);
3848}
3849
3850void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003851 SDLoc dl = getCurSDLoc();
Eli Friedman342e8df2011-08-24 20:50:09 +00003852
3853 AtomicOrdering Order = I.getOrdering();
3854 SynchronizationScope Scope = I.getSynchScope();
3855
3856 SDValue InChain = getRoot();
3857
Eric Christopher58a24612014-10-08 09:50:54 +00003858 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3859 EVT VT = TLI.getValueType(I.getValueOperand()->getType());
Eli Friedmanf1518212011-09-13 20:50:54 +00003860
Evan Chenga72b9702013-02-06 02:06:33 +00003861 if (I.getAlignment() < VT.getSizeInBits() / 8)
Eli Friedmanf1518212011-09-13 20:50:54 +00003862 report_fatal_error("Cannot generate unaligned atomic store");
3863
Robin Morissete2de06b2014-10-16 20:34:57 +00003864 SDValue OutChain =
3865 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
3866 InChain,
3867 getValue(I.getPointerOperand()),
3868 getValue(I.getValueOperand()),
3869 I.getPointerOperand(), I.getAlignment(),
3870 Order, Scope);
Eli Friedman342e8df2011-08-24 20:50:09 +00003871
3872 DAG.setRoot(OutChain);
3873}
3874
Dan Gohman575fad32008-09-03 16:12:24 +00003875/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3876/// node.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003877void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00003878 unsigned Intrinsic) {
Dan Gohman575fad32008-09-03 16:12:24 +00003879 bool HasChain = !I.doesNotAccessMemory();
3880 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3881
3882 // Build the operand list.
3883 SmallVector<SDValue, 8> Ops;
3884 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3885 if (OnlyLoad) {
3886 // We don't need to serialize loads against other loads.
3887 Ops.push_back(DAG.getRoot());
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003888 } else {
Dan Gohman575fad32008-09-03 16:12:24 +00003889 Ops.push_back(getRoot());
3890 }
3891 }
Mon P Wang769134b2008-11-01 20:24:53 +00003892
3893 // Info is set by getTgtMemInstrinsic
3894 TargetLowering::IntrinsicInfo Info;
Eric Christopher58a24612014-10-08 09:50:54 +00003895 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3896 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
Mon P Wang769134b2008-11-01 20:24:53 +00003897
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003898 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Bob Wilson5549d492010-09-21 17:56:22 +00003899 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3900 Info.opc == ISD::INTRINSIC_W_CHAIN)
Eric Christopher58a24612014-10-08 09:50:54 +00003901 Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohman575fad32008-09-03 16:12:24 +00003902
3903 // Add all operands of the call to the operand list.
Gabor Greifeba0be72010-06-25 09:38:13 +00003904 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3905 SDValue Op = getValue(I.getArgOperand(i));
Dan Gohman575fad32008-09-03 16:12:24 +00003906 Ops.push_back(Op);
3907 }
3908
Owen Anderson53aa7a92009-08-10 22:56:29 +00003909 SmallVector<EVT, 4> ValueVTs;
Eric Christopher58a24612014-10-08 09:50:54 +00003910 ComputeValueVTs(TLI, I.getType(), ValueVTs);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003911
Dan Gohman575fad32008-09-03 16:12:24 +00003912 if (HasChain)
Owen Anderson9f944592009-08-11 20:47:22 +00003913 ValueVTs.push_back(MVT::Other);
Dan Gohman575fad32008-09-03 16:12:24 +00003914
Craig Topperabb4ac72014-04-16 06:10:51 +00003915 SDVTList VTs = DAG.getVTList(ValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00003916
3917 // Create the node.
3918 SDValue Result;
Mon P Wang769134b2008-11-01 20:24:53 +00003919 if (IsTgtIntrinsic) {
3920 // This is target intrinsic that touches memory
Andrew Trickef9de2a2013-05-25 02:42:55 +00003921 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
Craig Topper206fcd42014-04-26 19:29:41 +00003922 VTs, Ops, Info.memVT,
Chris Lattnerd2d58ad2010-09-21 04:57:15 +00003923 MachinePointerInfo(Info.ptrVal, Info.offset),
Mon P Wang769134b2008-11-01 20:24:53 +00003924 Info.align, Info.vol,
Hal Finkel46ef7ce2014-08-13 01:15:40 +00003925 Info.readMem, Info.writeMem, Info.size);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003926 } else if (!HasChain) {
Craig Topper48d114b2014-04-26 18:35:24 +00003927 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00003928 } else if (!I.getType()->isVoidTy()) {
Craig Topper48d114b2014-04-26 18:35:24 +00003929 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003930 } else {
Craig Topper48d114b2014-04-26 18:35:24 +00003931 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003932 }
3933
Dan Gohman575fad32008-09-03 16:12:24 +00003934 if (HasChain) {
3935 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3936 if (OnlyLoad)
3937 PendingLoads.push_back(Chain);
3938 else
3939 DAG.setRoot(Chain);
3940 }
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003941
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00003942 if (!I.getType()->isVoidTy()) {
Chris Lattner229907c2011-07-18 04:54:35 +00003943 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Eric Christopher58a24612014-10-08 09:50:54 +00003944 EVT VT = TLI.getValueType(PTy);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003945 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003946 }
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003947
Dan Gohman575fad32008-09-03 16:12:24 +00003948 setValue(&I, Result);
3949 }
3950}
3951
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003952/// GetSignificand - Get the significand and build it into a floating-point
3953/// number with exponent of 1:
3954///
3955/// Op = (Op & 0x007fffff) | 0x3f800000;
3956///
Matt Beaumont-Gay0e760da2013-02-25 18:11:18 +00003957/// where Op is the hexadecimal representation of floating point value.
Bill Wendlinged3bb782008-09-09 20:39:27 +00003958static SDValue
Andrew Trickef9de2a2013-05-25 02:42:55 +00003959GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
Owen Anderson9f944592009-08-11 20:47:22 +00003960 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3961 DAG.getConstant(0x007fffff, MVT::i32));
3962 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3963 DAG.getConstant(0x3f800000, MVT::i32));
Wesley Peck527da1b2010-11-23 03:31:01 +00003964 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
Bill Wendlinged3bb782008-09-09 20:39:27 +00003965}
3966
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003967/// GetExponent - Get the exponent:
3968///
Bill Wendling23959162009-01-20 21:17:57 +00003969/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003970///
Matt Beaumont-Gay0e760da2013-02-25 18:11:18 +00003971/// where Op is the hexadecimal representation of floating point value.
Bill Wendlinged3bb782008-09-09 20:39:27 +00003972static SDValue
Dale Johannesendb7c5f62009-01-31 02:22:37 +00003973GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
Andrew Trickef9de2a2013-05-25 02:42:55 +00003974 SDLoc dl) {
Owen Anderson9f944592009-08-11 20:47:22 +00003975 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3976 DAG.getConstant(0x7f800000, MVT::i32));
3977 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands41826032009-01-31 15:50:11 +00003978 DAG.getConstant(23, TLI.getPointerTy()));
Owen Anderson9f944592009-08-11 20:47:22 +00003979 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3980 DAG.getConstant(127, MVT::i32));
Bill Wendling954cb182010-01-28 21:51:40 +00003981 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendlinged3bb782008-09-09 20:39:27 +00003982}
3983
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003984/// getF32Constant - Get 32-bit floating point constant.
3985static SDValue
3986getF32Constant(SelectionDAG &DAG, unsigned Flt) {
Tim Northover29178a32013-01-22 09:46:31 +00003987 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)),
3988 MVT::f32);
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003989}
3990
Benjamin Kramerfb0abce2015-03-05 21:13:08 +00003991static SDValue getLimitedPrecisionExp2(SDValue t0, SDLoc dl,
3992 SelectionDAG &DAG) {
3993 // IntegerPartOfX = ((int32_t)(t0);
3994 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3995
3996 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
3997 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3998 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3999
4000 // IntegerPartOfX <<= 23;
4001 IntegerPartOfX = DAG.getNode(
4002 ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4003 DAG.getConstant(23, DAG.getTargetLoweringInfo().getPointerTy()));
4004
4005 SDValue TwoToFractionalPartOfX;
4006 if (LimitFloatPrecision <= 6) {
4007 // For floating-point precision of 6:
4008 //
4009 // TwoToFractionalPartOfX =
4010 // 0.997535578f +
4011 // (0.735607626f + 0.252464424f * x) * x;
4012 //
4013 // error 0.0144103317, which is 6 bits
4014 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4015 getF32Constant(DAG, 0x3e814304));
4016 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4017 getF32Constant(DAG, 0x3f3c50c8));
4018 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4019 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4020 getF32Constant(DAG, 0x3f7f5e7e));
4021 } else if (LimitFloatPrecision <= 12) {
4022 // For floating-point precision of 12:
4023 //
4024 // TwoToFractionalPartOfX =
4025 // 0.999892986f +
4026 // (0.696457318f +
4027 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4028 //
4029 // error 0.000107046256, which is 13 to 14 bits
4030 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4031 getF32Constant(DAG, 0x3da235e3));
4032 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4033 getF32Constant(DAG, 0x3e65b8f3));
4034 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4035 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4036 getF32Constant(DAG, 0x3f324b07));
4037 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4038 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4039 getF32Constant(DAG, 0x3f7ff8fd));
4040 } else { // LimitFloatPrecision <= 18
4041 // For floating-point precision of 18:
4042 //
4043 // TwoToFractionalPartOfX =
4044 // 0.999999982f +
4045 // (0.693148872f +
4046 // (0.240227044f +
4047 // (0.554906021e-1f +
4048 // (0.961591928e-2f +
4049 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4050 // error 2.47208000*10^(-7), which is better than 18 bits
4051 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4052 getF32Constant(DAG, 0x3924b03e));
4053 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4054 getF32Constant(DAG, 0x3ab24b87));
4055 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4056 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4057 getF32Constant(DAG, 0x3c1d8c17));
4058 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4059 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4060 getF32Constant(DAG, 0x3d634a1d));
4061 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4062 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4063 getF32Constant(DAG, 0x3e75fe14));
4064 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4065 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4066 getF32Constant(DAG, 0x3f317234));
4067 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4068 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4069 getF32Constant(DAG, 0x3f800000));
4070 }
4071
4072 // Add the exponent into the result in integer domain.
4073 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4074 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4075 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4076}
4077
Craig Topperd2638c12012-11-24 18:52:06 +00004078/// expandExp - Lower an exp intrinsic. Handles the special sequences for
Bill Wendling48217d82008-09-09 22:13:54 +00004079/// limited-precision mode.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004080static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topperd2638c12012-11-24 18:52:06 +00004081 const TargetLowering &TLI) {
4082 if (Op.getValueType() == MVT::f32 &&
Bill Wendling48217d82008-09-09 22:13:54 +00004083 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Bill Wendling48217d82008-09-09 22:13:54 +00004084
4085 // Put the exponent in the right bit position for later addition to the
4086 // final result:
4087 //
4088 // #define LOG2OFe 1.4426950f
Benjamin Kramerfb0abce2015-03-05 21:13:08 +00004089 // t0 = Op * LOG2OFe
Owen Anderson9f944592009-08-11 20:47:22 +00004090 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004091 getF32Constant(DAG, 0x3fb8aa3b));
Benjamin Kramerfb0abce2015-03-05 21:13:08 +00004092 return getLimitedPrecisionExp2(t0, dl, DAG);
Bill Wendling48217d82008-09-09 22:13:54 +00004093 }
4094
Craig Topperd2638c12012-11-24 18:52:06 +00004095 // No special expansion.
4096 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
Dale Johannesen520143e2008-09-05 18:38:42 +00004097}
4098
Craig Topperbef254a2012-11-23 18:38:31 +00004099/// expandLog - Lower a log intrinsic. Handles the special sequences for
Bill Wendlinged3bb782008-09-09 20:39:27 +00004100/// limited-precision mode.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004101static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topperbef254a2012-11-23 18:38:31 +00004102 const TargetLowering &TLI) {
4103 if (Op.getValueType() == MVT::f32 &&
Bill Wendlinged3bb782008-09-09 20:39:27 +00004104 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Wesley Peck527da1b2010-11-23 03:31:01 +00004105 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendlinged3bb782008-09-09 20:39:27 +00004106
4107 // Scale the exponent by log(2) [0.69314718f].
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004108 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson9f944592009-08-11 20:47:22 +00004109 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004110 getF32Constant(DAG, 0x3f317218));
Bill Wendlinged3bb782008-09-09 20:39:27 +00004111
4112 // Get the significand and build it into a floating-point number with
4113 // exponent of 1.
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004114 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendlinged3bb782008-09-09 20:39:27 +00004115
Craig Topper3669de42012-11-16 19:08:44 +00004116 SDValue LogOfMantissa;
Bill Wendlinged3bb782008-09-09 20:39:27 +00004117 if (LimitFloatPrecision <= 6) {
4118 // For floating-point precision of 6:
4119 //
4120 // LogofMantissa =
4121 // -1.1609546f +
4122 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004123 //
Bill Wendlinged3bb782008-09-09 20:39:27 +00004124 // error 0.0034276066, which is better than 8 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004125 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004126 getF32Constant(DAG, 0xbe74c456));
Owen Anderson9f944592009-08-11 20:47:22 +00004127 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004128 getF32Constant(DAG, 0x3fb3a2b1));
Owen Anderson9f944592009-08-11 20:47:22 +00004129 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topper3669de42012-11-16 19:08:44 +00004130 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4131 getF32Constant(DAG, 0x3f949a29));
Craig Toppered756c52012-11-16 20:01:39 +00004132 } else if (LimitFloatPrecision <= 12) {
Bill Wendlinged3bb782008-09-09 20:39:27 +00004133 // For floating-point precision of 12:
4134 //
4135 // LogOfMantissa =
4136 // -1.7417939f +
4137 // (2.8212026f +
4138 // (-1.4699568f +
4139 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4140 //
4141 // error 0.000061011436, which is 14 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004142 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004143 getF32Constant(DAG, 0xbd67b6d6));
Owen Anderson9f944592009-08-11 20:47:22 +00004144 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004145 getF32Constant(DAG, 0x3ee4f4b8));
Owen Anderson9f944592009-08-11 20:47:22 +00004146 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4147 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004148 getF32Constant(DAG, 0x3fbc278b));
Owen Anderson9f944592009-08-11 20:47:22 +00004149 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4150 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004151 getF32Constant(DAG, 0x40348e95));
Owen Anderson9f944592009-08-11 20:47:22 +00004152 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topper3669de42012-11-16 19:08:44 +00004153 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4154 getF32Constant(DAG, 0x3fdef31a));
Craig Toppered756c52012-11-16 20:01:39 +00004155 } else { // LimitFloatPrecision <= 18
Bill Wendlinged3bb782008-09-09 20:39:27 +00004156 // For floating-point precision of 18:
4157 //
4158 // LogOfMantissa =
4159 // -2.1072184f +
4160 // (4.2372794f +
4161 // (-3.7029485f +
4162 // (2.2781945f +
4163 // (-0.87823314f +
4164 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4165 //
4166 // error 0.0000023660568, which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004167 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004168 getF32Constant(DAG, 0xbc91e5ac));
Owen Anderson9f944592009-08-11 20:47:22 +00004169 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004170 getF32Constant(DAG, 0x3e4350aa));
Owen Anderson9f944592009-08-11 20:47:22 +00004171 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4172 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004173 getF32Constant(DAG, 0x3f60d3e3));
Owen Anderson9f944592009-08-11 20:47:22 +00004174 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4175 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004176 getF32Constant(DAG, 0x4011cdf0));
Owen Anderson9f944592009-08-11 20:47:22 +00004177 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4178 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004179 getF32Constant(DAG, 0x406cfd1c));
Owen Anderson9f944592009-08-11 20:47:22 +00004180 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4181 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004182 getF32Constant(DAG, 0x408797cb));
Owen Anderson9f944592009-08-11 20:47:22 +00004183 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
Craig Topper3669de42012-11-16 19:08:44 +00004184 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4185 getF32Constant(DAG, 0x4006dcab));
Bill Wendlinged3bb782008-09-09 20:39:27 +00004186 }
Craig Topper3669de42012-11-16 19:08:44 +00004187
Craig Topperbef254a2012-11-23 18:38:31 +00004188 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendlinged3bb782008-09-09 20:39:27 +00004189 }
4190
Craig Topperbef254a2012-11-23 18:38:31 +00004191 // No special expansion.
4192 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
Dale Johannesen520143e2008-09-05 18:38:42 +00004193}
4194
Craig Topperbef254a2012-11-23 18:38:31 +00004195/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
Bill Wendling48416782008-09-09 00:28:24 +00004196/// limited-precision mode.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004197static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topperbef254a2012-11-23 18:38:31 +00004198 const TargetLowering &TLI) {
4199 if (Op.getValueType() == MVT::f32 &&
Bill Wendling48416782008-09-09 00:28:24 +00004200 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Wesley Peck527da1b2010-11-23 03:31:01 +00004201 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendling48416782008-09-09 00:28:24 +00004202
Bill Wendlinged3bb782008-09-09 20:39:27 +00004203 // Get the exponent.
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004204 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00004205
Bill Wendling48416782008-09-09 00:28:24 +00004206 // Get the significand and build it into a floating-point number with
Bill Wendlinged3bb782008-09-09 20:39:27 +00004207 // exponent of 1.
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004208 SDValue X = GetSignificand(DAG, Op1, dl);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004209
Bill Wendling48416782008-09-09 00:28:24 +00004210 // Different possible minimax approximations of significand in
4211 // floating-point for various degrees of accuracy over [1,2].
Craig Topper3669de42012-11-16 19:08:44 +00004212 SDValue Log2ofMantissa;
Bill Wendling48416782008-09-09 00:28:24 +00004213 if (LimitFloatPrecision <= 6) {
4214 // For floating-point precision of 6:
4215 //
4216 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4217 //
4218 // error 0.0049451742, which is more than 7 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004219 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004220 getF32Constant(DAG, 0xbeb08fe0));
Owen Anderson9f944592009-08-11 20:47:22 +00004221 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004222 getF32Constant(DAG, 0x40019463));
Owen Anderson9f944592009-08-11 20:47:22 +00004223 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topper3669de42012-11-16 19:08:44 +00004224 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4225 getF32Constant(DAG, 0x3fd6633d));
Craig Toppered756c52012-11-16 20:01:39 +00004226 } else if (LimitFloatPrecision <= 12) {
Bill Wendling48416782008-09-09 00:28:24 +00004227 // For floating-point precision of 12:
4228 //
4229 // Log2ofMantissa =
4230 // -2.51285454f +
4231 // (4.07009056f +
4232 // (-2.12067489f +
4233 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004234 //
Bill Wendling48416782008-09-09 00:28:24 +00004235 // error 0.0000876136000, which is better than 13 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004236 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004237 getF32Constant(DAG, 0xbda7262e));
Owen Anderson9f944592009-08-11 20:47:22 +00004238 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004239 getF32Constant(DAG, 0x3f25280b));
Owen Anderson9f944592009-08-11 20:47:22 +00004240 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4241 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004242 getF32Constant(DAG, 0x4007b923));
Owen Anderson9f944592009-08-11 20:47:22 +00004243 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4244 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004245 getF32Constant(DAG, 0x40823e2f));
Owen Anderson9f944592009-08-11 20:47:22 +00004246 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topper3669de42012-11-16 19:08:44 +00004247 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4248 getF32Constant(DAG, 0x4020d29c));
Craig Toppered756c52012-11-16 20:01:39 +00004249 } else { // LimitFloatPrecision <= 18
Bill Wendling48416782008-09-09 00:28:24 +00004250 // For floating-point precision of 18:
4251 //
4252 // Log2ofMantissa =
4253 // -3.0400495f +
4254 // (6.1129976f +
4255 // (-5.3420409f +
4256 // (3.2865683f +
4257 // (-1.2669343f +
4258 // (0.27515199f -
4259 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4260 //
4261 // error 0.0000018516, which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004262 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004263 getF32Constant(DAG, 0xbcd2769e));
Owen Anderson9f944592009-08-11 20:47:22 +00004264 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004265 getF32Constant(DAG, 0x3e8ce0b9));
Owen Anderson9f944592009-08-11 20:47:22 +00004266 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4267 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004268 getF32Constant(DAG, 0x3fa22ae7));
Owen Anderson9f944592009-08-11 20:47:22 +00004269 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4270 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004271 getF32Constant(DAG, 0x40525723));
Owen Anderson9f944592009-08-11 20:47:22 +00004272 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4273 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004274 getF32Constant(DAG, 0x40aaf200));
Owen Anderson9f944592009-08-11 20:47:22 +00004275 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4276 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004277 getF32Constant(DAG, 0x40c39dad));
Owen Anderson9f944592009-08-11 20:47:22 +00004278 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
Craig Topper3669de42012-11-16 19:08:44 +00004279 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4280 getF32Constant(DAG, 0x4042902c));
Bill Wendling48416782008-09-09 00:28:24 +00004281 }
Craig Topper3669de42012-11-16 19:08:44 +00004282
Craig Topperbef254a2012-11-23 18:38:31 +00004283 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
Dale Johannesen36d532a2008-09-05 23:49:37 +00004284 }
Bill Wendling48416782008-09-09 00:28:24 +00004285
Craig Topperbef254a2012-11-23 18:38:31 +00004286 // No special expansion.
4287 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
Dale Johannesen520143e2008-09-05 18:38:42 +00004288}
4289
Craig Topperbef254a2012-11-23 18:38:31 +00004290/// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
Bill Wendling48416782008-09-09 00:28:24 +00004291/// limited-precision mode.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004292static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topperbef254a2012-11-23 18:38:31 +00004293 const TargetLowering &TLI) {
4294 if (Op.getValueType() == MVT::f32 &&
Bill Wendling48416782008-09-09 00:28:24 +00004295 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Wesley Peck527da1b2010-11-23 03:31:01 +00004296 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendling48416782008-09-09 00:28:24 +00004297
Bill Wendlinged3bb782008-09-09 20:39:27 +00004298 // Scale the exponent by log10(2) [0.30102999f].
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004299 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson9f944592009-08-11 20:47:22 +00004300 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004301 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling48416782008-09-09 00:28:24 +00004302
4303 // Get the significand and build it into a floating-point number with
Bill Wendlinged3bb782008-09-09 20:39:27 +00004304 // exponent of 1.
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004305 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling48416782008-09-09 00:28:24 +00004306
Craig Topper3669de42012-11-16 19:08:44 +00004307 SDValue Log10ofMantissa;
Bill Wendling48416782008-09-09 00:28:24 +00004308 if (LimitFloatPrecision <= 6) {
Bill Wendlingfaeb4b62008-09-09 18:42:23 +00004309 // For floating-point precision of 6:
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004310 //
Bill Wendlingfaeb4b62008-09-09 18:42:23 +00004311 // Log10ofMantissa =
4312 // -0.50419619f +
4313 // (0.60948995f - 0.10380950f * x) * x;
4314 //
4315 // error 0.0014886165, which is 6 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004316 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004317 getF32Constant(DAG, 0xbdd49a13));
Owen Anderson9f944592009-08-11 20:47:22 +00004318 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004319 getF32Constant(DAG, 0x3f1c0789));
Owen Anderson9f944592009-08-11 20:47:22 +00004320 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topper3669de42012-11-16 19:08:44 +00004321 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4322 getF32Constant(DAG, 0x3f011300));
Craig Toppered756c52012-11-16 20:01:39 +00004323 } else if (LimitFloatPrecision <= 12) {
Bill Wendling48416782008-09-09 00:28:24 +00004324 // For floating-point precision of 12:
4325 //
4326 // Log10ofMantissa =
4327 // -0.64831180f +
4328 // (0.91751397f +
4329 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4330 //
4331 // error 0.00019228036, which is better than 12 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004332 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004333 getF32Constant(DAG, 0x3d431f31));
Owen Anderson9f944592009-08-11 20:47:22 +00004334 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004335 getF32Constant(DAG, 0x3ea21fb2));
Owen Anderson9f944592009-08-11 20:47:22 +00004336 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4337 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004338 getF32Constant(DAG, 0x3f6ae232));
Owen Anderson9f944592009-08-11 20:47:22 +00004339 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topper3669de42012-11-16 19:08:44 +00004340 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4341 getF32Constant(DAG, 0x3f25f7c3));
Craig Toppered756c52012-11-16 20:01:39 +00004342 } else { // LimitFloatPrecision <= 18
Bill Wendlingfaeb4b62008-09-09 18:42:23 +00004343 // For floating-point precision of 18:
4344 //
4345 // Log10ofMantissa =
4346 // -0.84299375f +
4347 // (1.5327582f +
4348 // (-1.0688956f +
4349 // (0.49102474f +
4350 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4351 //
4352 // error 0.0000037995730, which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004353 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004354 getF32Constant(DAG, 0x3c5d51ce));
Owen Anderson9f944592009-08-11 20:47:22 +00004355 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004356 getF32Constant(DAG, 0x3e00685a));
Owen Anderson9f944592009-08-11 20:47:22 +00004357 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4358 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004359 getF32Constant(DAG, 0x3efb6798));
Owen Anderson9f944592009-08-11 20:47:22 +00004360 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4361 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004362 getF32Constant(DAG, 0x3f88d192));
Owen Anderson9f944592009-08-11 20:47:22 +00004363 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4364 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004365 getF32Constant(DAG, 0x3fc4316c));
Owen Anderson9f944592009-08-11 20:47:22 +00004366 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
Craig Topper3669de42012-11-16 19:08:44 +00004367 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4368 getF32Constant(DAG, 0x3f57ce70));
Bill Wendling48416782008-09-09 00:28:24 +00004369 }
Craig Topper3669de42012-11-16 19:08:44 +00004370
Craig Topperbef254a2012-11-23 18:38:31 +00004371 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
Dale Johannesend4dac0e2008-09-05 21:27:19 +00004372 }
Bill Wendling48416782008-09-09 00:28:24 +00004373
Craig Topperbef254a2012-11-23 18:38:31 +00004374 // No special expansion.
4375 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
Dale Johannesen520143e2008-09-05 18:38:42 +00004376}
4377
Craig Topperd2638c12012-11-24 18:52:06 +00004378/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
Bill Wendlingab6676a2008-09-09 22:39:21 +00004379/// limited-precision mode.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004380static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topperd2638c12012-11-24 18:52:06 +00004381 const TargetLowering &TLI) {
4382 if (Op.getValueType() == MVT::f32 &&
Benjamin Kramerfb0abce2015-03-05 21:13:08 +00004383 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
4384 return getLimitedPrecisionExp2(Op, dl, DAG);
Bill Wendlingab6676a2008-09-09 22:39:21 +00004385
Craig Topperd2638c12012-11-24 18:52:06 +00004386 // No special expansion.
4387 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
Dale Johannesenf2a52bb2008-09-05 01:48:15 +00004388}
4389
Bill Wendling648930b2008-09-10 00:20:20 +00004390/// visitPow - Lower a pow intrinsic. Handles the special sequences for
4391/// limited-precision mode with x == 10.0f.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004392static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
Craig Topper79bd2052012-11-25 08:08:58 +00004393 SelectionDAG &DAG, const TargetLowering &TLI) {
Bill Wendling648930b2008-09-10 00:20:20 +00004394 bool IsExp10 = false;
Benjamin Kramer671a5962013-12-11 16:36:09 +00004395 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
Bill Wendling648930b2008-09-10 00:20:20 +00004396 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Craig Topper79bd2052012-11-25 08:08:58 +00004397 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4398 APFloat Ten(10.0f);
4399 IsExp10 = LHSC->isExactlyValue(Ten);
Bill Wendling648930b2008-09-10 00:20:20 +00004400 }
4401 }
4402
Craig Topper268b6222012-11-25 00:48:58 +00004403 if (IsExp10) {
Bill Wendling648930b2008-09-10 00:20:20 +00004404 // Put the exponent in the right bit position for later addition to the
4405 // final result:
4406 //
4407 // #define LOG2OF10 3.3219281f
Benjamin Kramerfb0abce2015-03-05 21:13:08 +00004408 // t0 = Op * LOG2OF10;
Craig Topper79bd2052012-11-25 08:08:58 +00004409 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004410 getF32Constant(DAG, 0x40549a78));
Benjamin Kramerfb0abce2015-03-05 21:13:08 +00004411 return getLimitedPrecisionExp2(t0, dl, DAG);
Bill Wendling648930b2008-09-10 00:20:20 +00004412 }
4413
Craig Topper79bd2052012-11-25 08:08:58 +00004414 // No special expansion.
4415 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
Bill Wendling648930b2008-09-10 00:20:20 +00004416}
4417
Chris Lattner39f18e52010-01-01 03:32:16 +00004418
4419/// ExpandPowI - Expand a llvm.powi intrinsic.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004420static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
Chris Lattner39f18e52010-01-01 03:32:16 +00004421 SelectionDAG &DAG) {
4422 // If RHS is a constant, we can expand this out to a multiplication tree,
4423 // otherwise we end up lowering to a call to __powidf2 (for example). When
4424 // optimizing for size, we only want to do this if the expansion would produce
4425 // a small number of multiplies, otherwise we do the full expansion.
4426 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4427 // Get the exponent as a positive value.
4428 unsigned Val = RHSC->getSExtValue();
4429 if ((int)Val < 0) Val = -Val;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00004430
Chris Lattner39f18e52010-01-01 03:32:16 +00004431 // powi(x, 0) -> 1.0
4432 if (Val == 0)
4433 return DAG.getConstantFP(1.0, LHS.getValueType());
4434
Dan Gohman913c9982010-04-15 04:33:49 +00004435 const Function *F = DAG.getMachineFunction().getFunction();
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +00004436 if (!F->hasFnAttribute(Attribute::OptimizeForSize) ||
Chris Lattner39f18e52010-01-01 03:32:16 +00004437 // If optimizing for size, don't insert too many multiplies. This
4438 // inserts up to 5 multiplies.
Benjamin Kramer5f6a9072015-02-12 15:35:40 +00004439 countPopulation(Val) + Log2_32(Val) < 7) {
Chris Lattner39f18e52010-01-01 03:32:16 +00004440 // We use the simple binary decomposition method to generate the multiply
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00004441 // sequence. There are more optimal ways to do this (for example,
Chris Lattner39f18e52010-01-01 03:32:16 +00004442 // powi(x,15) generates one more multiply than it should), but this has
4443 // the benefit of being both really simple and much better than a libcall.
4444 SDValue Res; // Logically starts equal to 1.0
4445 SDValue CurSquare = LHS;
4446 while (Val) {
Mikhail Glushenkov5c35d2f2010-01-01 04:41:36 +00004447 if (Val & 1) {
Chris Lattner39f18e52010-01-01 03:32:16 +00004448 if (Res.getNode())
4449 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4450 else
4451 Res = CurSquare; // 1.0*CurSquare.
Mikhail Glushenkov5c35d2f2010-01-01 04:41:36 +00004452 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00004453
Chris Lattner39f18e52010-01-01 03:32:16 +00004454 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4455 CurSquare, CurSquare);
4456 Val >>= 1;
4457 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00004458
Chris Lattner39f18e52010-01-01 03:32:16 +00004459 // If the original was negative, invert the result, producing 1/(x*x*x).
4460 if (RHSC->getSExtValue() < 0)
4461 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4462 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4463 return Res;
4464 }
4465 }
4466
4467 // Otherwise, expand to a libcall.
4468 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4469}
4470
Devang Patel8e60ff12011-05-16 21:24:05 +00004471// getTruncatedArgReg - Find underlying register used for an truncated
4472// argument.
4473static unsigned getTruncatedArgReg(const SDValue &N) {
4474 if (N.getOpcode() != ISD::TRUNCATE)
4475 return 0;
4476
4477 const SDValue &Ext = N.getOperand(0);
Stephen Lin6d715e82013-07-06 21:44:25 +00004478 if (Ext.getOpcode() == ISD::AssertZext ||
4479 Ext.getOpcode() == ISD::AssertSext) {
Devang Patel8e60ff12011-05-16 21:24:05 +00004480 const SDValue &CFR = Ext.getOperand(0);
4481 if (CFR.getOpcode() == ISD::CopyFromReg)
4482 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
Craig Topper692d5842012-04-11 04:55:51 +00004483 if (CFR.getOpcode() == ISD::TRUNCATE)
4484 return getTruncatedArgReg(CFR);
Devang Patel8e60ff12011-05-16 21:24:05 +00004485 }
4486 return 0;
4487}
4488
Evan Cheng6e822452010-04-28 23:08:54 +00004489/// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4490/// argument, create the corresponding DBG_VALUE machine instruction for it now.
4491/// At the end of instruction selection, they will be inserted to the entry BB.
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004492bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V,
4493 MDNode *Variable,
4494 MDNode *Expr, int64_t Offset,
4495 bool IsIndirect,
4496 const SDValue &N) {
Devang Patel86ec8b32010-08-31 22:22:42 +00004497 const Argument *Arg = dyn_cast<Argument>(V);
4498 if (!Arg)
Evan Cheng5fb45a22010-04-29 01:40:30 +00004499 return false;
Evan Cheng6e822452010-04-28 23:08:54 +00004500
Devang Patel03955532010-04-29 20:40:36 +00004501 MachineFunction &MF = DAG.getMachineFunction();
Eric Christopherfc6de422014-08-05 02:39:49 +00004502 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
Devang Patel94f2a252010-11-02 17:01:30 +00004503
Devang Patela46953d2010-04-29 18:50:36 +00004504 // Ignore inlined function arguments here.
4505 DIVariable DV(Variable);
Devang Patel03955532010-04-29 20:40:36 +00004506 if (DV.isInlinedFnArgument(MF.getFunction()))
Devang Patela46953d2010-04-29 18:50:36 +00004507 return false;
4508
David Blaikie0252265b2013-06-16 20:34:15 +00004509 Optional<MachineOperand> Op;
Devang Patel9d904e12011-09-08 22:59:09 +00004510 // Some arguments' frame index is recorded during argument lowering.
David Blaikie0252265b2013-06-16 20:34:15 +00004511 if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
4512 Op = MachineOperand::CreateFI(FI);
Devang Patel86ec8b32010-08-31 22:22:42 +00004513
David Blaikie0252265b2013-06-16 20:34:15 +00004514 if (!Op && N.getNode()) {
4515 unsigned Reg;
Devang Patel8e60ff12011-05-16 21:24:05 +00004516 if (N.getOpcode() == ISD::CopyFromReg)
4517 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4518 else
4519 Reg = getTruncatedArgReg(N);
4520 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
Evan Cheng6e822452010-04-28 23:08:54 +00004521 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4522 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4523 if (PR)
4524 Reg = PR;
4525 }
David Blaikie0252265b2013-06-16 20:34:15 +00004526 if (Reg)
4527 Op = MachineOperand::CreateReg(Reg, false);
Evan Cheng6e822452010-04-28 23:08:54 +00004528 }
4529
David Blaikie0252265b2013-06-16 20:34:15 +00004530 if (!Op) {
Devang Patel94f2a252010-11-02 17:01:30 +00004531 // Check if ValueMap has reg number.
Evan Cheng923679f2010-04-29 06:33:38 +00004532 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
Devang Patelbc741402010-11-02 17:19:03 +00004533 if (VMI != FuncInfo.ValueMap.end())
David Blaikie0252265b2013-06-16 20:34:15 +00004534 Op = MachineOperand::CreateReg(VMI->second, false);
Evan Cheng923679f2010-04-29 06:33:38 +00004535 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004536
David Blaikie0252265b2013-06-16 20:34:15 +00004537 if (!Op && N.getNode())
Devang Patel94f2a252010-11-02 17:01:30 +00004538 // Check if frame index is available.
4539 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
Wesley Peck527da1b2010-11-23 03:31:01 +00004540 if (FrameIndexSDNode *FINode =
David Blaikie0252265b2013-06-16 20:34:15 +00004541 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4542 Op = MachineOperand::CreateFI(FINode->getIndex());
Devang Patelbc741402010-11-02 17:19:03 +00004543
David Blaikie0252265b2013-06-16 20:34:15 +00004544 if (!Op)
Devang Patelbc741402010-11-02 17:19:03 +00004545 return false;
Devang Patel94f2a252010-11-02 17:01:30 +00004546
David Blaikie0252265b2013-06-16 20:34:15 +00004547 if (Op->isReg())
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004548 FuncInfo.ArgDbgValues.push_back(
4549 BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE),
4550 IsIndirect, Op->getReg(), Offset, Variable, Expr));
Adrian Prantl418d1d12013-07-09 20:28:37 +00004551 else
4552 FuncInfo.ArgDbgValues.push_back(
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004553 BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE))
4554 .addOperand(*Op)
4555 .addImm(Offset)
4556 .addMetadata(Variable)
4557 .addMetadata(Expr));
Adrian Prantl418d1d12013-07-09 20:28:37 +00004558
Evan Cheng5fb45a22010-04-29 01:40:30 +00004559 return true;
Evan Cheng6e822452010-04-28 23:08:54 +00004560}
Chris Lattner39f18e52010-01-01 03:32:16 +00004561
Douglas Gregor6739a892010-05-11 06:17:44 +00004562// VisualStudio defines setjmp as _setjmp
Michael J. Spencerded5f662010-09-24 19:48:47 +00004563#if defined(_MSC_VER) && defined(setjmp) && \
4564 !defined(setjmp_undefined_for_msvc)
4565# pragma push_macro("setjmp")
4566# undef setjmp
4567# define setjmp_undefined_for_msvc
Douglas Gregor6739a892010-05-11 06:17:44 +00004568#endif
4569
Dan Gohman575fad32008-09-03 16:12:24 +00004570/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4571/// we want to emit this as a call to a named external function, return the name
4572/// otherwise lower it and return null.
4573const char *
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004574SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
Eric Christopher58a24612014-10-08 09:50:54 +00004575 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004576 SDLoc sdl = getCurSDLoc();
Dale Johannesendb7c5f62009-01-31 02:22:37 +00004577 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb99b2692009-12-22 00:40:51 +00004578 SDValue Res;
4579
Dan Gohman575fad32008-09-03 16:12:24 +00004580 switch (Intrinsic) {
4581 default:
4582 // By default, turn this into a target intrinsic node.
4583 visitTargetIntrinsic(I, Intrinsic);
Craig Topperc0196b12014-04-14 00:51:57 +00004584 return nullptr;
4585 case Intrinsic::vastart: visitVAStart(I); return nullptr;
4586 case Intrinsic::vaend: visitVAEnd(I); return nullptr;
4587 case Intrinsic::vacopy: visitVACopy(I); return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00004588 case Intrinsic::returnaddress:
Eric Christopher58a24612014-10-08 09:50:54 +00004589 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI.getPointerTy(),
Gabor Greifeba0be72010-06-25 09:38:13 +00004590 getValue(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00004591 return nullptr;
Bill Wendlingc966a732008-09-26 22:10:44 +00004592 case Intrinsic::frameaddress:
Eric Christopher58a24612014-10-08 09:50:54 +00004593 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI.getPointerTy(),
Gabor Greifeba0be72010-06-25 09:38:13 +00004594 getValue(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00004595 return nullptr;
Renato Golinc7aea402014-05-06 16:51:25 +00004596 case Intrinsic::read_register: {
4597 Value *Reg = I.getArgOperand(0);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004598 SDValue RegName =
4599 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
Eric Christopher58a24612014-10-08 09:50:54 +00004600 EVT VT = TLI.getValueType(I.getType());
Renato Golinc7aea402014-05-06 16:51:25 +00004601 setValue(&I, DAG.getNode(ISD::READ_REGISTER, sdl, VT, RegName));
4602 return nullptr;
4603 }
4604 case Intrinsic::write_register: {
4605 Value *Reg = I.getArgOperand(0);
4606 Value *RegValue = I.getArgOperand(1);
4607 SDValue Chain = getValue(RegValue).getOperand(0);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004608 SDValue RegName =
4609 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
Renato Golinc7aea402014-05-06 16:51:25 +00004610 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
4611 RegName, getValue(RegValue)));
4612 return nullptr;
4613 }
Dan Gohman575fad32008-09-03 16:12:24 +00004614 case Intrinsic::setjmp:
Eric Christopher58a24612014-10-08 09:50:54 +00004615 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
Dan Gohman575fad32008-09-03 16:12:24 +00004616 case Intrinsic::longjmp:
Eric Christopher58a24612014-10-08 09:50:54 +00004617 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
Chris Lattnerdd708342008-11-21 16:42:48 +00004618 case Intrinsic::memcpy: {
Manuel Jacob8220add2015-01-27 13:14:35 +00004619 // FIXME: this definition of "user defined address space" is x86-specific
Mon P Wangc576ee92010-04-04 03:10:48 +00004620 // Assert for address < 256 since we support only user defined address
4621 // spaces.
Gabor Greifeba0be72010-06-25 09:38:13 +00004622 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wangc576ee92010-04-04 03:10:48 +00004623 < 256 &&
Gabor Greifeba0be72010-06-25 09:38:13 +00004624 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
Mon P Wangc576ee92010-04-04 03:10:48 +00004625 < 256 &&
4626 "Unknown address space");
Gabor Greifeba0be72010-06-25 09:38:13 +00004627 SDValue Op1 = getValue(I.getArgOperand(0));
4628 SDValue Op2 = getValue(I.getArgOperand(1));
4629 SDValue Op3 = getValue(I.getArgOperand(2));
4630 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
Chandler Carruth05920b182013-02-25 14:20:21 +00004631 if (!Align)
4632 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
Gabor Greifeba0be72010-06-25 09:38:13 +00004633 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004634 DAG.setRoot(DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, false,
Chris Lattner2510de22010-09-21 05:40:29 +00004635 MachinePointerInfo(I.getArgOperand(0)),
4636 MachinePointerInfo(I.getArgOperand(1))));
Craig Topperc0196b12014-04-14 00:51:57 +00004637 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00004638 }
Chris Lattnerdd708342008-11-21 16:42:48 +00004639 case Intrinsic::memset: {
Manuel Jacob8220add2015-01-27 13:14:35 +00004640 // FIXME: this definition of "user defined address space" is x86-specific
Mon P Wangc576ee92010-04-04 03:10:48 +00004641 // Assert for address < 256 since we support only user defined address
4642 // spaces.
Gabor Greifeba0be72010-06-25 09:38:13 +00004643 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wangc576ee92010-04-04 03:10:48 +00004644 < 256 &&
4645 "Unknown address space");
Gabor Greifeba0be72010-06-25 09:38:13 +00004646 SDValue Op1 = getValue(I.getArgOperand(0));
4647 SDValue Op2 = getValue(I.getArgOperand(1));
4648 SDValue Op3 = getValue(I.getArgOperand(2));
4649 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
Chandler Carruth05920b182013-02-25 14:20:21 +00004650 if (!Align)
4651 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
Gabor Greifeba0be72010-06-25 09:38:13 +00004652 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004653 DAG.setRoot(DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
Chris Lattner2510de22010-09-21 05:40:29 +00004654 MachinePointerInfo(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00004655 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00004656 }
Chris Lattnerdd708342008-11-21 16:42:48 +00004657 case Intrinsic::memmove: {
Manuel Jacob8220add2015-01-27 13:14:35 +00004658 // FIXME: this definition of "user defined address space" is x86-specific
Mon P Wangc576ee92010-04-04 03:10:48 +00004659 // Assert for address < 256 since we support only user defined address
4660 // spaces.
Gabor Greifeba0be72010-06-25 09:38:13 +00004661 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wangc576ee92010-04-04 03:10:48 +00004662 < 256 &&
Gabor Greifeba0be72010-06-25 09:38:13 +00004663 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
Mon P Wangc576ee92010-04-04 03:10:48 +00004664 < 256 &&
4665 "Unknown address space");
Gabor Greifeba0be72010-06-25 09:38:13 +00004666 SDValue Op1 = getValue(I.getArgOperand(0));
4667 SDValue Op2 = getValue(I.getArgOperand(1));
4668 SDValue Op3 = getValue(I.getArgOperand(2));
4669 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
Chandler Carruth05920b182013-02-25 14:20:21 +00004670 if (!Align)
4671 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
Gabor Greifeba0be72010-06-25 09:38:13 +00004672 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004673 DAG.setRoot(DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
Chris Lattner2510de22010-09-21 05:40:29 +00004674 MachinePointerInfo(I.getArgOperand(0)),
4675 MachinePointerInfo(I.getArgOperand(1))));
Craig Topperc0196b12014-04-14 00:51:57 +00004676 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00004677 }
Bill Wendling65c0fd42009-02-13 02:16:35 +00004678 case Intrinsic::dbg_declare: {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004679 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Devang Pateldf45c7f2009-10-09 22:42:28 +00004680 MDNode *Variable = DI.getVariable();
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004681 MDNode *Expression = DI.getExpression();
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004682 const Value *Address = DI.getAddress();
Manman Ren983a16c2013-06-28 05:43:10 +00004683 DIVariable DIVar(Variable);
4684 assert((!DIVar || DIVar.isVariable()) &&
4685 "Variable in DbgDeclareInst should be either null or a DIVariable.");
4686 if (!Address || !DIVar) {
Eric Christopherbe7a1012012-03-15 21:33:41 +00004687 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00004688 return nullptr;
Eric Christopherbe7a1012012-03-15 21:33:41 +00004689 }
Dale Johannesene0983522010-04-26 20:06:49 +00004690
Devang Patel3bffd522010-09-02 21:29:42 +00004691 // Check if address has undef value.
4692 if (isa<UndefValue>(Address) ||
4693 (Address->use_empty() && !isa<Argument>(Address))) {
Eric Christopher5c452052012-02-23 03:39:39 +00004694 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00004695 return nullptr;
Devang Patel3bffd522010-09-02 21:29:42 +00004696 }
4697
Dale Johannesene0983522010-04-26 20:06:49 +00004698 SDValue &N = NodeMap[Address];
Devang Patel86ec8b32010-08-31 22:22:42 +00004699 if (!N.getNode() && isa<Argument>(Address))
4700 // Check unused arguments map.
4701 N = UnusedArgNodeMap[Address];
Dale Johannesene0983522010-04-26 20:06:49 +00004702 SDDbgValue *SDV;
4703 if (N.getNode()) {
Devang Patel98d3edf2010-09-02 21:02:27 +00004704 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4705 Address = BCI->getOperand(0);
Eric Christopherda970542012-02-24 01:59:08 +00004706 // Parameters are handled specially.
4707 bool isParameter =
4708 (DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable ||
4709 isa<Argument>(Address));
4710
Devang Patel98d3edf2010-09-02 21:02:27 +00004711 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4712
Dale Johannesene0983522010-04-26 20:06:49 +00004713 if (isParameter && !AI) {
4714 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4715 if (FINode)
4716 // Byval parameter. We have a frame index at this point.
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004717 SDV = DAG.getFrameIndexDbgValue(
4718 Variable, Expression, FINode->getIndex(), 0, dl, SDNodeOrder);
Devang Patelc24048a2010-12-06 22:39:26 +00004719 else {
Devang Patel8e60ff12011-05-16 21:24:05 +00004720 // Address is an argument, so try to emit its dbg value using
4721 // virtual register info from the FuncInfo.ValueMap.
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004722 EmitFuncArgumentDbgValue(Address, Variable, Expression, 0, false, N);
Craig Topperc0196b12014-04-14 00:51:57 +00004723 return nullptr;
Devang Patelc24048a2010-12-06 22:39:26 +00004724 }
Dale Johannesene0983522010-04-26 20:06:49 +00004725 } else if (AI)
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004726 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
Adrian Prantl32da8892014-04-25 20:49:25 +00004727 true, 0, dl, SDNodeOrder);
Devang Patelc24048a2010-12-06 22:39:26 +00004728 else {
Dale Johannesene0983522010-04-26 20:06:49 +00004729 // Can't do anything with other non-AI cases yet.
Eric Christopher5c452052012-02-23 03:39:39 +00004730 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Eric Christopherda970542012-02-24 01:59:08 +00004731 DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
4732 DEBUG(Address->dump());
Craig Topperc0196b12014-04-14 00:51:57 +00004733 return nullptr;
Devang Patelc24048a2010-12-06 22:39:26 +00004734 }
Dale Johannesene0983522010-04-26 20:06:49 +00004735 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4736 } else {
Gabor Greif47a3b8c2010-10-01 10:32:19 +00004737 // If Address is an argument then try to emit its dbg value using
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00004738 // virtual register info from the FuncInfo.ValueMap.
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004739 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, 0, false,
4740 N)) {
Devang Patelda25de82010-09-15 14:48:53 +00004741 // If variable is pinned by a alloca in dominating bb then
4742 // use StaticAllocaMap.
4743 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
Devang Patel46b96c42010-09-15 18:13:55 +00004744 if (AI->getParent() != DI.getParent()) {
4745 DenseMap<const AllocaInst*, int>::iterator SI =
4746 FuncInfo.StaticAllocaMap.find(AI);
4747 if (SI != FuncInfo.StaticAllocaMap.end()) {
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004748 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second,
Adrian Prantl32da8892014-04-25 20:49:25 +00004749 0, dl, SDNodeOrder);
Craig Topperc0196b12014-04-14 00:51:57 +00004750 DAG.AddDbgValue(SDV, nullptr, false);
4751 return nullptr;
Devang Patel46b96c42010-09-15 18:13:55 +00004752 }
Devang Patelda25de82010-09-15 14:48:53 +00004753 }
4754 }
Eric Christopher18c6be72012-02-23 03:39:43 +00004755 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Devang Patelea134f52010-08-26 22:53:27 +00004756 }
Dale Johannesene0983522010-04-26 20:06:49 +00004757 }
Craig Topperc0196b12014-04-14 00:51:57 +00004758 return nullptr;
Bill Wendling65c0fd42009-02-13 02:16:35 +00004759 }
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004760 case Intrinsic::dbg_value: {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004761 const DbgValueInst &DI = cast<DbgValueInst>(I);
Manman Ren983a16c2013-06-28 05:43:10 +00004762 DIVariable DIVar(DI.getVariable());
4763 assert((!DIVar || DIVar.isVariable()) &&
4764 "Variable in DbgValueInst should be either null or a DIVariable.");
4765 if (!DIVar)
Craig Topperc0196b12014-04-14 00:51:57 +00004766 return nullptr;
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004767
4768 MDNode *Variable = DI.getVariable();
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004769 MDNode *Expression = DI.getExpression();
Devang Patelf2bce7c2010-03-15 19:15:44 +00004770 uint64_t Offset = DI.getOffset();
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004771 const Value *V = DI.getValue();
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004772 if (!V)
Craig Topperc0196b12014-04-14 00:51:57 +00004773 return nullptr;
Devang Patelf2bce7c2010-03-15 19:15:44 +00004774
Dale Johannesene0983522010-04-26 20:06:49 +00004775 SDDbgValue *SDV;
Devang Patelaab841c2011-08-03 23:13:55 +00004776 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004777 SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl,
4778 SDNodeOrder);
Craig Topperc0196b12014-04-14 00:51:57 +00004779 DAG.AddDbgValue(SDV, nullptr, false);
Devang Patelf2bce7c2010-03-15 19:15:44 +00004780 } else {
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00004781 // Do not use getValue() in here; we don't want to generate code at
4782 // this point if it hasn't been done yet.
Devang Patelb0c76392010-06-01 19:59:01 +00004783 SDValue N = NodeMap[V];
4784 if (!N.getNode() && isa<Argument>(V))
4785 // Check unused arguments map.
4786 N = UnusedArgNodeMap[V];
Dale Johannesene0983522010-04-26 20:06:49 +00004787 if (N.getNode()) {
Adrian Prantl32da8892014-04-25 20:49:25 +00004788 // A dbg.value for an alloca is always indirect.
4789 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004790 if (!EmitFuncArgumentDbgValue(V, Variable, Expression, Offset,
4791 IsIndirect, N)) {
4792 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4793 IsIndirect, Offset, dl, SDNodeOrder);
Evan Cheng5fb45a22010-04-29 01:40:30 +00004794 DAG.AddDbgValue(SDV, N.getNode(), false);
4795 }
Devang Patelb7ae3cc2011-02-18 22:43:42 +00004796 } else if (!V->use_empty() ) {
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00004797 // Do not call getValue(V) yet, as we don't want to generate code.
4798 // Remember it for later.
4799 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4800 DanglingDebugInfoMap[V] = DDI;
Devang Patelf2855b12010-08-27 22:25:51 +00004801 } else {
Devang Patelf2bce7c2010-03-15 19:15:44 +00004802 // We may expand this to cover more cases. One case where we have no
Devang Patelc24048a2010-12-06 22:39:26 +00004803 // data available is an unreferenced parameter.
Eric Christopher18c6be72012-02-23 03:39:43 +00004804 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Dale Johannesene0983522010-04-26 20:06:49 +00004805 }
Devang Patelf2bce7c2010-03-15 19:15:44 +00004806 }
4807
4808 // Build a debug info table entry.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004809 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004810 V = BCI->getOperand(0);
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004811 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004812 // Don't handle byval struct arguments or VLAs, for example.
Eric Christopherc1e2dcd2012-03-26 06:10:32 +00004813 if (!AI) {
Eric Christopher24a62982012-03-28 07:34:36 +00004814 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
4815 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00004816 return nullptr;
Eric Christopherc1e2dcd2012-03-26 06:10:32 +00004817 }
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004818 DenseMap<const AllocaInst*, int>::iterator SI =
4819 FuncInfo.StaticAllocaMap.find(AI);
4820 if (SI == FuncInfo.StaticAllocaMap.end())
Craig Topperc0196b12014-04-14 00:51:57 +00004821 return nullptr; // VLAs.
Craig Topperc0196b12014-04-14 00:51:57 +00004822 return nullptr;
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004823 }
Dan Gohman575fad32008-09-03 16:12:24 +00004824
Duncan Sands8e6ccb62009-10-14 16:11:37 +00004825 case Intrinsic::eh_typeid_for: {
Chris Lattnerfb964e52010-04-05 06:19:28 +00004826 // Find the type id for the given typeinfo.
Reid Kleckner283bc2e2014-11-14 00:35:50 +00004827 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
Chris Lattnerfb964e52010-04-05 06:19:28 +00004828 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4829 Res = DAG.getConstant(TypeID, MVT::i32);
Bill Wendlingb99b2692009-12-22 00:40:51 +00004830 setValue(&I, Res);
Craig Topperc0196b12014-04-14 00:51:57 +00004831 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00004832 }
4833
Anton Korobeynikov45165ed2008-09-08 21:13:56 +00004834 case Intrinsic::eh_return_i32:
4835 case Intrinsic::eh_return_i64:
Chris Lattnerfb964e52010-04-05 06:19:28 +00004836 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004837 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
Chris Lattnerfb964e52010-04-05 06:19:28 +00004838 MVT::Other,
4839 getControlRoot(),
Gabor Greifeba0be72010-06-25 09:38:13 +00004840 getValue(I.getArgOperand(0)),
4841 getValue(I.getArgOperand(1))));
Craig Topperc0196b12014-04-14 00:51:57 +00004842 return nullptr;
Anton Korobeynikov45165ed2008-09-08 21:13:56 +00004843 case Intrinsic::eh_unwind_init:
Chris Lattnerfb964e52010-04-05 06:19:28 +00004844 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
Craig Topperc0196b12014-04-14 00:51:57 +00004845 return nullptr;
Anton Korobeynikov45165ed2008-09-08 21:13:56 +00004846 case Intrinsic::eh_dwarf_cfa: {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004847 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
Eric Christopher58a24612014-10-08 09:50:54 +00004848 TLI.getPointerTy());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004849 SDValue Offset = DAG.getNode(ISD::ADD, sdl,
Tom Stellard838e2342013-08-26 15:06:10 +00004850 CfaArg.getValueType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004851 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
Tom Stellard838e2342013-08-26 15:06:10 +00004852 CfaArg.getValueType()),
Anton Korobeynikov45165ed2008-09-08 21:13:56 +00004853 CfaArg);
Eric Christopher58a24612014-10-08 09:50:54 +00004854 SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl, TLI.getPointerTy(),
4855 DAG.getConstant(0, TLI.getPointerTy()));
Tom Stellard838e2342013-08-26 15:06:10 +00004856 setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
Bill Wendling954cb182010-01-28 21:51:40 +00004857 FA, Offset));
Craig Topperc0196b12014-04-14 00:51:57 +00004858 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00004859 }
Jim Grosbach54c05302010-01-28 01:45:32 +00004860 case Intrinsic::eh_sjlj_callsite: {
Chris Lattnerfb964e52010-04-05 06:19:28 +00004861 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Gabor Greifeba0be72010-06-25 09:38:13 +00004862 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
Jim Grosbach54c05302010-01-28 01:45:32 +00004863 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
Chris Lattnerfb964e52010-04-05 06:19:28 +00004864 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
Jim Grosbach54c05302010-01-28 01:45:32 +00004865
Chris Lattnerfb964e52010-04-05 06:19:28 +00004866 MMI.setCurrentCallSite(CI->getZExtValue());
Craig Topperc0196b12014-04-14 00:51:57 +00004867 return nullptr;
Jim Grosbach54c05302010-01-28 01:45:32 +00004868 }
Bill Wendling66b110f2011-09-28 03:36:43 +00004869 case Intrinsic::eh_sjlj_functioncontext: {
4870 // Get and store the index of the function context.
4871 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
Bill Wendlingbaf39412011-09-28 03:52:41 +00004872 AllocaInst *FnCtx =
4873 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
Bill Wendling66b110f2011-09-28 03:36:43 +00004874 int FI = FuncInfo.StaticAllocaMap[FnCtx];
4875 MFI->setFunctionContextIndex(FI);
Craig Topperc0196b12014-04-14 00:51:57 +00004876 return nullptr;
Bill Wendling66b110f2011-09-28 03:36:43 +00004877 }
Jim Grosbachc98892f2010-05-26 20:22:18 +00004878 case Intrinsic::eh_sjlj_setjmp: {
Bill Wendling7ecfbd92011-10-07 21:25:38 +00004879 SDValue Ops[2];
4880 Ops[0] = getRoot();
4881 Ops[1] = getValue(I.getArgOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004882 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
Craig Topper48d114b2014-04-26 18:35:24 +00004883 DAG.getVTList(MVT::i32, MVT::Other), Ops);
Bill Wendling7ecfbd92011-10-07 21:25:38 +00004884 setValue(&I, Op.getValue(0));
4885 DAG.setRoot(Op.getValue(1));
Craig Topperc0196b12014-04-14 00:51:57 +00004886 return nullptr;
Jim Grosbachc98892f2010-05-26 20:22:18 +00004887 }
Jim Grosbachbd9485d2010-05-22 01:06:18 +00004888 case Intrinsic::eh_sjlj_longjmp: {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004889 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
Jim Grosbachbbdc5d22010-10-19 23:27:08 +00004890 getRoot(), getValue(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00004891 return nullptr;
Jim Grosbachbbdc5d22010-10-19 23:27:08 +00004892 }
Jim Grosbach54c05302010-01-28 01:45:32 +00004893
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00004894 case Intrinsic::masked_load:
4895 visitMaskedLoad(I);
4896 return nullptr;
4897 case Intrinsic::masked_store:
4898 visitMaskedStore(I);
4899 return nullptr;
Dale Johannesendd224d22010-09-30 23:57:10 +00004900 case Intrinsic::x86_mmx_pslli_w:
4901 case Intrinsic::x86_mmx_pslli_d:
4902 case Intrinsic::x86_mmx_pslli_q:
4903 case Intrinsic::x86_mmx_psrli_w:
4904 case Intrinsic::x86_mmx_psrli_d:
4905 case Intrinsic::x86_mmx_psrli_q:
4906 case Intrinsic::x86_mmx_psrai_w:
4907 case Intrinsic::x86_mmx_psrai_d: {
4908 SDValue ShAmt = getValue(I.getArgOperand(1));
4909 if (isa<ConstantSDNode>(ShAmt)) {
4910 visitTargetIntrinsic(I, Intrinsic);
Craig Topperc0196b12014-04-14 00:51:57 +00004911 return nullptr;
Dale Johannesendd224d22010-09-30 23:57:10 +00004912 }
4913 unsigned NewIntrinsic = 0;
4914 EVT ShAmtVT = MVT::v2i32;
4915 switch (Intrinsic) {
4916 case Intrinsic::x86_mmx_pslli_w:
4917 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4918 break;
4919 case Intrinsic::x86_mmx_pslli_d:
4920 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4921 break;
4922 case Intrinsic::x86_mmx_pslli_q:
4923 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4924 break;
4925 case Intrinsic::x86_mmx_psrli_w:
4926 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4927 break;
4928 case Intrinsic::x86_mmx_psrli_d:
4929 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4930 break;
4931 case Intrinsic::x86_mmx_psrli_q:
4932 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4933 break;
4934 case Intrinsic::x86_mmx_psrai_w:
4935 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4936 break;
4937 case Intrinsic::x86_mmx_psrai_d:
4938 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4939 break;
4940 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4941 }
4942
4943 // The vector shift intrinsics with scalars uses 32b shift amounts but
4944 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4945 // to be zero.
4946 // We must do this early because v2i32 is not a legal type.
Dale Johannesendd224d22010-09-30 23:57:10 +00004947 SDValue ShOps[2];
4948 ShOps[0] = ShAmt;
4949 ShOps[1] = DAG.getConstant(0, MVT::i32);
Craig Topper48d114b2014-04-26 18:35:24 +00004950 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps);
Eric Christopher58a24612014-10-08 09:50:54 +00004951 EVT DestVT = TLI.getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004952 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
4953 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
Dale Johannesendd224d22010-09-30 23:57:10 +00004954 DAG.getConstant(NewIntrinsic, MVT::i32),
4955 getValue(I.getArgOperand(0)), ShAmt);
4956 setValue(&I, Res);
Craig Topperc0196b12014-04-14 00:51:57 +00004957 return nullptr;
Dale Johannesendd224d22010-09-30 23:57:10 +00004958 }
Pete Cooper682c76b2012-02-24 03:51:49 +00004959 case Intrinsic::x86_avx_vinsertf128_pd_256:
4960 case Intrinsic::x86_avx_vinsertf128_ps_256:
Craig Topperd024cef2012-04-07 22:32:29 +00004961 case Intrinsic::x86_avx_vinsertf128_si_256:
4962 case Intrinsic::x86_avx2_vinserti128: {
Eric Christopher58a24612014-10-08 09:50:54 +00004963 EVT DestVT = TLI.getValueType(I.getType());
4964 EVT ElVT = TLI.getValueType(I.getArgOperand(1)->getType());
Pete Cooper682c76b2012-02-24 03:51:49 +00004965 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue() & 1) *
4966 ElVT.getVectorNumElements();
Eric Christopher58a24612014-10-08 09:50:54 +00004967 Res =
4968 DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, DestVT,
4969 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
4970 DAG.getConstant(Idx, TLI.getVectorIdxTy()));
Craig Topper2db23532012-09-05 05:48:09 +00004971 setValue(&I, Res);
Craig Topperc0196b12014-04-14 00:51:57 +00004972 return nullptr;
Craig Topper2db23532012-09-05 05:48:09 +00004973 }
4974 case Intrinsic::x86_avx_vextractf128_pd_256:
4975 case Intrinsic::x86_avx_vextractf128_ps_256:
4976 case Intrinsic::x86_avx_vextractf128_si_256:
4977 case Intrinsic::x86_avx2_vextracti128: {
Eric Christopher58a24612014-10-08 09:50:54 +00004978 EVT DestVT = TLI.getValueType(I.getType());
Craig Topper2db23532012-09-05 05:48:09 +00004979 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(1))->getZExtValue() & 1) *
4980 DestVT.getVectorNumElements();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004981 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, DestVT,
Craig Topper2db23532012-09-05 05:48:09 +00004982 getValue(I.getArgOperand(0)),
Eric Christopher58a24612014-10-08 09:50:54 +00004983 DAG.getConstant(Idx, TLI.getVectorIdxTy()));
Pete Cooper682c76b2012-02-24 03:51:49 +00004984 setValue(&I, Res);
Craig Topperc0196b12014-04-14 00:51:57 +00004985 return nullptr;
Pete Cooper682c76b2012-02-24 03:51:49 +00004986 }
Mon P Wang58fb9132008-11-10 20:54:11 +00004987 case Intrinsic::convertff:
4988 case Intrinsic::convertfsi:
4989 case Intrinsic::convertfui:
4990 case Intrinsic::convertsif:
4991 case Intrinsic::convertuif:
4992 case Intrinsic::convertss:
4993 case Intrinsic::convertsu:
4994 case Intrinsic::convertus:
4995 case Intrinsic::convertuu: {
4996 ISD::CvtCode Code = ISD::CVT_INVALID;
4997 switch (Intrinsic) {
Craig Topperbc680062012-04-11 04:34:11 +00004998 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
Mon P Wang58fb9132008-11-10 20:54:11 +00004999 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
5000 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
5001 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
5002 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
5003 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
5004 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
5005 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
5006 case Intrinsic::convertus: Code = ISD::CVT_US; break;
5007 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
5008 }
Eric Christopher58a24612014-10-08 09:50:54 +00005009 EVT DestVT = TLI.getValueType(I.getType());
Gabor Greifeba0be72010-06-25 09:38:13 +00005010 const Value *Op1 = I.getArgOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005011 Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
Bill Wendlingb99b2692009-12-22 00:40:51 +00005012 DAG.getValueType(DestVT),
5013 DAG.getValueType(getValue(Op1).getValueType()),
Gabor Greifeba0be72010-06-25 09:38:13 +00005014 getValue(I.getArgOperand(1)),
5015 getValue(I.getArgOperand(2)),
Bill Wendlingb99b2692009-12-22 00:40:51 +00005016 Code);
5017 setValue(&I, Res);
Craig Topperc0196b12014-04-14 00:51:57 +00005018 return nullptr;
Mon P Wang58fb9132008-11-10 20:54:11 +00005019 }
Dan Gohman575fad32008-09-03 16:12:24 +00005020 case Intrinsic::powi:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005021 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
Gabor Greifeba0be72010-06-25 09:38:13 +00005022 getValue(I.getArgOperand(1)), DAG));
Craig Topperc0196b12014-04-14 00:51:57 +00005023 return nullptr;
Dale Johannesenda2d8062008-09-04 00:47:13 +00005024 case Intrinsic::log:
Eric Christopher58a24612014-10-08 09:50:54 +00005025 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
Craig Topperc0196b12014-04-14 00:51:57 +00005026 return nullptr;
Dale Johannesenda2d8062008-09-04 00:47:13 +00005027 case Intrinsic::log2:
Eric Christopher58a24612014-10-08 09:50:54 +00005028 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
Craig Topperc0196b12014-04-14 00:51:57 +00005029 return nullptr;
Dale Johannesenda2d8062008-09-04 00:47:13 +00005030 case Intrinsic::log10:
Eric Christopher58a24612014-10-08 09:50:54 +00005031 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
Craig Topperc0196b12014-04-14 00:51:57 +00005032 return nullptr;
Dale Johannesenda2d8062008-09-04 00:47:13 +00005033 case Intrinsic::exp:
Eric Christopher58a24612014-10-08 09:50:54 +00005034 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
Craig Topperc0196b12014-04-14 00:51:57 +00005035 return nullptr;
Dale Johannesenda2d8062008-09-04 00:47:13 +00005036 case Intrinsic::exp2:
Eric Christopher58a24612014-10-08 09:50:54 +00005037 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
Craig Topperc0196b12014-04-14 00:51:57 +00005038 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005039 case Intrinsic::pow:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005040 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
Eric Christopher58a24612014-10-08 09:50:54 +00005041 getValue(I.getArgOperand(1)), DAG, TLI));
Craig Topperc0196b12014-04-14 00:51:57 +00005042 return nullptr;
Craig Topperae894262012-11-16 07:48:23 +00005043 case Intrinsic::sqrt:
Peter Collingbourne913869b2012-05-28 21:48:37 +00005044 case Intrinsic::fabs:
Craig Topperae894262012-11-16 07:48:23 +00005045 case Intrinsic::sin:
5046 case Intrinsic::cos:
Dan Gohman0b3d7822012-07-26 17:43:27 +00005047 case Intrinsic::floor:
Craig Topper61d04572012-11-15 06:51:10 +00005048 case Intrinsic::ceil:
Craig Topper61d04572012-11-15 06:51:10 +00005049 case Intrinsic::trunc:
Craig Topper61d04572012-11-15 06:51:10 +00005050 case Intrinsic::rint:
Hal Finkel171817e2013-08-07 22:49:12 +00005051 case Intrinsic::nearbyint:
5052 case Intrinsic::round: {
Craig Topperae894262012-11-16 07:48:23 +00005053 unsigned Opcode;
5054 switch (Intrinsic) {
5055 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5056 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
5057 case Intrinsic::fabs: Opcode = ISD::FABS; break;
5058 case Intrinsic::sin: Opcode = ISD::FSIN; break;
5059 case Intrinsic::cos: Opcode = ISD::FCOS; break;
5060 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
5061 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
5062 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
5063 case Intrinsic::rint: Opcode = ISD::FRINT; break;
5064 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
Hal Finkel171817e2013-08-07 22:49:12 +00005065 case Intrinsic::round: Opcode = ISD::FROUND; break;
Craig Topperae894262012-11-16 07:48:23 +00005066 }
5067
Andrew Trickef9de2a2013-05-25 02:42:55 +00005068 setValue(&I, DAG.getNode(Opcode, sdl,
Craig Topper61d04572012-11-15 06:51:10 +00005069 getValue(I.getArgOperand(0)).getValueType(),
5070 getValue(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00005071 return nullptr;
Craig Topperae894262012-11-16 07:48:23 +00005072 }
Matt Arsenault7c936902014-10-21 23:01:01 +00005073 case Intrinsic::minnum:
5074 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
5075 getValue(I.getArgOperand(0)).getValueType(),
5076 getValue(I.getArgOperand(0)),
5077 getValue(I.getArgOperand(1))));
5078 return nullptr;
5079 case Intrinsic::maxnum:
5080 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
5081 getValue(I.getArgOperand(0)).getValueType(),
5082 getValue(I.getArgOperand(0)),
5083 getValue(I.getArgOperand(1))));
5084 return nullptr;
Hal Finkel0c5c01aa2013-08-19 23:35:46 +00005085 case Intrinsic::copysign:
5086 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5087 getValue(I.getArgOperand(0)).getValueType(),
5088 getValue(I.getArgOperand(0)),
5089 getValue(I.getArgOperand(1))));
Craig Topperc0196b12014-04-14 00:51:57 +00005090 return nullptr;
Cameron Zwarichf03fa182011-07-08 21:39:21 +00005091 case Intrinsic::fma:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005092 setValue(&I, DAG.getNode(ISD::FMA, sdl,
Cameron Zwarichf03fa182011-07-08 21:39:21 +00005093 getValue(I.getArgOperand(0)).getValueType(),
5094 getValue(I.getArgOperand(0)),
5095 getValue(I.getArgOperand(1)),
5096 getValue(I.getArgOperand(2))));
Craig Topperc0196b12014-04-14 00:51:57 +00005097 return nullptr;
Lang Hamesa59100c2012-06-05 19:07:46 +00005098 case Intrinsic::fmuladd: {
Eric Christopher58a24612014-10-08 09:50:54 +00005099 EVT VT = TLI.getValueType(I.getType());
Lang Hamesb8650f12012-06-22 01:09:09 +00005100 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
Eric Christopher58a24612014-10-08 09:50:54 +00005101 TLI.isFMAFasterThanFMulAndFAdd(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005102 setValue(&I, DAG.getNode(ISD::FMA, sdl,
Lang Hamesa59100c2012-06-05 19:07:46 +00005103 getValue(I.getArgOperand(0)).getValueType(),
5104 getValue(I.getArgOperand(0)),
5105 getValue(I.getArgOperand(1)),
5106 getValue(I.getArgOperand(2))));
5107 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005108 SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
Lang Hamesa59100c2012-06-05 19:07:46 +00005109 getValue(I.getArgOperand(0)).getValueType(),
5110 getValue(I.getArgOperand(0)),
5111 getValue(I.getArgOperand(1)));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005112 SDValue Add = DAG.getNode(ISD::FADD, sdl,
Lang Hamesa59100c2012-06-05 19:07:46 +00005113 getValue(I.getArgOperand(0)).getValueType(),
5114 Mul,
5115 getValue(I.getArgOperand(2)));
5116 setValue(&I, Add);
5117 }
Craig Topperc0196b12014-04-14 00:51:57 +00005118 return nullptr;
Lang Hamesa59100c2012-06-05 19:07:46 +00005119 }
Anton Korobeynikov39ed49d2010-03-14 18:42:15 +00005120 case Intrinsic::convert_to_fp16:
Tim Northoverf7a02c12014-07-21 09:13:56 +00005121 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5122 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5123 getValue(I.getArgOperand(0)),
5124 DAG.getTargetConstant(0, MVT::i32))));
Craig Topperc0196b12014-04-14 00:51:57 +00005125 return nullptr;
Anton Korobeynikov39ed49d2010-03-14 18:42:15 +00005126 case Intrinsic::convert_from_fp16:
Tim Northoverfd7e4242014-07-17 10:51:23 +00005127 setValue(&I,
Eric Christopher58a24612014-10-08 09:50:54 +00005128 DAG.getNode(ISD::FP_EXTEND, sdl, TLI.getValueType(I.getType()),
Tim Northoverf7a02c12014-07-21 09:13:56 +00005129 DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5130 getValue(I.getArgOperand(0)))));
Craig Topperc0196b12014-04-14 00:51:57 +00005131 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005132 case Intrinsic::pcmarker: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005133 SDValue Tmp = getValue(I.getArgOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005134 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
Craig Topperc0196b12014-04-14 00:51:57 +00005135 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005136 }
5137 case Intrinsic::readcyclecounter: {
5138 SDValue Op = getRoot();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005139 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
Craig Topper48d114b2014-04-26 18:35:24 +00005140 DAG.getVTList(MVT::i64, MVT::Other), Op);
Bill Wendlingb99b2692009-12-22 00:40:51 +00005141 setValue(&I, Res);
5142 DAG.setRoot(Res.getValue(1));
Craig Topperc0196b12014-04-14 00:51:57 +00005143 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005144 }
Dan Gohman575fad32008-09-03 16:12:24 +00005145 case Intrinsic::bswap:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005146 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
Gabor Greifeba0be72010-06-25 09:38:13 +00005147 getValue(I.getArgOperand(0)).getValueType(),
5148 getValue(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00005149 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005150 case Intrinsic::cttz: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005151 SDValue Arg = getValue(I.getArgOperand(0));
Chandler Carruth637cc6a2011-12-13 01:56:10 +00005152 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
Owen Anderson53aa7a92009-08-10 22:56:29 +00005153 EVT Ty = Arg.getValueType();
Chandler Carruth637cc6a2011-12-13 01:56:10 +00005154 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005155 sdl, Ty, Arg));
Craig Topperc0196b12014-04-14 00:51:57 +00005156 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005157 }
5158 case Intrinsic::ctlz: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005159 SDValue Arg = getValue(I.getArgOperand(0));
Chandler Carruth637cc6a2011-12-13 01:56:10 +00005160 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
Owen Anderson53aa7a92009-08-10 22:56:29 +00005161 EVT Ty = Arg.getValueType();
Chandler Carruth637cc6a2011-12-13 01:56:10 +00005162 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005163 sdl, Ty, Arg));
Craig Topperc0196b12014-04-14 00:51:57 +00005164 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005165 }
5166 case Intrinsic::ctpop: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005167 SDValue Arg = getValue(I.getArgOperand(0));
Owen Anderson53aa7a92009-08-10 22:56:29 +00005168 EVT Ty = Arg.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005169 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
Craig Topperc0196b12014-04-14 00:51:57 +00005170 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005171 }
5172 case Intrinsic::stacksave: {
5173 SDValue Op = getRoot();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005174 Res = DAG.getNode(ISD::STACKSAVE, sdl,
Eric Christopher58a24612014-10-08 09:50:54 +00005175 DAG.getVTList(TLI.getPointerTy(), MVT::Other), Op);
Bill Wendlingb99b2692009-12-22 00:40:51 +00005176 setValue(&I, Res);
5177 DAG.setRoot(Res.getValue(1));
Craig Topperc0196b12014-04-14 00:51:57 +00005178 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005179 }
5180 case Intrinsic::stackrestore: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005181 Res = getValue(I.getArgOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005182 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
Craig Topperc0196b12014-04-14 00:51:57 +00005183 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005184 }
Bill Wendling13020d22008-11-18 11:01:33 +00005185 case Intrinsic::stackprotector: {
Bill Wendlingd970ea32008-11-06 02:29:10 +00005186 // Emit code into the DAG to store the stack guard onto the stack.
5187 MachineFunction &MF = DAG.getMachineFunction();
5188 MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopher58a24612014-10-08 09:50:54 +00005189 EVT PtrTy = TLI.getPointerTy();
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00005190 SDValue Src, Chain = getRoot();
Akira Hatanaka5acc58f2014-08-07 23:08:24 +00005191 const Value *Ptr = cast<LoadInst>(I.getArgOperand(0))->getPointerOperand();
5192 const GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr);
Bill Wendlingd970ea32008-11-06 02:29:10 +00005193
Akira Hatanaka5acc58f2014-08-07 23:08:24 +00005194 // See if Ptr is a bitcast. If it is, look through it and see if we can get
5195 // global variable __stack_chk_guard.
5196 if (!GV)
5197 if (const Operator *BC = dyn_cast<Operator>(Ptr))
5198 if (BC->getOpcode() == Instruction::BitCast)
5199 GV = dyn_cast<GlobalVariable>(BC->getOperand(0));
5200
Eric Christopher58a24612014-10-08 09:50:54 +00005201 if (GV && TLI.useLoadStackGuardNode()) {
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00005202 // Emit a LOAD_STACK_GUARD node.
5203 MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD,
5204 sdl, PtrTy, Chain);
Akira Hatanaka5acc58f2014-08-07 23:08:24 +00005205 MachinePointerInfo MPInfo(GV);
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00005206 MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
5207 unsigned Flags = MachineMemOperand::MOLoad |
5208 MachineMemOperand::MOInvariant;
5209 *MemRefs = MF.getMachineMemOperand(MPInfo, Flags,
5210 PtrTy.getSizeInBits() / 8,
5211 DAG.getEVTAlignment(PtrTy));
5212 Node->setMemRefs(MemRefs, MemRefs + 1);
5213
5214 // Copy the guard value to a virtual register so that it can be
5215 // retrieved in the epilogue.
5216 Src = SDValue(Node, 0);
5217 const TargetRegisterClass *RC =
Eric Christopher58a24612014-10-08 09:50:54 +00005218 TLI.getRegClassFor(Src.getSimpleValueType());
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00005219 unsigned Reg = MF.getRegInfo().createVirtualRegister(RC);
5220
5221 SPDescriptor.setGuardReg(Reg);
5222 Chain = DAG.getCopyToReg(Chain, sdl, Reg, Src);
5223 } else {
5224 Src = getValue(I.getArgOperand(0)); // The guard's value.
5225 }
5226
Gabor Greifeba0be72010-06-25 09:38:13 +00005227 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
Bill Wendlingd970ea32008-11-06 02:29:10 +00005228
Bill Wendlingeb4268d2008-11-07 01:23:58 +00005229 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingd970ea32008-11-06 02:29:10 +00005230 MFI->setStackProtectorIndex(FI);
5231
5232 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5233
5234 // Store the stack protector onto the stack.
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00005235 Res = DAG.getStore(Chain, sdl, Src, FIN,
Chris Lattnera4f19972010-09-21 18:58:22 +00005236 MachinePointerInfo::getFixedStack(FI),
5237 true, false, 0);
Bill Wendlingb99b2692009-12-22 00:40:51 +00005238 setValue(&I, Res);
5239 DAG.setRoot(Res);
Craig Topperc0196b12014-04-14 00:51:57 +00005240 return nullptr;
Bill Wendlingd970ea32008-11-06 02:29:10 +00005241 }
Eric Christopher7a50b282009-10-27 00:52:25 +00005242 case Intrinsic::objectsize: {
5243 // If we don't know by now, we're never going to know.
Gabor Greifeba0be72010-06-25 09:38:13 +00005244 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
Eric Christopher7a50b282009-10-27 00:52:25 +00005245
5246 assert(CI && "Non-constant type in __builtin_object_size?");
5247
Gabor Greifeba0be72010-06-25 09:38:13 +00005248 SDValue Arg = getValue(I.getCalledValue());
Eric Christopher1fd4c572009-10-28 21:32:16 +00005249 EVT Ty = Arg.getValueType();
5250
Dan Gohmanf1d83042010-06-18 14:22:04 +00005251 if (CI->isZero())
Bill Wendlingb99b2692009-12-22 00:40:51 +00005252 Res = DAG.getConstant(-1ULL, Ty);
Eric Christopher7a50b282009-10-27 00:52:25 +00005253 else
Bill Wendlingb99b2692009-12-22 00:40:51 +00005254 Res = DAG.getConstant(0, Ty);
5255
5256 setValue(&I, Res);
Craig Topperc0196b12014-04-14 00:51:57 +00005257 return nullptr;
Eric Christopher7a50b282009-10-27 00:52:25 +00005258 }
Justin Holewinskifff1f5f2013-05-21 14:37:16 +00005259 case Intrinsic::annotation:
5260 case Intrinsic::ptr_annotation:
5261 // Drop the intrinsic, but forward the value
5262 setValue(&I, getValue(I.getOperand(0)));
Craig Topperc0196b12014-04-14 00:51:57 +00005263 return nullptr;
Hal Finkel93046912014-07-25 21:13:35 +00005264 case Intrinsic::assume:
Dan Gohman575fad32008-09-03 16:12:24 +00005265 case Intrinsic::var_annotation:
Hal Finkel93046912014-07-25 21:13:35 +00005266 // Discard annotate attributes and assumptions
Craig Topperc0196b12014-04-14 00:51:57 +00005267 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005268
5269 case Intrinsic::init_trampoline: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005270 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
Dan Gohman575fad32008-09-03 16:12:24 +00005271
5272 SDValue Ops[6];
5273 Ops[0] = getRoot();
Gabor Greifeba0be72010-06-25 09:38:13 +00005274 Ops[1] = getValue(I.getArgOperand(0));
5275 Ops[2] = getValue(I.getArgOperand(1));
5276 Ops[3] = getValue(I.getArgOperand(2));
5277 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
Dan Gohman575fad32008-09-03 16:12:24 +00005278 Ops[5] = DAG.getSrcValue(F);
5279
Craig Topper48d114b2014-04-26 18:35:24 +00005280 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
Dan Gohman575fad32008-09-03 16:12:24 +00005281
Duncan Sandsa0984362011-09-06 13:37:06 +00005282 DAG.setRoot(Res);
Craig Topperc0196b12014-04-14 00:51:57 +00005283 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00005284 }
5285 case Intrinsic::adjust_trampoline: {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005286 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
Eric Christopher58a24612014-10-08 09:50:54 +00005287 TLI.getPointerTy(),
Duncan Sandsa0984362011-09-06 13:37:06 +00005288 getValue(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00005289 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005290 }
Dan Gohman575fad32008-09-03 16:12:24 +00005291 case Intrinsic::gcroot:
5292 if (GFI) {
Bill Wendlingb6b50c62012-05-01 22:50:45 +00005293 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
Gabor Greifeba0be72010-06-25 09:38:13 +00005294 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00005295
Dan Gohman575fad32008-09-03 16:12:24 +00005296 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5297 GFI->addStackRoot(FI->getIndex(), TypeMap);
5298 }
Craig Topperc0196b12014-04-14 00:51:57 +00005299 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005300 case Intrinsic::gcread:
5301 case Intrinsic::gcwrite:
Torok Edwinfbcc6632009-07-14 16:55:14 +00005302 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
Bill Wendlingb99b2692009-12-22 00:40:51 +00005303 case Intrinsic::flt_rounds:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005304 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
Craig Topperc0196b12014-04-14 00:51:57 +00005305 return nullptr;
Jakub Staszak3f158fd2011-07-06 18:22:43 +00005306
5307 case Intrinsic::expect: {
5308 // Just replace __builtin_expect(exp, c) with EXP.
5309 setValue(&I, getValue(I.getArgOperand(0)));
Craig Topperc0196b12014-04-14 00:51:57 +00005310 return nullptr;
Jakub Staszak3f158fd2011-07-06 18:22:43 +00005311 }
5312
Shuxin Yangcdde0592012-10-19 20:11:16 +00005313 case Intrinsic::debugtrap:
Evan Cheng74d92c12011-04-08 21:37:21 +00005314 case Intrinsic::trap: {
Nick Lewycky50f02cb2011-12-02 22:16:29 +00005315 StringRef TrapFuncName = TM.Options.getTrapFunctionName();
Evan Cheng74d92c12011-04-08 21:37:21 +00005316 if (TrapFuncName.empty()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00005317 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
Shuxin Yangcdde0592012-10-19 20:11:16 +00005318 ISD::TRAP : ISD::DEBUGTRAP;
Andrew Trickef9de2a2013-05-25 02:42:55 +00005319 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
Craig Topperc0196b12014-04-14 00:51:57 +00005320 return nullptr;
Evan Cheng74d92c12011-04-08 21:37:21 +00005321 }
5322 TargetLowering::ArgListTy Args;
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +00005323
5324 TargetLowering::CallLoweringInfo CLI(DAG);
5325 CLI.setDebugLoc(sdl).setChain(getRoot())
5326 .setCallee(CallingConv::C, I.getType(),
Eric Christopher58a24612014-10-08 09:50:54 +00005327 DAG.getExternalSymbol(TrapFuncName.data(), TLI.getPointerTy()),
Juergen Ributzka3bd03c72014-07-01 22:01:54 +00005328 std::move(Args), 0);
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +00005329
Eric Christopher58a24612014-10-08 09:50:54 +00005330 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
Evan Cheng74d92c12011-04-08 21:37:21 +00005331 DAG.setRoot(Result.second);
Craig Topperc0196b12014-04-14 00:51:57 +00005332 return nullptr;
Evan Cheng74d92c12011-04-08 21:37:21 +00005333 }
Shuxin Yangcdde0592012-10-19 20:11:16 +00005334
Bill Wendling5eee7442008-11-21 02:38:44 +00005335 case Intrinsic::uadd_with_overflow:
Bill Wendlingdb8ec2d2008-12-09 22:08:41 +00005336 case Intrinsic::sadd_with_overflow:
Bill Wendlingdb8ec2d2008-12-09 22:08:41 +00005337 case Intrinsic::usub_with_overflow:
Bill Wendlingdb8ec2d2008-12-09 22:08:41 +00005338 case Intrinsic::ssub_with_overflow:
Bill Wendlingdb8ec2d2008-12-09 22:08:41 +00005339 case Intrinsic::umul_with_overflow:
Craig Topperbc680062012-04-11 04:34:11 +00005340 case Intrinsic::smul_with_overflow: {
5341 ISD::NodeType Op;
5342 switch (Intrinsic) {
5343 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5344 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5345 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5346 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5347 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5348 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5349 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5350 }
5351 SDValue Op1 = getValue(I.getArgOperand(0));
5352 SDValue Op2 = getValue(I.getArgOperand(1));
Bill Wendling74296c62008-11-21 02:03:52 +00005353
Craig Topperbc680062012-04-11 04:34:11 +00005354 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005355 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
Craig Topperc0196b12014-04-14 00:51:57 +00005356 return nullptr;
Craig Topperbc680062012-04-11 04:34:11 +00005357 }
Dan Gohman575fad32008-09-03 16:12:24 +00005358 case Intrinsic::prefetch: {
Bruno Cardoso Lopesdc9ff3a2011-06-14 04:58:37 +00005359 SDValue Ops[5];
Dale Johannesene660f4d2010-10-26 23:11:10 +00005360 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
Dan Gohman575fad32008-09-03 16:12:24 +00005361 Ops[0] = getRoot();
Gabor Greifeba0be72010-06-25 09:38:13 +00005362 Ops[1] = getValue(I.getArgOperand(0));
5363 Ops[2] = getValue(I.getArgOperand(1));
5364 Ops[3] = getValue(I.getArgOperand(2));
Bruno Cardoso Lopesdc9ff3a2011-06-14 04:58:37 +00005365 Ops[4] = getValue(I.getArgOperand(3));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005366 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
Craig Topper206fcd42014-04-26 19:29:41 +00005367 DAG.getVTList(MVT::Other), Ops,
Dale Johannesene660f4d2010-10-26 23:11:10 +00005368 EVT::getIntegerVT(*Context, 8),
5369 MachinePointerInfo(I.getArgOperand(0)),
5370 0, /* align */
5371 false, /* volatile */
5372 rw==0, /* read */
5373 rw==1)); /* write */
Craig Topperc0196b12014-04-14 00:51:57 +00005374 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005375 }
Duncan Sandsdca0c282009-11-10 09:08:09 +00005376 case Intrinsic::lifetime_start:
Nadav Rotem7c277da2012-09-06 09:17:37 +00005377 case Intrinsic::lifetime_end: {
Nadav Rotem7c277da2012-09-06 09:17:37 +00005378 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
Nadav Rotemd753a952012-09-10 08:43:23 +00005379 // Stack coloring is not enabled in O0, discard region information.
5380 if (TM.getOptLevel() == CodeGenOpt::None)
Craig Topperc0196b12014-04-14 00:51:57 +00005381 return nullptr;
Nadav Rotem7c277da2012-09-06 09:17:37 +00005382
Nadav Rotemd753a952012-09-10 08:43:23 +00005383 SmallVector<Value *, 4> Allocas;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005384 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
Nadav Rotemd753a952012-09-10 08:43:23 +00005385
Craig Toppere1c1d362013-07-03 05:11:49 +00005386 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5387 E = Allocas.end(); Object != E; ++Object) {
Nadav Rotemd753a952012-09-10 08:43:23 +00005388 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5389
5390 // Could not find an Alloca.
5391 if (!LifetimeObject)
5392 continue;
5393
Pete Cooper230332f2014-10-17 22:59:33 +00005394 // First check that the Alloca is static, otherwise it won't have a
5395 // valid frame index.
5396 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
5397 if (SI == FuncInfo.StaticAllocaMap.end())
5398 return nullptr;
5399
5400 int FI = SI->second;
Nadav Rotemd753a952012-09-10 08:43:23 +00005401
5402 SDValue Ops[2];
5403 Ops[0] = getRoot();
Eric Christopher58a24612014-10-08 09:50:54 +00005404 Ops[1] = DAG.getFrameIndex(FI, TLI.getPointerTy(), true);
Nadav Rotemd753a952012-09-10 08:43:23 +00005405 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5406
Craig Topper48d114b2014-04-26 18:35:24 +00005407 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
Nadav Rotemd753a952012-09-10 08:43:23 +00005408 DAG.setRoot(Res);
5409 }
Craig Topperc0196b12014-04-14 00:51:57 +00005410 return nullptr;
Nadav Rotem7c277da2012-09-06 09:17:37 +00005411 }
5412 case Intrinsic::invariant_start:
Duncan Sandsdca0c282009-11-10 09:08:09 +00005413 // Discard region information.
Eric Christopher58a24612014-10-08 09:50:54 +00005414 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
Craig Topperc0196b12014-04-14 00:51:57 +00005415 return nullptr;
Duncan Sandsdca0c282009-11-10 09:08:09 +00005416 case Intrinsic::invariant_end:
Duncan Sandsdca0c282009-11-10 09:08:09 +00005417 // Discard region information.
Craig Topperc0196b12014-04-14 00:51:57 +00005418 return nullptr;
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00005419 case Intrinsic::stackprotectorcheck: {
5420 // Do not actually emit anything for this basic block. Instead we initialize
5421 // the stack protector descriptor and export the guard variable so we can
5422 // access it in FinishBasicBlock.
5423 const BasicBlock *BB = I.getParent();
5424 SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
5425 ExportFromCurrentBlock(SPDescriptor.getGuard());
5426
5427 // Flush our exports since we are going to process a terminator.
5428 (void)getControlRoot();
Craig Topperc0196b12014-04-14 00:51:57 +00005429 return nullptr;
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00005430 }
Renato Golinc0a3c1d2014-03-26 12:52:28 +00005431 case Intrinsic::clear_cache:
Eric Christopher58a24612014-10-08 09:50:54 +00005432 return TLI.getClearCacheBuiltinName();
Nuno Lopesec9653b2012-06-28 22:30:12 +00005433 case Intrinsic::donothing:
5434 // ignore
Craig Topperc0196b12014-04-14 00:51:57 +00005435 return nullptr;
Andrew Trick74f4c742013-10-31 17:18:24 +00005436 case Intrinsic::experimental_stackmap: {
5437 visitStackmap(I);
Craig Topperc0196b12014-04-14 00:51:57 +00005438 return nullptr;
Andrew Trick74f4c742013-10-31 17:18:24 +00005439 }
5440 case Intrinsic::experimental_patchpoint_void:
5441 case Intrinsic::experimental_patchpoint_i64: {
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00005442 visitPatchpoint(&I);
Craig Topperc0196b12014-04-14 00:51:57 +00005443 return nullptr;
Andrew Trick74f4c742013-10-31 17:18:24 +00005444 }
Philip Reames1a1bdb22014-12-02 18:50:36 +00005445 case Intrinsic::experimental_gc_statepoint: {
5446 visitStatepoint(I);
5447 return nullptr;
5448 }
5449 case Intrinsic::experimental_gc_result_int:
5450 case Intrinsic::experimental_gc_result_float:
Ramkumar Ramachandra75a4f352015-01-22 20:14:38 +00005451 case Intrinsic::experimental_gc_result_ptr:
5452 case Intrinsic::experimental_gc_result: {
Philip Reames1a1bdb22014-12-02 18:50:36 +00005453 visitGCResult(I);
5454 return nullptr;
5455 }
5456 case Intrinsic::experimental_gc_relocate: {
5457 visitGCRelocate(I);
5458 return nullptr;
5459 }
Justin Bogner61ba2e32014-12-08 18:02:35 +00005460 case Intrinsic::instrprof_increment:
5461 llvm_unreachable("instrprof failed to lower an increment");
Reid Klecknere9b89312015-01-13 00:48:10 +00005462
Reid Klecknercfb9ce52015-03-05 18:26:34 +00005463 case Intrinsic::frameescape: {
Reid Klecknere9b89312015-01-13 00:48:10 +00005464 MachineFunction &MF = DAG.getMachineFunction();
5465 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5466
Reid Klecknercfb9ce52015-03-05 18:26:34 +00005467 // Directly emit some FRAME_ALLOC machine instrs. Label assignment emission
5468 // is the same on all targets.
5469 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
5470 AllocaInst *Slot =
5471 cast<AllocaInst>(I.getArgOperand(Idx)->stripPointerCasts());
5472 assert(FuncInfo.StaticAllocaMap.count(Slot) &&
5473 "can only escape static allocas");
5474 int FI = FuncInfo.StaticAllocaMap[Slot];
5475 MCSymbol *FrameAllocSym =
5476 MF.getMMI().getContext().getOrCreateFrameAllocSymbol(MF.getName(),
5477 Idx);
5478 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
5479 TII->get(TargetOpcode::FRAME_ALLOC))
5480 .addSym(FrameAllocSym)
5481 .addFrameIndex(FI);
5482 }
Reid Klecknere9b89312015-01-13 00:48:10 +00005483
5484 return nullptr;
5485 }
5486
Reid Kleckner3542ace2015-01-13 01:51:34 +00005487 case Intrinsic::framerecover: {
Reid Klecknercfb9ce52015-03-05 18:26:34 +00005488 // i8* @llvm.framerecover(i8* %fn, i8* %fp, i32 %idx)
Reid Klecknere9b89312015-01-13 00:48:10 +00005489 MachineFunction &MF = DAG.getMachineFunction();
5490 MVT PtrVT = TLI.getPointerTy(0);
5491
5492 // Get the symbol that defines the frame offset.
Reid Klecknercfb9ce52015-03-05 18:26:34 +00005493 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
5494 auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
5495 unsigned IdxVal = unsigned(Idx->getLimitedValue(INT_MAX));
Reid Klecknere9b89312015-01-13 00:48:10 +00005496 MCSymbol *FrameAllocSym =
Reid Klecknercfb9ce52015-03-05 18:26:34 +00005497 MF.getMMI().getContext().getOrCreateFrameAllocSymbol(Fn->getName(),
5498 IdxVal);
Reid Klecknere9b89312015-01-13 00:48:10 +00005499
5500 // Create a TargetExternalSymbol for the label to avoid any target lowering
5501 // that would make this PC relative.
5502 StringRef Name = FrameAllocSym->getName();
Reid Klecknercfb9ce52015-03-05 18:26:34 +00005503 assert(Name.data()[Name.size()] == '\0' && "not null terminated");
Reid Klecknere9b89312015-01-13 00:48:10 +00005504 SDValue OffsetSym = DAG.getTargetExternalSymbol(Name.data(), PtrVT);
5505 SDValue OffsetVal =
Reid Kleckner3542ace2015-01-13 01:51:34 +00005506 DAG.getNode(ISD::FRAME_ALLOC_RECOVER, sdl, PtrVT, OffsetSym);
Reid Klecknere9b89312015-01-13 00:48:10 +00005507
5508 // Add the offset to the FP.
5509 Value *FP = I.getArgOperand(1);
5510 SDValue FPVal = getValue(FP);
5511 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
5512 setValue(&I, Add);
5513
5514 return nullptr;
5515 }
Andrew Kaylor78b53db2015-02-10 19:52:43 +00005516 case Intrinsic::eh_begincatch:
5517 case Intrinsic::eh_endcatch:
5518 llvm_unreachable("begin/end catch intrinsics not lowered in codegen");
Dan Gohman575fad32008-09-03 16:12:24 +00005519 }
5520}
5521
Juergen Ributzkafd4633e2014-10-16 21:26:35 +00005522std::pair<SDValue, SDValue>
5523SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
5524 MachineBasicBlock *LandingPad) {
Chris Lattnerfb964e52010-04-05 06:19:28 +00005525 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Craig Topperc0196b12014-04-14 00:51:57 +00005526 MCSymbol *BeginLabel = nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005527
Chris Lattnerfb964e52010-04-05 06:19:28 +00005528 if (LandingPad) {
Dan Gohman575fad32008-09-03 16:12:24 +00005529 // Insert a label before the invoke call to mark the try range. This can be
5530 // used to detect deletion of the invoke via the MachineModuleInfo.
Chris Lattnerfb964e52010-04-05 06:19:28 +00005531 BeginLabel = MMI.getContext().CreateTempSymbol();
Jim Grosbach693e36a2009-08-11 00:09:57 +00005532
Jim Grosbach54c05302010-01-28 01:45:32 +00005533 // For SjLj, keep track of which landing pads go with which invokes
5534 // so as to maintain the ordering of pads in the LSDA.
Chris Lattnerfb964e52010-04-05 06:19:28 +00005535 unsigned CallSiteIndex = MMI.getCurrentCallSite();
Jim Grosbach54c05302010-01-28 01:45:32 +00005536 if (CallSiteIndex) {
Chris Lattnerfb964e52010-04-05 06:19:28 +00005537 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
Bill Wendling267f3232011-10-05 22:24:35 +00005538 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
Bill Wendling3d11aa72011-10-04 22:00:35 +00005539
Jim Grosbach54c05302010-01-28 01:45:32 +00005540 // Now that the call site is handled, stop tracking it.
Chris Lattnerfb964e52010-04-05 06:19:28 +00005541 MMI.setCurrentCallSite(0);
Jim Grosbach54c05302010-01-28 01:45:32 +00005542 }
5543
Dan Gohman575fad32008-09-03 16:12:24 +00005544 // Both PendingLoads and PendingExports must be flushed here;
5545 // this call might not return.
5546 (void)getRoot();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005547 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
Juergen Ributzkafd4633e2014-10-16 21:26:35 +00005548
5549 CLI.setChain(getRoot());
Dan Gohman575fad32008-09-03 16:12:24 +00005550 }
Eric Christopher2b214e72015-01-27 01:01:36 +00005551 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5552 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00005553
Juergen Ributzkafd4633e2014-10-16 21:26:35 +00005554 assert((CLI.IsTailCall || Result.second.getNode()) &&
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00005555 "Non-null chain expected with non-tail call!");
5556 assert((Result.second.getNode() || !Result.first.getNode()) &&
5557 "Null value expected with tail call!");
Bill Wendlinga4d7df72009-12-22 00:50:32 +00005558
Evan Cheng8d68ebd2011-04-01 19:42:22 +00005559 if (!Result.second.getNode()) {
Andrew Trick74f4c742013-10-31 17:18:24 +00005560 // As a special case, a null chain means that a tail call has been emitted
5561 // and the DAG root is already updated.
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00005562 HasTailCall = true;
Tim Northoverdab4db52013-07-06 12:58:45 +00005563
5564 // Since there's no actual continuation from this block, nothing can be
5565 // relying on us setting vregs for them.
5566 PendingExports.clear();
Evan Cheng8d68ebd2011-04-01 19:42:22 +00005567 } else {
5568 DAG.setRoot(Result.second);
Evan Cheng8d68ebd2011-04-01 19:42:22 +00005569 }
Dan Gohman575fad32008-09-03 16:12:24 +00005570
Chris Lattnerfb964e52010-04-05 06:19:28 +00005571 if (LandingPad) {
Dan Gohman575fad32008-09-03 16:12:24 +00005572 // Insert a label at the end of the invoke call to mark the try range. This
5573 // can be used to detect deletion of the invoke via the MachineModuleInfo.
Chris Lattnerfb964e52010-04-05 06:19:28 +00005574 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005575 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
Dan Gohman575fad32008-09-03 16:12:24 +00005576
5577 // Inform MachineModuleInfo of range.
Chris Lattnerfb964e52010-04-05 06:19:28 +00005578 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
Dan Gohman575fad32008-09-03 16:12:24 +00005579 }
Juergen Ributzkafd4633e2014-10-16 21:26:35 +00005580
5581 return Result;
5582}
5583
5584void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
5585 bool isTailCall,
5586 MachineBasicBlock *LandingPad) {
5587 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
5588 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
5589 Type *RetTy = FTy->getReturnType();
5590
5591 TargetLowering::ArgListTy Args;
5592 TargetLowering::ArgListEntry Entry;
5593 Args.reserve(CS.arg_size());
5594
5595 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
5596 i != e; ++i) {
5597 const Value *V = *i;
5598
5599 // Skip empty types
5600 if (V->getType()->isEmptyTy())
5601 continue;
5602
5603 SDValue ArgNode = getValue(V);
5604 Entry.Node = ArgNode; Entry.Ty = V->getType();
5605
5606 // Skip the first return-type Attribute to get to params.
5607 Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
5608 Args.push_back(Entry);
5609 }
5610
5611 // Check if target-independent constraints permit a tail call here.
5612 // Target-dependent constraints are checked within TLI->LowerCallTo.
5613 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
5614 isTailCall = false;
5615
5616 TargetLowering::CallLoweringInfo CLI(DAG);
5617 CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
5618 .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
5619 .setTailCall(isTailCall);
5620 std::pair<SDValue,SDValue> Result = lowerInvokable(CLI, LandingPad);
5621
5622 if (Result.first.getNode())
5623 setValue(CS.getInstruction(), Result.first);
Dan Gohman575fad32008-09-03 16:12:24 +00005624}
5625
Chris Lattner1a32ede2009-12-24 00:37:38 +00005626/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5627/// value is equal or not-equal to zero.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005628static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00005629 for (const User *U : V->users()) {
5630 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
Chris Lattner1a32ede2009-12-24 00:37:38 +00005631 if (IC->isEquality())
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005632 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
Chris Lattner1a32ede2009-12-24 00:37:38 +00005633 if (C->isNullValue())
5634 continue;
5635 // Unknown instruction.
5636 return false;
5637 }
5638 return true;
5639}
5640
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005641static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
Chris Lattner229907c2011-07-18 04:54:35 +00005642 Type *LoadTy,
Chris Lattner1a32ede2009-12-24 00:37:38 +00005643 SelectionDAGBuilder &Builder) {
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005644
Chris Lattner1a32ede2009-12-24 00:37:38 +00005645 // Check to see if this load can be trivially constant folded, e.g. if the
5646 // input is from a string literal.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005647 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
Chris Lattner1a32ede2009-12-24 00:37:38 +00005648 // Cast pointer to the type we really want to load.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005649 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
Chris Lattner1a32ede2009-12-24 00:37:38 +00005650 PointerType::getUnqual(LoadTy));
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005651
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005652 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
5653 const_cast<Constant *>(LoadInput), *Builder.DL))
Chris Lattner1a32ede2009-12-24 00:37:38 +00005654 return Builder.getValue(LoadCst);
5655 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005656
Chris Lattner1a32ede2009-12-24 00:37:38 +00005657 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5658 // still constant memory, the input chain can be the entry node.
5659 SDValue Root;
5660 bool ConstantMemory = false;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005661
Chris Lattner1a32ede2009-12-24 00:37:38 +00005662 // Do not serialize (non-volatile) loads of constant memory with anything.
5663 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5664 Root = Builder.DAG.getEntryNode();
5665 ConstantMemory = true;
5666 } else {
5667 // Do not serialize non-volatile loads against each other.
5668 Root = Builder.DAG.getRoot();
5669 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005670
Chris Lattner1a32ede2009-12-24 00:37:38 +00005671 SDValue Ptr = Builder.getValue(PtrVal);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005672 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
Chris Lattner1ffcf522010-09-21 16:36:31 +00005673 Ptr, MachinePointerInfo(PtrVal),
David Greene39c6d012010-02-15 17:00:31 +00005674 false /*volatile*/,
Stephen Lincfe7f352013-07-08 00:37:03 +00005675 false /*nontemporal*/,
Pete Cooper82cd9e82011-11-08 18:42:53 +00005676 false /*isinvariant*/, 1 /* align=1 */);
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005677
Chris Lattner1a32ede2009-12-24 00:37:38 +00005678 if (!ConstantMemory)
5679 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5680 return LoadVal;
5681}
5682
Richard Sandiforde3827752013-08-16 10:55:47 +00005683/// processIntegerCallValue - Record the value for an instruction that
5684/// produces an integer result, converting the type where necessary.
5685void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
5686 SDValue Value,
5687 bool IsSigned) {
Eric Christopher58a24612014-10-08 09:50:54 +00005688 EVT VT = DAG.getTargetLoweringInfo().getValueType(I.getType(), true);
Richard Sandiforde3827752013-08-16 10:55:47 +00005689 if (IsSigned)
5690 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
5691 else
5692 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
5693 setValue(&I, Value);
5694}
Chris Lattner1a32ede2009-12-24 00:37:38 +00005695
5696/// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5697/// If so, return true and lower it, otherwise return false and it will be
5698/// lowered like a normal call.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005699bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
Chris Lattner1a32ede2009-12-24 00:37:38 +00005700 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
Gabor Greiff69acfe2010-06-30 12:55:46 +00005701 if (I.getNumArgOperands() != 3)
Chris Lattner1a32ede2009-12-24 00:37:38 +00005702 return false;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005703
Gabor Greifeba0be72010-06-25 09:38:13 +00005704 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
Duncan Sands19d0b472010-02-16 11:11:14 +00005705 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
Gabor Greifeba0be72010-06-25 09:38:13 +00005706 !I.getArgOperand(2)->getType()->isIntegerTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +00005707 !I.getType()->isIntegerTy())
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005708 return false;
5709
Richard Sandiforde3827752013-08-16 10:55:47 +00005710 const Value *Size = I.getArgOperand(2);
5711 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
5712 if (CSize && CSize->getZExtValue() == 0) {
Eric Christopher58a24612014-10-08 09:50:54 +00005713 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(I.getType(), true);
Richard Sandiford564681c2013-08-12 10:28:10 +00005714 setValue(&I, DAG.getConstant(0, CallVT));
5715 return true;
5716 }
5717
Richard Sandiford564681c2013-08-12 10:28:10 +00005718 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5719 std::pair<SDValue, SDValue> Res =
5720 TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
Richard Sandiforde3827752013-08-16 10:55:47 +00005721 getValue(LHS), getValue(RHS), getValue(Size),
5722 MachinePointerInfo(LHS),
5723 MachinePointerInfo(RHS));
Richard Sandiford564681c2013-08-12 10:28:10 +00005724 if (Res.first.getNode()) {
Richard Sandiforde3827752013-08-16 10:55:47 +00005725 processIntegerCallValue(I, Res.first, true);
5726 PendingLoads.push_back(Res.second);
Richard Sandiford564681c2013-08-12 10:28:10 +00005727 return true;
5728 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005729
Chris Lattner1a32ede2009-12-24 00:37:38 +00005730 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5731 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
Richard Sandiforde3827752013-08-16 10:55:47 +00005732 if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005733 bool ActuallyDoIt = true;
5734 MVT LoadVT;
Chris Lattner229907c2011-07-18 04:54:35 +00005735 Type *LoadTy;
Richard Sandiforde3827752013-08-16 10:55:47 +00005736 switch (CSize->getZExtValue()) {
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005737 default:
5738 LoadVT = MVT::Other;
Craig Topperc0196b12014-04-14 00:51:57 +00005739 LoadTy = nullptr;
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005740 ActuallyDoIt = false;
5741 break;
5742 case 2:
5743 LoadVT = MVT::i16;
Richard Sandiforde3827752013-08-16 10:55:47 +00005744 LoadTy = Type::getInt16Ty(CSize->getContext());
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005745 break;
5746 case 4:
5747 LoadVT = MVT::i32;
Richard Sandiforde3827752013-08-16 10:55:47 +00005748 LoadTy = Type::getInt32Ty(CSize->getContext());
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005749 break;
5750 case 8:
5751 LoadVT = MVT::i64;
Richard Sandiforde3827752013-08-16 10:55:47 +00005752 LoadTy = Type::getInt64Ty(CSize->getContext());
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005753 break;
5754 /*
5755 case 16:
5756 LoadVT = MVT::v4i32;
Richard Sandiforde3827752013-08-16 10:55:47 +00005757 LoadTy = Type::getInt32Ty(CSize->getContext());
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005758 LoadTy = VectorType::get(LoadTy, 4);
5759 break;
5760 */
5761 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005762
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005763 // This turns into unaligned loads. We only do this if the target natively
5764 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5765 // we'll only produce a small number of byte loads.
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005766
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005767 // Require that we can find a legal MVT, and only do this if the target
5768 // supports unaligned loads of that type. Expanding into byte loads would
5769 // bloat the code.
Eric Christopher58a24612014-10-08 09:50:54 +00005770 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Richard Sandiforde3827752013-08-16 10:55:47 +00005771 if (ActuallyDoIt && CSize->getZExtValue() > 4) {
Matt Arsenault1b55dd92014-02-05 23:16:05 +00005772 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
5773 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005774 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5775 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
Matt Arsenault6f2a5262014-07-27 17:46:40 +00005776 // TODO: Check alignment of src and dest ptrs.
Eric Christopher58a24612014-10-08 09:50:54 +00005777 if (!TLI.isTypeLegal(LoadVT) ||
5778 !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) ||
5779 !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS))
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005780 ActuallyDoIt = false;
5781 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005782
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005783 if (ActuallyDoIt) {
5784 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5785 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005786
Andrew Trickef9de2a2013-05-25 02:42:55 +00005787 SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005788 ISD::SETNE);
Richard Sandiforde3827752013-08-16 10:55:47 +00005789 processIntegerCallValue(I, Res, false);
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005790 return true;
5791 }
Chris Lattner1a32ede2009-12-24 00:37:38 +00005792 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005793
5794
Chris Lattner1a32ede2009-12-24 00:37:38 +00005795 return false;
5796}
5797
Richard Sandiford6f6d5512013-08-20 09:38:48 +00005798/// visitMemChrCall -- See if we can lower a memchr call into an optimized
5799/// form. If so, return true and lower it, otherwise return false and it
5800/// will be lowered like a normal call.
5801bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
5802 // Verify that the prototype makes sense. void *memchr(void *, int, size_t)
5803 if (I.getNumArgOperands() != 3)
5804 return false;
5805
5806 const Value *Src = I.getArgOperand(0);
5807 const Value *Char = I.getArgOperand(1);
5808 const Value *Length = I.getArgOperand(2);
5809 if (!Src->getType()->isPointerTy() ||
5810 !Char->getType()->isIntegerTy() ||
5811 !Length->getType()->isIntegerTy() ||
5812 !I.getType()->isPointerTy())
5813 return false;
5814
5815 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5816 std::pair<SDValue, SDValue> Res =
5817 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
5818 getValue(Src), getValue(Char), getValue(Length),
5819 MachinePointerInfo(Src));
5820 if (Res.first.getNode()) {
5821 setValue(&I, Res.first);
5822 PendingLoads.push_back(Res.second);
5823 return true;
5824 }
5825
5826 return false;
5827}
5828
Richard Sandifordbb83a502013-08-16 11:29:37 +00005829/// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
5830/// optimized form. If so, return true and lower it, otherwise return false
5831/// and it will be lowered like a normal call.
5832bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
5833 // Verify that the prototype makes sense. char *strcpy(char *, char *)
5834 if (I.getNumArgOperands() != 2)
5835 return false;
5836
5837 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5838 if (!Arg0->getType()->isPointerTy() ||
5839 !Arg1->getType()->isPointerTy() ||
5840 !I.getType()->isPointerTy())
5841 return false;
5842
5843 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5844 std::pair<SDValue, SDValue> Res =
5845 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
5846 getValue(Arg0), getValue(Arg1),
5847 MachinePointerInfo(Arg0),
5848 MachinePointerInfo(Arg1), isStpcpy);
5849 if (Res.first.getNode()) {
5850 setValue(&I, Res.first);
5851 DAG.setRoot(Res.second);
5852 return true;
5853 }
5854
5855 return false;
5856}
5857
Richard Sandifordca232712013-08-16 11:21:54 +00005858/// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
5859/// If so, return true and lower it, otherwise return false and it will be
5860/// lowered like a normal call.
5861bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
5862 // Verify that the prototype makes sense. int strcmp(void*,void*)
5863 if (I.getNumArgOperands() != 2)
5864 return false;
5865
5866 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5867 if (!Arg0->getType()->isPointerTy() ||
5868 !Arg1->getType()->isPointerTy() ||
5869 !I.getType()->isIntegerTy())
5870 return false;
5871
5872 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5873 std::pair<SDValue, SDValue> Res =
5874 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5875 getValue(Arg0), getValue(Arg1),
5876 MachinePointerInfo(Arg0),
5877 MachinePointerInfo(Arg1));
5878 if (Res.first.getNode()) {
5879 processIntegerCallValue(I, Res.first, true);
5880 PendingLoads.push_back(Res.second);
5881 return true;
5882 }
5883
5884 return false;
5885}
5886
Richard Sandiford0dec06a2013-08-16 11:41:43 +00005887/// visitStrLenCall -- See if we can lower a strlen call into an optimized
5888/// form. If so, return true and lower it, otherwise return false and it
5889/// will be lowered like a normal call.
5890bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
5891 // Verify that the prototype makes sense. size_t strlen(char *)
5892 if (I.getNumArgOperands() != 1)
5893 return false;
5894
5895 const Value *Arg0 = I.getArgOperand(0);
5896 if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
5897 return false;
5898
5899 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5900 std::pair<SDValue, SDValue> Res =
5901 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
5902 getValue(Arg0), MachinePointerInfo(Arg0));
5903 if (Res.first.getNode()) {
5904 processIntegerCallValue(I, Res.first, false);
5905 PendingLoads.push_back(Res.second);
5906 return true;
5907 }
5908
5909 return false;
5910}
5911
5912/// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
5913/// form. If so, return true and lower it, otherwise return false and it
5914/// will be lowered like a normal call.
5915bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
5916 // Verify that the prototype makes sense. size_t strnlen(char *, size_t)
5917 if (I.getNumArgOperands() != 2)
5918 return false;
5919
5920 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5921 if (!Arg0->getType()->isPointerTy() ||
5922 !Arg1->getType()->isIntegerTy() ||
5923 !I.getType()->isIntegerTy())
5924 return false;
5925
5926 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5927 std::pair<SDValue, SDValue> Res =
5928 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
5929 getValue(Arg0), getValue(Arg1),
5930 MachinePointerInfo(Arg0));
5931 if (Res.first.getNode()) {
5932 processIntegerCallValue(I, Res.first, false);
5933 PendingLoads.push_back(Res.second);
5934 return true;
5935 }
5936
5937 return false;
5938}
5939
Bob Wilson874886c2012-08-03 23:29:17 +00005940/// visitUnaryFloatCall - If a call instruction is a unary floating-point
5941/// operation (as expected), translate it to an SDNode with the specified opcode
5942/// and return true.
5943bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
5944 unsigned Opcode) {
5945 // Sanity check that it really is a unary floating-point call.
5946 if (I.getNumArgOperands() != 1 ||
5947 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5948 I.getType() != I.getArgOperand(0)->getType() ||
5949 !I.onlyReadsMemory())
5950 return false;
5951
5952 SDValue Tmp = getValue(I.getArgOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005953 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
Bob Wilson874886c2012-08-03 23:29:17 +00005954 return true;
5955}
Chris Lattner1a32ede2009-12-24 00:37:38 +00005956
Matt Arsenault4b7bd2d2014-10-24 18:13:10 +00005957/// visitBinaryFloatCall - If a call instruction is a binary floating-point
Matt Arsenault7c936902014-10-21 23:01:01 +00005958/// operation (as expected), translate it to an SDNode with the specified opcode
5959/// and return true.
5960bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
5961 unsigned Opcode) {
Matt Arsenault4b7bd2d2014-10-24 18:13:10 +00005962 // Sanity check that it really is a binary floating-point call.
Matt Arsenault7c936902014-10-21 23:01:01 +00005963 if (I.getNumArgOperands() != 2 ||
5964 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5965 I.getType() != I.getArgOperand(0)->getType() ||
5966 I.getType() != I.getArgOperand(1)->getType() ||
5967 !I.onlyReadsMemory())
5968 return false;
5969
5970 SDValue Tmp0 = getValue(I.getArgOperand(0));
5971 SDValue Tmp1 = getValue(I.getArgOperand(1));
5972 EVT VT = Tmp0.getValueType();
5973 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
5974 return true;
5975}
5976
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005977void SelectionDAGBuilder::visitCall(const CallInst &I) {
Chris Lattner2c0315a2010-07-05 05:36:21 +00005978 // Handle inline assembly differently.
5979 if (isa<InlineAsm>(I.getCalledValue())) {
5980 visitInlineAsm(&I);
5981 return;
5982 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00005983
Michael J. Spencer0e36e032010-10-21 20:49:23 +00005984 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Michael J. Spencer8b98bf22012-02-22 19:06:13 +00005985 ComputeUsesVAFloatArgument(I, &MMI);
Michael J. Spencer0e36e032010-10-21 20:49:23 +00005986
Craig Topperc0196b12014-04-14 00:51:57 +00005987 const char *RenameFn = nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005988 if (Function *F = I.getCalledFunction()) {
5989 if (F->isDeclaration()) {
Chris Lattner2c0315a2010-07-05 05:36:21 +00005990 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
Dale Johannesenb842d522009-02-05 01:49:45 +00005991 if (unsigned IID = II->getIntrinsicID(F)) {
5992 RenameFn = visitIntrinsicCall(I, IID);
5993 if (!RenameFn)
5994 return;
5995 }
5996 }
Dan Gohman575fad32008-09-03 16:12:24 +00005997 if (unsigned IID = F->getIntrinsicID()) {
5998 RenameFn = visitIntrinsicCall(I, IID);
5999 if (!RenameFn)
6000 return;
6001 }
6002 }
6003
6004 // Check for well-known libc/libm calls. If the function is internal, it
6005 // can't be a library call.
Bob Wilson871701c2012-08-03 21:26:24 +00006006 LibFunc::Func Func;
6007 if (!F->hasLocalLinkage() && F->hasName() &&
6008 LibInfo->getLibFunc(F->getName(), Func) &&
6009 LibInfo->hasOptimizedCodeGen(Func)) {
6010 switch (Func) {
6011 default: break;
6012 case LibFunc::copysign:
6013 case LibFunc::copysignf:
6014 case LibFunc::copysignl:
Gabor Greiff69acfe2010-06-30 12:55:46 +00006015 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
Gabor Greifeba0be72010-06-25 09:38:13 +00006016 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
6017 I.getType() == I.getArgOperand(0)->getType() &&
Bob Wilson874886c2012-08-03 23:29:17 +00006018 I.getType() == I.getArgOperand(1)->getType() &&
6019 I.onlyReadsMemory()) {
Gabor Greifeba0be72010-06-25 09:38:13 +00006020 SDValue LHS = getValue(I.getArgOperand(0));
6021 SDValue RHS = getValue(I.getArgOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006022 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
Bill Wendling0602f392009-12-23 01:28:19 +00006023 LHS.getValueType(), LHS, RHS));
Dan Gohman575fad32008-09-03 16:12:24 +00006024 return;
6025 }
Bob Wilson871701c2012-08-03 21:26:24 +00006026 break;
6027 case LibFunc::fabs:
6028 case LibFunc::fabsf:
6029 case LibFunc::fabsl:
Bob Wilson874886c2012-08-03 23:29:17 +00006030 if (visitUnaryFloatCall(I, ISD::FABS))
Dan Gohman575fad32008-09-03 16:12:24 +00006031 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006032 break;
Matt Arsenault7c936902014-10-21 23:01:01 +00006033 case LibFunc::fmin:
6034 case LibFunc::fminf:
6035 case LibFunc::fminl:
6036 if (visitBinaryFloatCall(I, ISD::FMINNUM))
6037 return;
6038 break;
6039 case LibFunc::fmax:
6040 case LibFunc::fmaxf:
6041 case LibFunc::fmaxl:
6042 if (visitBinaryFloatCall(I, ISD::FMAXNUM))
6043 return;
6044 break;
Bob Wilson871701c2012-08-03 21:26:24 +00006045 case LibFunc::sin:
6046 case LibFunc::sinf:
6047 case LibFunc::sinl:
Bob Wilson874886c2012-08-03 23:29:17 +00006048 if (visitUnaryFloatCall(I, ISD::FSIN))
Dan Gohman575fad32008-09-03 16:12:24 +00006049 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006050 break;
6051 case LibFunc::cos:
6052 case LibFunc::cosf:
6053 case LibFunc::cosl:
Bob Wilson874886c2012-08-03 23:29:17 +00006054 if (visitUnaryFloatCall(I, ISD::FCOS))
Dan Gohman575fad32008-09-03 16:12:24 +00006055 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006056 break;
6057 case LibFunc::sqrt:
6058 case LibFunc::sqrtf:
6059 case LibFunc::sqrtl:
Preston Gurd048f99d2013-05-27 15:44:35 +00006060 case LibFunc::sqrt_finite:
6061 case LibFunc::sqrtf_finite:
6062 case LibFunc::sqrtl_finite:
Bob Wilson874886c2012-08-03 23:29:17 +00006063 if (visitUnaryFloatCall(I, ISD::FSQRT))
Dale Johannesenc7213422009-09-25 17:23:22 +00006064 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006065 break;
6066 case LibFunc::floor:
6067 case LibFunc::floorf:
6068 case LibFunc::floorl:
Bob Wilson874886c2012-08-03 23:29:17 +00006069 if (visitUnaryFloatCall(I, ISD::FFLOOR))
Owen Anderson0b9b9da2011-12-08 19:32:14 +00006070 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006071 break;
6072 case LibFunc::nearbyint:
6073 case LibFunc::nearbyintf:
6074 case LibFunc::nearbyintl:
Bob Wilson874886c2012-08-03 23:29:17 +00006075 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
Owen Anderson0b9b9da2011-12-08 19:32:14 +00006076 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006077 break;
6078 case LibFunc::ceil:
6079 case LibFunc::ceilf:
6080 case LibFunc::ceill:
Bob Wilson874886c2012-08-03 23:29:17 +00006081 if (visitUnaryFloatCall(I, ISD::FCEIL))
Owen Anderson0b9b9da2011-12-08 19:32:14 +00006082 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006083 break;
6084 case LibFunc::rint:
6085 case LibFunc::rintf:
6086 case LibFunc::rintl:
Bob Wilson874886c2012-08-03 23:29:17 +00006087 if (visitUnaryFloatCall(I, ISD::FRINT))
Owen Anderson0b9b9da2011-12-08 19:32:14 +00006088 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006089 break;
Hal Finkel171817e2013-08-07 22:49:12 +00006090 case LibFunc::round:
6091 case LibFunc::roundf:
6092 case LibFunc::roundl:
6093 if (visitUnaryFloatCall(I, ISD::FROUND))
6094 return;
6095 break;
Bob Wilson871701c2012-08-03 21:26:24 +00006096 case LibFunc::trunc:
6097 case LibFunc::truncf:
6098 case LibFunc::truncl:
Bob Wilson874886c2012-08-03 23:29:17 +00006099 if (visitUnaryFloatCall(I, ISD::FTRUNC))
Owen Anderson0b9b9da2011-12-08 19:32:14 +00006100 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006101 break;
6102 case LibFunc::log2:
6103 case LibFunc::log2f:
6104 case LibFunc::log2l:
Bob Wilson874886c2012-08-03 23:29:17 +00006105 if (visitUnaryFloatCall(I, ISD::FLOG2))
Owen Andersone7f329f2011-12-15 00:54:12 +00006106 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006107 break;
6108 case LibFunc::exp2:
6109 case LibFunc::exp2f:
6110 case LibFunc::exp2l:
Bob Wilson874886c2012-08-03 23:29:17 +00006111 if (visitUnaryFloatCall(I, ISD::FEXP2))
Owen Andersone7f329f2011-12-15 00:54:12 +00006112 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006113 break;
6114 case LibFunc::memcmp:
Chris Lattner1a32ede2009-12-24 00:37:38 +00006115 if (visitMemCmpCall(I))
6116 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006117 break;
Richard Sandiford6f6d5512013-08-20 09:38:48 +00006118 case LibFunc::memchr:
6119 if (visitMemChrCall(I))
6120 return;
6121 break;
Richard Sandifordbb83a502013-08-16 11:29:37 +00006122 case LibFunc::strcpy:
6123 if (visitStrCpyCall(I, false))
6124 return;
6125 break;
6126 case LibFunc::stpcpy:
6127 if (visitStrCpyCall(I, true))
6128 return;
6129 break;
Richard Sandifordca232712013-08-16 11:21:54 +00006130 case LibFunc::strcmp:
6131 if (visitStrCmpCall(I))
6132 return;
6133 break;
Richard Sandiford0dec06a2013-08-16 11:41:43 +00006134 case LibFunc::strlen:
6135 if (visitStrLenCall(I))
6136 return;
6137 break;
6138 case LibFunc::strnlen:
6139 if (visitStrNLenCall(I))
6140 return;
6141 break;
Dan Gohman575fad32008-09-03 16:12:24 +00006142 }
6143 }
Dan Gohman575fad32008-09-03 16:12:24 +00006144 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006145
Dan Gohman575fad32008-09-03 16:12:24 +00006146 SDValue Callee;
6147 if (!RenameFn)
Gabor Greifeba0be72010-06-25 09:38:13 +00006148 Callee = getValue(I.getCalledValue());
Dan Gohman575fad32008-09-03 16:12:24 +00006149 else
Eric Christopher58a24612014-10-08 09:50:54 +00006150 Callee = DAG.getExternalSymbol(RenameFn,
6151 DAG.getTargetLoweringInfo().getPointerTy());
Dan Gohman575fad32008-09-03 16:12:24 +00006152
Bill Wendling0602f392009-12-23 01:28:19 +00006153 // Check if we can potentially perform a tail call. More detailed checking is
6154 // be done within LowerCallTo, after more information about the call is known.
Evan Chengc35b5a12010-01-26 23:13:04 +00006155 LowerCallTo(&I, Callee, I.isTailCall());
Dan Gohman575fad32008-09-03 16:12:24 +00006156}
6157
Benjamin Kramer355ce072011-03-26 16:35:10 +00006158namespace {
Dan Gohman4db93c92010-05-29 17:53:24 +00006159
Dan Gohman575fad32008-09-03 16:12:24 +00006160/// AsmOperandInfo - This contains information for each constraint that we are
6161/// lowering.
Benjamin Kramer355ce072011-03-26 16:35:10 +00006162class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
Cedric Venetd1e179d2009-02-14 16:06:42 +00006163public:
Dan Gohman575fad32008-09-03 16:12:24 +00006164 /// CallOperand - If this is the result output operand or a clobber
6165 /// this is null, otherwise it is the incoming operand to the CallInst.
6166 /// This gets modified as the asm is processed.
6167 SDValue CallOperand;
6168
6169 /// AssignedRegs - If this is a register or register class operand, this
6170 /// contains the set of register corresponding to the operand.
6171 RegsForValue AssignedRegs;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006172
John Thompson1094c802010-09-13 18:15:37 +00006173 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
Craig Topperc0196b12014-04-14 00:51:57 +00006174 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
Dan Gohman575fad32008-09-03 16:12:24 +00006175 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006176
Owen Anderson53aa7a92009-08-10 22:56:29 +00006177 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
Chris Lattner3b1833c2008-10-17 17:05:25 +00006178 /// corresponds to. If there is no Value* for this operand, it returns
Owen Anderson9f944592009-08-11 20:47:22 +00006179 /// MVT::Other.
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00006180 EVT getCallOperandValEVT(LLVMContext &Context,
Owen Anderson55f1c092009-08-13 21:58:54 +00006181 const TargetLowering &TLI,
Rafael Espindola5f57f462014-02-21 18:34:28 +00006182 const DataLayout *DL) const {
Craig Topperc0196b12014-04-14 00:51:57 +00006183 if (!CallOperandVal) return MVT::Other;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006184
Chris Lattner3b1833c2008-10-17 17:05:25 +00006185 if (isa<BasicBlock>(CallOperandVal))
6186 return TLI.getPointerTy();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006187
Chris Lattner229907c2011-07-18 04:54:35 +00006188 llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006189
Eric Christopher44804282011-05-09 20:04:43 +00006190 // FIXME: code duplicated from TargetLowering::ParseConstraints().
Chris Lattner3b1833c2008-10-17 17:05:25 +00006191 // If this is an indirect operand, the operand is a pointer to the
6192 // accessed type.
Bob Wilsonbac37ab2009-12-22 18:34:19 +00006193 if (isIndirect) {
Chris Lattner229907c2011-07-18 04:54:35 +00006194 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
Bob Wilsonbac37ab2009-12-22 18:34:19 +00006195 if (!PtrTy)
Chris Lattner2104b8d2010-04-07 22:58:41 +00006196 report_fatal_error("Indirect operand for inline asm not a pointer!");
Bob Wilsonbac37ab2009-12-22 18:34:19 +00006197 OpTy = PtrTy->getElementType();
6198 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006199
Eric Christopher44804282011-05-09 20:04:43 +00006200 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
Chris Lattner229907c2011-07-18 04:54:35 +00006201 if (StructType *STy = dyn_cast<StructType>(OpTy))
Eric Christopher44804282011-05-09 20:04:43 +00006202 if (STy->getNumElements() == 1)
6203 OpTy = STy->getElementType(0);
6204
Chris Lattner3b1833c2008-10-17 17:05:25 +00006205 // If OpTy is not a single value, it may be a struct/union that we
6206 // can tile with integers.
6207 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
Rafael Espindola5f57f462014-02-21 18:34:28 +00006208 unsigned BitSize = DL->getTypeSizeInBits(OpTy);
Chris Lattner3b1833c2008-10-17 17:05:25 +00006209 switch (BitSize) {
6210 default: break;
6211 case 1:
6212 case 8:
6213 case 16:
6214 case 32:
6215 case 64:
Chris Lattneraadf7412008-10-17 19:59:51 +00006216 case 128:
Owen Anderson55f1c092009-08-13 21:58:54 +00006217 OpTy = IntegerType::get(Context, BitSize);
Chris Lattner3b1833c2008-10-17 17:05:25 +00006218 break;
6219 }
6220 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006221
Chris Lattner3b1833c2008-10-17 17:05:25 +00006222 return TLI.getValueType(OpTy, true);
6223 }
Dan Gohman575fad32008-09-03 16:12:24 +00006224};
Dan Gohman4db93c92010-05-29 17:53:24 +00006225
John Thompsone8360b72010-10-29 17:29:13 +00006226typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
6227
Benjamin Kramer355ce072011-03-26 16:35:10 +00006228} // end anonymous namespace
Dan Gohman575fad32008-09-03 16:12:24 +00006229
Dan Gohman575fad32008-09-03 16:12:24 +00006230/// GetRegistersForValue - Assign registers (virtual or physical) for the
6231/// specified operand. We prefer to assign virtual registers, to allow the
Bob Wilson1c00b692009-12-17 05:07:36 +00006232/// register allocator to handle the assignment process. However, if the asm
6233/// uses features that we can't model on machineinstrs, we have SDISel do the
Dan Gohman575fad32008-09-03 16:12:24 +00006234/// allocation. This produces generally horrible, but correct, code.
6235///
6236/// OpInfo describes the operand.
Dan Gohman575fad32008-09-03 16:12:24 +00006237///
Benjamin Kramer355ce072011-03-26 16:35:10 +00006238static void GetRegistersForValue(SelectionDAG &DAG,
6239 const TargetLowering &TLI,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006240 SDLoc DL,
Benjamin Kramer6fe3e3d2012-02-24 14:01:17 +00006241 SDISelAsmOperandInfo &OpInfo) {
Benjamin Kramer355ce072011-03-26 16:35:10 +00006242 LLVMContext &Context = *DAG.getContext();
Owen Anderson117c9e82009-08-12 00:36:31 +00006243
Dan Gohman575fad32008-09-03 16:12:24 +00006244 MachineFunction &MF = DAG.getMachineFunction();
6245 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006246
Dan Gohman575fad32008-09-03 16:12:24 +00006247 // If this is a constraint for a single physreg, or a constraint for a
6248 // register class, find it.
Eric Christopher11e4df72015-02-26 22:38:43 +00006249 std::pair<unsigned, const TargetRegisterClass *> PhysReg =
6250 TLI.getRegForInlineAsmConstraint(MF.getSubtarget().getRegisterInfo(),
6251 OpInfo.ConstraintCode,
6252 OpInfo.ConstraintVT);
Dan Gohman575fad32008-09-03 16:12:24 +00006253
6254 unsigned NumRegs = 1;
Owen Anderson9f944592009-08-11 20:47:22 +00006255 if (OpInfo.ConstraintVT != MVT::Other) {
Chris Lattner4396e0d2008-10-21 00:45:36 +00006256 // If this is a FP input in an integer register (or visa versa) insert a bit
6257 // cast of the input value. More generally, handle any case where the input
6258 // value disagrees with the register class we plan to stick this in.
6259 if (OpInfo.Type == InlineAsm::isInput &&
6260 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006261 // Try to convert to the first EVT that the reg class contains. If the
Chris Lattner4396e0d2008-10-21 00:45:36 +00006262 // types are identical size, use a bitcast to convert (e.g. two differing
6263 // vector types).
Patrik Hagglund4e0f8282012-12-19 12:23:01 +00006264 MVT RegVT = *PhysReg.second->vt_begin();
Kevin Qin275ce912014-03-21 02:14:50 +00006265 if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
Benjamin Kramer355ce072011-03-26 16:35:10 +00006266 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
Dale Johannesened255b32009-01-30 01:34:22 +00006267 RegVT, OpInfo.CallOperand);
Chris Lattner4396e0d2008-10-21 00:45:36 +00006268 OpInfo.ConstraintVT = RegVT;
6269 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
6270 // If the input is a FP value and we want it in FP registers, do a
6271 // bitcast to the corresponding integer type. This turns an f64 value
6272 // into i64, which can be passed with two i32 values on a 32-bit
6273 // machine.
Patrik Hagglund4e0f8282012-12-19 12:23:01 +00006274 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
Benjamin Kramer355ce072011-03-26 16:35:10 +00006275 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
Dale Johannesened255b32009-01-30 01:34:22 +00006276 RegVT, OpInfo.CallOperand);
Chris Lattner4396e0d2008-10-21 00:45:36 +00006277 OpInfo.ConstraintVT = RegVT;
6278 }
6279 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006280
Owen Anderson117c9e82009-08-12 00:36:31 +00006281 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
Chris Lattner4396e0d2008-10-21 00:45:36 +00006282 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006283
Patrik Hagglund4e0f8282012-12-19 12:23:01 +00006284 MVT RegVT;
Owen Anderson53aa7a92009-08-10 22:56:29 +00006285 EVT ValueVT = OpInfo.ConstraintVT;
Dan Gohman575fad32008-09-03 16:12:24 +00006286
6287 // If this is a constraint for a specific physical register, like {r17},
6288 // assign it now.
Chris Lattnerc35847e2009-03-24 15:27:37 +00006289 if (unsigned AssignedReg = PhysReg.first) {
6290 const TargetRegisterClass *RC = PhysReg.second;
Owen Anderson9f944592009-08-11 20:47:22 +00006291 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnerc35847e2009-03-24 15:27:37 +00006292 ValueVT = *RC->vt_begin();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006293
Dan Gohman575fad32008-09-03 16:12:24 +00006294 // Get the actual register value type. This is important, because the user
6295 // may have asked for (e.g.) the AX register in i32 type. We need to
6296 // remember that AX is actually i16 to get the right extension.
Chris Lattnerc35847e2009-03-24 15:27:37 +00006297 RegVT = *RC->vt_begin();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006298
Dan Gohman575fad32008-09-03 16:12:24 +00006299 // This is a explicit reference to a physical register.
Chris Lattnerc35847e2009-03-24 15:27:37 +00006300 Regs.push_back(AssignedReg);
Dan Gohman575fad32008-09-03 16:12:24 +00006301
6302 // If this is an expanded reference, add the rest of the regs to Regs.
6303 if (NumRegs != 1) {
Chris Lattnerc35847e2009-03-24 15:27:37 +00006304 TargetRegisterClass::iterator I = RC->begin();
6305 for (; *I != AssignedReg; ++I)
6306 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006307
Dan Gohman575fad32008-09-03 16:12:24 +00006308 // Already added the first reg.
6309 --NumRegs; ++I;
6310 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnerc35847e2009-03-24 15:27:37 +00006311 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohman575fad32008-09-03 16:12:24 +00006312 Regs.push_back(*I);
6313 }
6314 }
Bill Wendlingac087582009-12-22 01:25:10 +00006315
Dan Gohmand16aa542010-05-29 17:03:36 +00006316 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
Dan Gohman575fad32008-09-03 16:12:24 +00006317 return;
6318 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006319
Dan Gohman575fad32008-09-03 16:12:24 +00006320 // Otherwise, if this was a reference to an LLVM register class, create vregs
6321 // for this reference.
Chris Lattner42eceb32009-03-24 15:25:07 +00006322 if (const TargetRegisterClass *RC = PhysReg.second) {
6323 RegVT = *RC->vt_begin();
Owen Anderson9f944592009-08-11 20:47:22 +00006324 if (OpInfo.ConstraintVT == MVT::Other)
Evan Cheng968c3b02009-03-23 08:01:15 +00006325 ValueVT = RegVT;
Dan Gohman575fad32008-09-03 16:12:24 +00006326
Evan Cheng968c3b02009-03-23 08:01:15 +00006327 // Create the appropriate number of virtual registers.
6328 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6329 for (; NumRegs; --NumRegs)
Chris Lattner42eceb32009-03-24 15:25:07 +00006330 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006331
Dan Gohmand16aa542010-05-29 17:03:36 +00006332 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
Evan Cheng968c3b02009-03-23 08:01:15 +00006333 return;
Dan Gohman575fad32008-09-03 16:12:24 +00006334 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00006335
Dan Gohman575fad32008-09-03 16:12:24 +00006336 // Otherwise, we couldn't allocate enough registers for this.
6337}
6338
Dan Gohman575fad32008-09-03 16:12:24 +00006339/// visitInlineAsm - Handle a call to an InlineAsm object.
6340///
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006341void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
6342 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Dan Gohman575fad32008-09-03 16:12:24 +00006343
6344 /// ConstraintOperands - Information about all of the constraints.
John Thompsone8360b72010-10-29 17:29:13 +00006345 SDISelAsmOperandInfoVector ConstraintOperands;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006346
Eric Christopher58a24612014-10-08 09:50:54 +00006347 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Eric Christopher11e4df72015-02-26 22:38:43 +00006348 TargetLowering::AsmOperandInfoVector TargetConstraints =
6349 TLI.ParseConstraints(DAG.getSubtarget().getRegisterInfo(), CS);
Evan Chengd26fc5e2011-05-06 20:52:23 +00006350
John Thompson1094c802010-09-13 18:15:37 +00006351 bool hasMemory = false;
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006352
Dan Gohman575fad32008-09-03 16:12:24 +00006353 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6354 unsigned ResNo = 0; // ResNo - The result number of the next output.
John Thompson1094c802010-09-13 18:15:37 +00006355 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6356 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
Dan Gohman575fad32008-09-03 16:12:24 +00006357 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006358
Patrik Hagglundf9934612012-12-19 15:19:11 +00006359 MVT OpVT = MVT::Other;
Dan Gohman575fad32008-09-03 16:12:24 +00006360
6361 // Compute the value type for each operand.
6362 switch (OpInfo.Type) {
6363 case InlineAsm::isOutput:
6364 // Indirect outputs just consume an argument.
6365 if (OpInfo.isIndirect) {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006366 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Dan Gohman575fad32008-09-03 16:12:24 +00006367 break;
6368 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006369
Dan Gohman575fad32008-09-03 16:12:24 +00006370 // The return value of the call is this value. As such, there is no
6371 // corresponding argument.
Nick Lewyckyf40df1d2011-09-30 22:19:53 +00006372 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
Chris Lattner229907c2011-07-18 04:54:35 +00006373 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
Eric Christopher58a24612014-10-08 09:50:54 +00006374 OpVT = TLI.getSimpleValueType(STy->getElementType(ResNo));
Dan Gohman575fad32008-09-03 16:12:24 +00006375 } else {
6376 assert(ResNo == 0 && "Asm only has one result!");
Eric Christopher58a24612014-10-08 09:50:54 +00006377 OpVT = TLI.getSimpleValueType(CS.getType());
Dan Gohman575fad32008-09-03 16:12:24 +00006378 }
6379 ++ResNo;
6380 break;
6381 case InlineAsm::isInput:
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006382 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Dan Gohman575fad32008-09-03 16:12:24 +00006383 break;
6384 case InlineAsm::isClobber:
6385 // Nothing to do.
6386 break;
6387 }
6388
6389 // If this is an input or an indirect output, process the call argument.
6390 // BasicBlocks are labels, currently appearing only in asm's.
6391 if (OpInfo.CallOperandVal) {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006392 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohman575fad32008-09-03 16:12:24 +00006393 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner3b1833c2008-10-17 17:05:25 +00006394 } else {
Dan Gohman575fad32008-09-03 16:12:24 +00006395 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohman575fad32008-09-03 16:12:24 +00006396 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006397
Eric Christopher58a24612014-10-08 09:50:54 +00006398 OpVT =
6399 OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, DL).getSimpleVT();
Dan Gohman575fad32008-09-03 16:12:24 +00006400 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006401
Dan Gohman575fad32008-09-03 16:12:24 +00006402 OpInfo.ConstraintVT = OpVT;
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006403
John Thompson1094c802010-09-13 18:15:37 +00006404 // Indirect operand accesses access memory.
6405 if (OpInfo.isIndirect)
6406 hasMemory = true;
6407 else {
6408 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
Evan Chengd26fc5e2011-05-06 20:52:23 +00006409 TargetLowering::ConstraintType
Eric Christopher58a24612014-10-08 09:50:54 +00006410 CType = TLI.getConstraintType(OpInfo.Codes[j]);
John Thompson1094c802010-09-13 18:15:37 +00006411 if (CType == TargetLowering::C_Memory) {
6412 hasMemory = true;
6413 break;
6414 }
6415 }
6416 }
Chris Lattner160e8ab2008-10-18 18:49:30 +00006417 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006418
John Thompson1094c802010-09-13 18:15:37 +00006419 SDValue Chain, Flag;
6420
6421 // We won't need to flush pending loads if this asm doesn't touch
6422 // memory and is nonvolatile.
6423 if (hasMemory || IA->hasSideEffects())
6424 Chain = getRoot();
6425 else
6426 Chain = DAG.getRoot();
6427
Chris Lattner160e8ab2008-10-18 18:49:30 +00006428 // Second pass over the constraints: compute which constraint option to use
6429 // and assign registers to constraints that want a specific physreg.
John Thompson1094c802010-09-13 18:15:37 +00006430 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Chris Lattner160e8ab2008-10-18 18:49:30 +00006431 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006432
John Thompson8118ef82010-09-24 22:24:05 +00006433 // If this is an output operand with a matching input operand, look up the
6434 // matching input. If their types mismatch, e.g. one is an integer, the
6435 // other is floating point, or their sizes are different, flag it as an
6436 // error.
6437 if (OpInfo.hasMatchingInput()) {
6438 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006439
John Thompson8118ef82010-09-24 22:24:05 +00006440 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Eric Christopher11e4df72015-02-26 22:38:43 +00006441 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
6442 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
6443 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
6444 OpInfo.ConstraintVT);
6445 std::pair<unsigned, const TargetRegisterClass *> InputRC =
6446 TLI.getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
6447 Input.ConstraintVT);
John Thompson8118ef82010-09-24 22:24:05 +00006448 if ((OpInfo.ConstraintVT.isInteger() !=
6449 Input.ConstraintVT.isInteger()) ||
Eric Christopher92464be2011-07-14 20:13:52 +00006450 (MatchRC.second != InputRC.second)) {
John Thompson8118ef82010-09-24 22:24:05 +00006451 report_fatal_error("Unsupported asm: input constraint"
6452 " with a matching output constraint of"
6453 " incompatible type!");
6454 }
6455 Input.ConstraintVT = OpInfo.ConstraintVT;
6456 }
6457 }
6458
Dan Gohman575fad32008-09-03 16:12:24 +00006459 // Compute the constraint code and ConstraintType to use.
Eric Christopher58a24612014-10-08 09:50:54 +00006460 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Dan Gohman575fad32008-09-03 16:12:24 +00006461
Eric Christopher0cb6fd92013-01-11 18:12:39 +00006462 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6463 OpInfo.Type == InlineAsm::isClobber)
6464 continue;
6465
Dan Gohman575fad32008-09-03 16:12:24 +00006466 // If this is a memory input, and if the operand is not indirect, do what we
6467 // need to to provide an address for the memory input.
6468 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6469 !OpInfo.isIndirect) {
Evan Chengd26fc5e2011-05-06 20:52:23 +00006470 assert((OpInfo.isMultipleAlternative ||
6471 (OpInfo.Type == InlineAsm::isInput)) &&
Dan Gohman575fad32008-09-03 16:12:24 +00006472 "Can only indirectify direct input operands!");
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006473
Dan Gohman575fad32008-09-03 16:12:24 +00006474 // Memory operands really want the address of the value. If we don't have
6475 // an indirect input, put it in the constpool if we can, otherwise spill
6476 // it to a stack slot.
Eric Christopherfbff0e42011-06-03 17:21:23 +00006477 // TODO: This isn't quite right. We need to handle these according to
6478 // the addressing mode that the constraint wants. Also, this may take
6479 // an additional register for the computation and we don't want that
6480 // either.
Eric Christopher0713a9d2011-06-08 23:55:35 +00006481
Dan Gohman575fad32008-09-03 16:12:24 +00006482 // If the operand is a float, integer, or vector constant, spill to a
6483 // constant pool entry to get its address.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006484 const Value *OpVal = OpInfo.CallOperandVal;
Dan Gohman575fad32008-09-03 16:12:24 +00006485 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
Chris Lattner0256be92012-01-27 03:08:05 +00006486 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
Dan Gohman575fad32008-09-03 16:12:24 +00006487 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
Eric Christopher58a24612014-10-08 09:50:54 +00006488 TLI.getPointerTy());
Dan Gohman575fad32008-09-03 16:12:24 +00006489 } else {
6490 // Otherwise, create a stack slot and emit a store to it before the
6491 // asm.
Chris Lattner229907c2011-07-18 04:54:35 +00006492 Type *Ty = OpVal->getType();
Eric Christopher58a24612014-10-08 09:50:54 +00006493 uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
6494 unsigned Align = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
Dan Gohman575fad32008-09-03 16:12:24 +00006495 MachineFunction &MF = DAG.getMachineFunction();
David Greene1fbe0542009-11-12 20:49:22 +00006496 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Eric Christopher58a24612014-10-08 09:50:54 +00006497 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006498 Chain = DAG.getStore(Chain, getCurSDLoc(),
Chris Lattner1ffcf522010-09-21 16:36:31 +00006499 OpInfo.CallOperand, StackSlot,
6500 MachinePointerInfo::getFixedStack(SSFI),
David Greene39c6d012010-02-15 17:00:31 +00006501 false, false, 0);
Dan Gohman575fad32008-09-03 16:12:24 +00006502 OpInfo.CallOperand = StackSlot;
6503 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006504
Dan Gohman575fad32008-09-03 16:12:24 +00006505 // There is no longer a Value* corresponding to this operand.
Craig Topperc0196b12014-04-14 00:51:57 +00006506 OpInfo.CallOperandVal = nullptr;
Bill Wendlingac087582009-12-22 01:25:10 +00006507
Dan Gohman575fad32008-09-03 16:12:24 +00006508 // It is now an indirect operand.
6509 OpInfo.isIndirect = true;
6510 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006511
Dan Gohman575fad32008-09-03 16:12:24 +00006512 // If this constraint is for a specific register, allocate it before
6513 // anything else.
6514 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Eric Christopher58a24612014-10-08 09:50:54 +00006515 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
Dan Gohman575fad32008-09-03 16:12:24 +00006516 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006517
Dan Gohman575fad32008-09-03 16:12:24 +00006518 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattneref890172008-10-17 16:21:11 +00006519 // to register class operands.
Dan Gohman575fad32008-09-03 16:12:24 +00006520 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6521 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006522
Dan Gohman575fad32008-09-03 16:12:24 +00006523 // C_Register operands have already been allocated, Other/Memory don't need
6524 // to be.
6525 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Eric Christopher58a24612014-10-08 09:50:54 +00006526 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006527 }
6528
Dan Gohman575fad32008-09-03 16:12:24 +00006529 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6530 std::vector<SDValue> AsmNodeOperands;
6531 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
6532 AsmNodeOperands.push_back(
Dan Gohmanfeeced42010-01-04 21:00:54 +00006533 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
Eric Christopher58a24612014-10-08 09:50:54 +00006534 TLI.getPointerTy()));
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006535
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006536 // If we have a !srcloc metadata node associated with it, we want to attach
6537 // this to the ultimately generated inline asm machineinstr. To do this, we
6538 // pass in the third operand as this (potentially null) inline asm MDNode.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00006539 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006540 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006541
Chad Rosier9e1274f2012-10-30 19:11:54 +00006542 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6543 // bits as operand 3.
Evan Cheng6eb516d2011-01-07 23:50:32 +00006544 unsigned ExtraInfo = 0;
6545 if (IA->hasSideEffects())
6546 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6547 if (IA->isAlignStack())
6548 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
Chad Rosiercbd2a192012-09-05 22:17:43 +00006549 // Set the asm dialect.
Chad Rosiere53314f2012-09-05 22:40:13 +00006550 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
Chad Rosier9e1274f2012-10-30 19:11:54 +00006551
6552 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6553 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6554 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6555
6556 // Compute the constraint code and ConstraintType to use.
Eric Christopher58a24612014-10-08 09:50:54 +00006557 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chad Rosier9e1274f2012-10-30 19:11:54 +00006558
Chad Rosier86f60502012-10-30 20:01:12 +00006559 // Ideally, we would only check against memory constraints. However, the
6560 // meaning of an other constraint can be target-specific and we can't easily
6561 // reason about it. Therefore, be conservative and set MayLoad/MayStore
6562 // for other constriants as well.
Chad Rosier9e1274f2012-10-30 19:11:54 +00006563 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6564 OpInfo.ConstraintType == TargetLowering::C_Other) {
6565 if (OpInfo.Type == InlineAsm::isInput)
6566 ExtraInfo |= InlineAsm::Extra_MayLoad;
6567 else if (OpInfo.Type == InlineAsm::isOutput)
6568 ExtraInfo |= InlineAsm::Extra_MayStore;
Eric Christopher0cb6fd92013-01-11 18:12:39 +00006569 else if (OpInfo.Type == InlineAsm::isClobber)
6570 ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
Chad Rosier9e1274f2012-10-30 19:11:54 +00006571 }
6572 }
6573
Evan Cheng6eb516d2011-01-07 23:50:32 +00006574 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
Eric Christopher58a24612014-10-08 09:50:54 +00006575 TLI.getPointerTy()));
Dale Johannesen4d887f7c2010-07-02 20:16:09 +00006576
Dan Gohman575fad32008-09-03 16:12:24 +00006577 // Loop over all of the inputs, copying the operand values into the
6578 // appropriate registers and processing the output regs.
6579 RegsForValue RetValRegs;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006580
Dan Gohman575fad32008-09-03 16:12:24 +00006581 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6582 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006583
Dan Gohman575fad32008-09-03 16:12:24 +00006584 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6585 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6586
6587 switch (OpInfo.Type) {
6588 case InlineAsm::isOutput: {
6589 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6590 OpInfo.ConstraintType != TargetLowering::C_Register) {
6591 // Memory output, or 'other' output (e.g. 'X' constraint).
6592 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6593
6594 // Add information to the INLINEASM node to know about this output.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006595 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6596 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
Eric Christopher58a24612014-10-08 09:50:54 +00006597 TLI.getPointerTy()));
Dan Gohman575fad32008-09-03 16:12:24 +00006598 AsmNodeOperands.push_back(OpInfo.CallOperand);
6599 break;
6600 }
6601
6602 // Otherwise, this is a register or register class output.
6603
6604 // Copy the output from the appropriate register. Find a register that
6605 // we can use.
Chris Lattner6b77a072012-01-03 23:51:01 +00006606 if (OpInfo.AssignedRegs.Regs.empty()) {
6607 LLVMContext &Ctx = *DAG.getContext();
Stephen Lincfe7f352013-07-08 00:37:03 +00006608 Ctx.emitError(CS.getInstruction(),
Chris Lattner6b77a072012-01-03 23:51:01 +00006609 "couldn't allocate output register for constraint '" +
Eric Christophere6656ac2013-07-31 01:26:24 +00006610 Twine(OpInfo.ConstraintCode) + "'");
6611 return;
Chris Lattner6b77a072012-01-03 23:51:01 +00006612 }
Dan Gohman575fad32008-09-03 16:12:24 +00006613
6614 // If this is an indirect operand, store through the pointer after the
6615 // asm.
6616 if (OpInfo.isIndirect) {
6617 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6618 OpInfo.CallOperandVal));
6619 } else {
6620 // This is the result value of the call.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00006621 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
Dan Gohman575fad32008-09-03 16:12:24 +00006622 // Concatenate this output onto the outputs list.
6623 RetValRegs.append(OpInfo.AssignedRegs);
6624 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006625
Dan Gohman575fad32008-09-03 16:12:24 +00006626 // Add information to the INLINEASM node to know that this register is
6627 // set.
Eric Christopher029af152013-07-30 22:50:44 +00006628 OpInfo.AssignedRegs
6629 .AddInlineAsmOperands(OpInfo.isEarlyClobber
6630 ? InlineAsm::Kind_RegDefEarlyClobber
6631 : InlineAsm::Kind_RegDef,
6632 false, 0, DAG, AsmNodeOperands);
Dan Gohman575fad32008-09-03 16:12:24 +00006633 break;
6634 }
6635 case InlineAsm::isInput: {
6636 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006637
Chris Lattner860df6e2008-10-17 16:47:46 +00006638 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohman575fad32008-09-03 16:12:24 +00006639 // If this is required to match an output register we have already set,
6640 // just use its register.
Chris Lattneref890172008-10-17 16:21:11 +00006641 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006642
Dan Gohman575fad32008-09-03 16:12:24 +00006643 // Scan until we find the definition we already emitted of this operand.
6644 // When we find it, create a RegsForValue operand.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006645 unsigned CurOp = InlineAsm::Op_FirstOperand;
Dan Gohman575fad32008-09-03 16:12:24 +00006646 for (; OperandNo; --OperandNo) {
6647 // Advance to the next operand.
Evan Cheng2e559232009-03-20 18:03:34 +00006648 unsigned OpFlag =
Dan Gohmaneffb8942008-09-12 16:56:44 +00006649 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006650 assert((InlineAsm::isRegDefKind(OpFlag) ||
6651 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6652 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
Evan Cheng2e559232009-03-20 18:03:34 +00006653 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohman575fad32008-09-03 16:12:24 +00006654 }
6655
Evan Cheng2e559232009-03-20 18:03:34 +00006656 unsigned OpFlag =
Dan Gohmaneffb8942008-09-12 16:56:44 +00006657 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006658 if (InlineAsm::isRegDefKind(OpFlag) ||
6659 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
Evan Cheng2e559232009-03-20 18:03:34 +00006660 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Chris Lattner3c65a832010-04-08 00:09:16 +00006661 if (OpInfo.isIndirect) {
6662 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
Dan Gohman7c0303a2010-04-19 22:41:47 +00006663 LLVMContext &Ctx = *DAG.getContext();
Eric Christophere6656ac2013-07-31 01:26:24 +00006664 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6665 " don't know how to handle tied "
6666 "indirect register inputs");
6667 return;
Chris Lattner3c65a832010-04-08 00:09:16 +00006668 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006669
Dan Gohman575fad32008-09-03 16:12:24 +00006670 RegsForValue MatchedRegs;
Dan Gohman575fad32008-09-03 16:12:24 +00006671 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Patrik Hagglund5e6c3612012-12-13 06:34:11 +00006672 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
Evan Cheng968c3b02009-03-23 08:01:15 +00006673 MatchedRegs.RegVTs.push_back(RegVT);
6674 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng2e559232009-03-20 18:03:34 +00006675 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Chad Rosier108d5a62013-04-24 22:53:10 +00006676 i != e; ++i) {
Eric Christopher58a24612014-10-08 09:50:54 +00006677 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
Chad Rosier108d5a62013-04-24 22:53:10 +00006678 MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
6679 else {
6680 LLVMContext &Ctx = *DAG.getContext();
Eric Christophere6656ac2013-07-31 01:26:24 +00006681 Ctx.emitError(CS.getInstruction(),
6682 "inline asm error: This value"
Chad Rosier108d5a62013-04-24 22:53:10 +00006683 " type register class is not natively supported!");
Eric Christophere6656ac2013-07-31 01:26:24 +00006684 return;
Chad Rosier108d5a62013-04-24 22:53:10 +00006685 }
6686 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006687 // Use the produced MatchedRegs object to
Andrew Trickef9de2a2013-05-25 02:42:55 +00006688 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
Bill Wendling5def8912012-09-26 06:16:18 +00006689 Chain, &Flag, CS.getInstruction());
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006690 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
Evan Cheng968c3b02009-03-23 08:01:15 +00006691 true, OpInfo.getMatchedOperand(),
Bill Wendling78c5b7a2010-03-02 01:55:18 +00006692 DAG, AsmNodeOperands);
Dan Gohman575fad32008-09-03 16:12:24 +00006693 break;
Dan Gohman575fad32008-09-03 16:12:24 +00006694 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006695
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006696 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6697 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6698 "Unexpected number of operands");
6699 // Add information to the INLINEASM node to know about this input.
6700 // See InlineAsm.h isUseOperandTiedToDef.
6701 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6702 OpInfo.getMatchedOperand());
6703 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
Eric Christopher58a24612014-10-08 09:50:54 +00006704 TLI.getPointerTy()));
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006705 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6706 break;
Dan Gohman575fad32008-09-03 16:12:24 +00006707 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006708
Dale Johannesencaca5482010-07-13 20:17:05 +00006709 // Treat indirect 'X' constraint as memory.
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006710 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6711 OpInfo.isIndirect)
Dale Johannesencaca5482010-07-13 20:17:05 +00006712 OpInfo.ConstraintType = TargetLowering::C_Memory;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006713
Dale Johannesencaca5482010-07-13 20:17:05 +00006714 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Dan Gohman575fad32008-09-03 16:12:24 +00006715 std::vector<SDValue> Ops;
Eric Christopher58a24612014-10-08 09:50:54 +00006716 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006717 Ops, DAG);
Chris Lattner6b77a072012-01-03 23:51:01 +00006718 if (Ops.empty()) {
6719 LLVMContext &Ctx = *DAG.getContext();
6720 Ctx.emitError(CS.getInstruction(),
6721 "invalid operand for inline asm constraint '" +
Eric Christophere6656ac2013-07-31 01:26:24 +00006722 Twine(OpInfo.ConstraintCode) + "'");
6723 return;
Chris Lattner6b77a072012-01-03 23:51:01 +00006724 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006725
Dan Gohman575fad32008-09-03 16:12:24 +00006726 // Add information to the INLINEASM node to know about this input.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006727 unsigned ResOpType =
6728 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006729 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Eric Christopher58a24612014-10-08 09:50:54 +00006730 TLI.getPointerTy()));
Dan Gohman575fad32008-09-03 16:12:24 +00006731 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6732 break;
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006733 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006734
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006735 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Dan Gohman575fad32008-09-03 16:12:24 +00006736 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Eric Christopher58a24612014-10-08 09:50:54 +00006737 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
Dan Gohman575fad32008-09-03 16:12:24 +00006738 "Memory operands expect pointer values");
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006739
Dan Gohman575fad32008-09-03 16:12:24 +00006740 // Add information to the INLINEASM node to know about this input.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006741 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
Dale Johannesenc36660d2008-09-24 01:07:17 +00006742 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Eric Christopher58a24612014-10-08 09:50:54 +00006743 TLI.getPointerTy()));
Dan Gohman575fad32008-09-03 16:12:24 +00006744 AsmNodeOperands.push_back(InOperandVal);
6745 break;
6746 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006747
Dan Gohman575fad32008-09-03 16:12:24 +00006748 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6749 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6750 "Unknown constraint type!");
Eric Christopherdd8638f2012-07-02 21:16:43 +00006751
6752 // TODO: Support this.
6753 if (OpInfo.isIndirect) {
6754 LLVMContext &Ctx = *DAG.getContext();
6755 Ctx.emitError(CS.getInstruction(),
6756 "Don't know how to handle indirect register inputs yet "
Eric Christophere6656ac2013-07-31 01:26:24 +00006757 "for constraint '" +
6758 Twine(OpInfo.ConstraintCode) + "'");
6759 return;
Eric Christopherdd8638f2012-07-02 21:16:43 +00006760 }
Dan Gohman575fad32008-09-03 16:12:24 +00006761
6762 // Copy the input into the appropriate registers.
Chris Lattner6b77a072012-01-03 23:51:01 +00006763 if (OpInfo.AssignedRegs.Regs.empty()) {
6764 LLVMContext &Ctx = *DAG.getContext();
Stephen Lincfe7f352013-07-08 00:37:03 +00006765 Ctx.emitError(CS.getInstruction(),
Chris Lattner6b77a072012-01-03 23:51:01 +00006766 "couldn't allocate input reg for constraint '" +
Eric Christophere6656ac2013-07-31 01:26:24 +00006767 Twine(OpInfo.ConstraintCode) + "'");
6768 return;
Chris Lattner6b77a072012-01-03 23:51:01 +00006769 }
Dan Gohman575fad32008-09-03 16:12:24 +00006770
Andrew Trickef9de2a2013-05-25 02:42:55 +00006771 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
Bill Wendling5def8912012-09-26 06:16:18 +00006772 Chain, &Flag, CS.getInstruction());
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006773
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006774 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
Bill Wendling78c5b7a2010-03-02 01:55:18 +00006775 DAG, AsmNodeOperands);
Dan Gohman575fad32008-09-03 16:12:24 +00006776 break;
6777 }
6778 case InlineAsm::isClobber: {
6779 // Add the clobbered value to the operand list, so that the register
6780 // allocator is aware that the physreg got clobbered.
6781 if (!OpInfo.AssignedRegs.Regs.empty())
Jakob Stoklund Olesen537a3022011-06-27 04:08:33 +00006782 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
Bill Wendling78c5b7a2010-03-02 01:55:18 +00006783 false, 0, DAG,
Bill Wendlingac087582009-12-22 01:25:10 +00006784 AsmNodeOperands);
Dan Gohman575fad32008-09-03 16:12:24 +00006785 break;
6786 }
6787 }
6788 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006789
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006790 // Finish up input operands. Set the input chain and add the flag last.
Dale Johannesen4d887f7c2010-07-02 20:16:09 +00006791 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
Dan Gohman575fad32008-09-03 16:12:24 +00006792 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006793
Andrew Trickef9de2a2013-05-25 02:42:55 +00006794 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00006795 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
Dan Gohman575fad32008-09-03 16:12:24 +00006796 Flag = Chain.getValue(1);
6797
6798 // If this asm returns a register value, copy the result from that register
6799 // and set it as the value of the call.
6800 if (!RetValRegs.Regs.empty()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006801 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
Bill Wendling81406f62012-09-26 04:04:19 +00006802 Chain, &Flag, CS.getInstruction());
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006803
Chris Lattner160e8ab2008-10-18 18:49:30 +00006804 // FIXME: Why don't we do this for inline asms with MRVs?
6805 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
Eric Christopher58a24612014-10-08 09:50:54 +00006806 EVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006807
Chris Lattner160e8ab2008-10-18 18:49:30 +00006808 // If any of the results of the inline asm is a vector, it may have the
6809 // wrong width/num elts. This can happen for register classes that can
6810 // contain multiple different value types. The preg or vreg allocated may
6811 // not have the same VT as was expected. Convert it to the right type
6812 // with bit_convert.
6813 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006814 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00006815 ResultType, Val);
Dan Gohman6de25562008-10-18 01:03:45 +00006816
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006817 } else if (ResultType != Val.getValueType() &&
Chris Lattner160e8ab2008-10-18 18:49:30 +00006818 ResultType.isInteger() && Val.getValueType().isInteger()) {
6819 // If a result value was tied to an input value, the computed result may
6820 // have a wider width than the expected result. Extract the relevant
6821 // portion.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006822 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
Dan Gohman6de25562008-10-18 01:03:45 +00006823 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006824
Chris Lattner160e8ab2008-10-18 18:49:30 +00006825 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner052092b2008-10-17 17:52:49 +00006826 }
Dan Gohman6de25562008-10-18 01:03:45 +00006827
Dan Gohman575fad32008-09-03 16:12:24 +00006828 setValue(CS.getInstruction(), Val);
Dale Johannesen83593f42009-04-14 00:56:56 +00006829 // Don't need to use this as a chain in this case.
6830 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6831 return;
Dan Gohman575fad32008-09-03 16:12:24 +00006832 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006833
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006834 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006835
Dan Gohman575fad32008-09-03 16:12:24 +00006836 // Process indirect outputs, first output all of the flagged copies out of
6837 // physregs.
6838 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6839 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006840 const Value *Ptr = IndirectStoresToEmit[i].second;
Andrew Trickef9de2a2013-05-25 02:42:55 +00006841 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
Bill Wendling81406f62012-09-26 04:04:19 +00006842 Chain, &Flag, IA);
Dan Gohman575fad32008-09-03 16:12:24 +00006843 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6844 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006845
Dan Gohman575fad32008-09-03 16:12:24 +00006846 // Emit the non-flagged stores from the physregs.
6847 SmallVector<SDValue, 8> OutChains;
Bill Wendlingac087582009-12-22 01:25:10 +00006848 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006849 SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
Bill Wendlingac087582009-12-22 01:25:10 +00006850 StoresToEmit[i].first,
6851 getValue(StoresToEmit[i].second),
Chris Lattnera4f19972010-09-21 18:58:22 +00006852 MachinePointerInfo(StoresToEmit[i].second),
David Greene39c6d012010-02-15 17:00:31 +00006853 false, false, 0);
Bill Wendlingac087582009-12-22 01:25:10 +00006854 OutChains.push_back(Val);
Bill Wendlingac087582009-12-22 01:25:10 +00006855 }
6856
Dan Gohman575fad32008-09-03 16:12:24 +00006857 if (!OutChains.empty())
Craig Topper48d114b2014-04-26 18:35:24 +00006858 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
Bill Wendlingac087582009-12-22 01:25:10 +00006859
Dan Gohman575fad32008-09-03 16:12:24 +00006860 DAG.setRoot(Chain);
6861}
6862
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006863void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006864 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
Bill Wendling91313062009-12-23 00:44:51 +00006865 MVT::Other, getRoot(),
Gabor Greifeba0be72010-06-25 09:38:13 +00006866 getValue(I.getArgOperand(0)),
6867 DAG.getSrcValue(I.getArgOperand(0))));
Dan Gohman575fad32008-09-03 16:12:24 +00006868}
6869
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006870void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
Eric Christopher58a24612014-10-08 09:50:54 +00006871 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6872 const DataLayout &DL = *TLI.getDataLayout();
6873 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurSDLoc(),
Dale Johannesen3a09f552009-02-03 23:04:43 +00006874 getRoot(), getValue(I.getOperand(0)),
Rafael Espindolaa76eccf2010-07-11 04:01:49 +00006875 DAG.getSrcValue(I.getOperand(0)),
Rafael Espindola5f57f462014-02-21 18:34:28 +00006876 DL.getABITypeAlignment(I.getType()));
Dan Gohman575fad32008-09-03 16:12:24 +00006877 setValue(&I, V);
6878 DAG.setRoot(V.getValue(1));
6879}
6880
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006881void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006882 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
Bill Wendling91313062009-12-23 00:44:51 +00006883 MVT::Other, getRoot(),
Gabor Greifeba0be72010-06-25 09:38:13 +00006884 getValue(I.getArgOperand(0)),
6885 DAG.getSrcValue(I.getArgOperand(0))));
Dan Gohman575fad32008-09-03 16:12:24 +00006886}
6887
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006888void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006889 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
Bill Wendling91313062009-12-23 00:44:51 +00006890 MVT::Other, getRoot(),
Gabor Greifeba0be72010-06-25 09:38:13 +00006891 getValue(I.getArgOperand(0)),
6892 getValue(I.getArgOperand(1)),
6893 DAG.getSrcValue(I.getArgOperand(0)),
6894 DAG.getSrcValue(I.getArgOperand(1))));
Dan Gohman575fad32008-09-03 16:12:24 +00006895}
6896
Andrew Trick74f4c742013-10-31 17:18:24 +00006897/// \brief Lower an argument list according to the target calling convention.
6898///
6899/// \return A tuple of <return-value, token-chain>
6900///
6901/// This is a helper for lowering intrinsics that follow a target calling
6902/// convention or require stack pointer adjustment. Only a subset of the
6903/// intrinsic's operands need to participate in the calling convention.
6904std::pair<SDValue, SDValue>
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00006905SelectionDAGBuilder::lowerCallOperands(ImmutableCallSite CS, unsigned ArgIdx,
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00006906 unsigned NumArgs, SDValue Callee,
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00006907 bool UseVoidTy,
Hal Finkel0ad96c82015-01-13 17:48:04 +00006908 MachineBasicBlock *LandingPad,
6909 bool IsPatchPoint) {
Andrew Trick74f4c742013-10-31 17:18:24 +00006910 TargetLowering::ArgListTy Args;
6911 Args.reserve(NumArgs);
6912
6913 // Populate the argument list.
6914 // Attributes for args start at offset 1, after the return attribute.
Andrew Trick74f4c742013-10-31 17:18:24 +00006915 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
6916 ArgI != ArgE; ++ArgI) {
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00006917 const Value *V = CS->getOperand(ArgI);
Andrew Trick74f4c742013-10-31 17:18:24 +00006918
6919 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
6920
6921 TargetLowering::ArgListEntry Entry;
6922 Entry.Node = getValue(V);
6923 Entry.Ty = V->getType();
6924 Entry.setAttributes(&CS, AttrI);
6925 Args.push_back(Entry);
6926 }
6927
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00006928 Type *retTy = UseVoidTy ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +00006929 TargetLowering::CallLoweringInfo CLI(DAG);
6930 CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00006931 .setCallee(CS.getCallingConv(), retTy, Callee, std::move(Args), NumArgs)
Hal Finkel0ad96c82015-01-13 17:48:04 +00006932 .setDiscardResult(CS->use_empty()).setIsPatchPoint(IsPatchPoint);
Andrew Trick74f4c742013-10-31 17:18:24 +00006933
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00006934 return lowerInvokable(CLI, LandingPad);
Andrew Trick74f4c742013-10-31 17:18:24 +00006935}
6936
Andrew Trick4a1abb72013-11-22 19:07:36 +00006937/// \brief Add a stack map intrinsic call's live variable operands to a stackmap
6938/// or patchpoint target node's operand list.
Andrew Trick391dbad2013-11-26 02:03:25 +00006939///
6940/// Constants are converted to TargetConstants purely as an optimization to
6941/// avoid constant materialization and register allocation.
6942///
6943/// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
6944/// generate addess computation nodes, and so ExpandISelPseudo can convert the
6945/// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
6946/// address materialization and register allocation, but may also be required
6947/// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
6948/// alloca in the entry block, then the runtime may assume that the alloca's
6949/// StackMap location can be read immediately after compilation and that the
6950/// location is valid at any point during execution (this is similar to the
6951/// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
6952/// only available in a register, then the runtime would need to trap when
6953/// execution reaches the StackMap in order to read the alloca's location.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00006954static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
Andrew Trick4a1abb72013-11-22 19:07:36 +00006955 SmallVectorImpl<SDValue> &Ops,
6956 SelectionDAGBuilder &Builder) {
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00006957 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
6958 SDValue OpVal = Builder.getValue(CS.getArgument(i));
Andrew Trick4a1abb72013-11-22 19:07:36 +00006959 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
6960 Ops.push_back(
6961 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
6962 Ops.push_back(
6963 Builder.DAG.getTargetConstant(C->getSExtValue(), MVT::i64));
Andrew Trick391dbad2013-11-26 02:03:25 +00006964 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
6965 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
6966 Ops.push_back(
6967 Builder.DAG.getTargetFrameIndex(FI->getIndex(), TLI.getPointerTy()));
Andrew Trick4a1abb72013-11-22 19:07:36 +00006968 } else
6969 Ops.push_back(OpVal);
6970 }
6971}
6972
Andrew Trick74f4c742013-10-31 17:18:24 +00006973/// \brief Lower llvm.experimental.stackmap directly to its target opcode.
6974void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
6975 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
6976 // [live variables...])
6977
6978 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
6979
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006980 SDValue Chain, InFlag, Callee, NullPtr;
6981 SmallVector<SDValue, 32> Ops;
Andrew Trick74f4c742013-10-31 17:18:24 +00006982
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006983 SDLoc DL = getCurSDLoc();
6984 Callee = getValue(CI.getCalledValue());
6985 NullPtr = DAG.getIntPtrConstant(0, true);
Andrew Trick74f4c742013-10-31 17:18:24 +00006986
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00006987 // The stackmap intrinsic only records the live variables (the arguemnts
6988 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
6989 // intrinsic, this won't be lowered to a function call. This means we don't
6990 // have to worry about calling conventions and target specific lowering code.
6991 // Instead we perform the call lowering right here.
6992 //
6993 // chain, flag = CALLSEQ_START(chain, 0)
6994 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
6995 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
6996 //
6997 Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL);
6998 InFlag = Chain.getValue(1);
Andrew Trick74f4c742013-10-31 17:18:24 +00006999
Juergen Ributzkaaa30da32014-02-12 22:17:10 +00007000 // Add the <id> and <numBytes> constants.
7001 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
7002 Ops.push_back(DAG.getTargetConstant(
7003 cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i64));
7004 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
7005 Ops.push_back(DAG.getTargetConstant(
7006 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00007007
Andrew Trick74f4c742013-10-31 17:18:24 +00007008 // Push live variables for the stack map.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007009 addStackMapLiveVars(&CI, 2, Ops, *this);
Andrew Trick74f4c742013-10-31 17:18:24 +00007010
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00007011 // We are not pushing any register mask info here on the operands list,
7012 // because the stackmap doesn't clobber anything.
Andrew Trick74f4c742013-10-31 17:18:24 +00007013
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00007014 // Push the chain and the glue flag.
7015 Ops.push_back(Chain);
7016 Ops.push_back(InFlag);
Andrew Trick74f4c742013-10-31 17:18:24 +00007017
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00007018 // Create the STACKMAP node.
Andrew Trick74f4c742013-10-31 17:18:24 +00007019 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00007020 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
7021 Chain = SDValue(SM, 0);
7022 InFlag = Chain.getValue(1);
Andrew Trick6664df12013-11-05 22:44:04 +00007023
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00007024 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
Andrew Trick6664df12013-11-05 22:44:04 +00007025
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00007026 // Stackmaps don't generate values, so nothing goes into the NodeMap.
Andrew Trick6664df12013-11-05 22:44:04 +00007027
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00007028 // Set the root to the target-lowered call chain.
7029 DAG.setRoot(Chain);
Juergen Ributzkae8294752013-12-14 06:53:06 +00007030
7031 // Inform the Frame Information that we have a stackmap in this function.
7032 FuncInfo.MF->getFrameInfo()->setHasStackMap();
Andrew Trick74f4c742013-10-31 17:18:24 +00007033}
7034
7035/// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007036void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
7037 MachineBasicBlock *LandingPad) {
Andrew Tricke8cba372013-12-13 18:37:10 +00007038 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
Andrew Trick561f2212013-11-14 06:54:10 +00007039 // i32 <numBytes>,
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007040 // i8* <target>,
7041 // i32 <numArgs>,
7042 // [Args...],
7043 // [live variables...])
Andrew Trick74f4c742013-10-31 17:18:24 +00007044
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007045 CallingConv::ID CC = CS.getCallingConv();
7046 bool IsAnyRegCC = CC == CallingConv::AnyReg;
7047 bool HasDef = !CS->getType()->isVoidTy();
7048 SDValue Callee = getValue(CS->getOperand(2)); // <target>
Andrew Trick74f4c742013-10-31 17:18:24 +00007049
7050 // Get the real number of arguments participating in the call <numArgs>
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007051 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
Andrew Tricka2428e02013-11-22 19:07:33 +00007052 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
Andrew Trick74f4c742013-10-31 17:18:24 +00007053
7054 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
Andrew Tricka2428e02013-11-22 19:07:33 +00007055 // Intrinsics include all meta-operands up to but not including CC.
7056 unsigned NumMetaOpers = PatchPointOpers::CCPos;
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007057 assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
Andrew Trick74f4c742013-10-31 17:18:24 +00007058 "Not enough arguments provided to the patchpoint intrinsic");
7059
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007060 // For AnyRegCC the arguments are lowered later on manually.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007061 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
Andrew Trick74f4c742013-10-31 17:18:24 +00007062 std::pair<SDValue, SDValue> Result =
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007063 lowerCallOperands(CS, NumMetaOpers, NumCallArgs, Callee, IsAnyRegCC,
Hal Finkel0ad96c82015-01-13 17:48:04 +00007064 LandingPad, true);
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007065
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007066 SDNode *CallEnd = Result.second.getNode();
7067 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007068 CallEnd = CallEnd->getOperand(0).getNode();
7069
Andrew Trick74f4c742013-10-31 17:18:24 +00007070 /// Get a call instruction from the call sequence chain.
7071 /// Tail calls are not allowed.
7072 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
7073 "Expected a callseq node.");
7074 SDNode *Call = CallEnd->getOperand(0).getNode();
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007075 bool HasGlue = Call->getGluedNode();
Andrew Trick74f4c742013-10-31 17:18:24 +00007076
7077 // Replace the target specific call node with the patchable intrinsic.
7078 SmallVector<SDValue, 8> Ops;
7079
Andrew Tricka2428e02013-11-22 19:07:33 +00007080 // Add the <id> and <numBytes> constants.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007081 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
Andrew Tricka2428e02013-11-22 19:07:33 +00007082 Ops.push_back(DAG.getTargetConstant(
Andrew Tricke8cba372013-12-13 18:37:10 +00007083 cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i64));
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007084 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
Andrew Tricka2428e02013-11-22 19:07:33 +00007085 Ops.push_back(DAG.getTargetConstant(
7086 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
7087
Andrew Trick74f4c742013-10-31 17:18:24 +00007088 // Assume that the Callee is a constant address.
Andrew Tricka2428e02013-11-22 19:07:33 +00007089 // FIXME: handle function symbols in the future.
Andrew Trick74f4c742013-10-31 17:18:24 +00007090 Ops.push_back(
Juergen Ributzka87ed9062013-11-09 01:51:33 +00007091 DAG.getIntPtrConstant(cast<ConstantSDNode>(Callee)->getZExtValue(),
7092 /*isTarget=*/true));
Andrew Trick74f4c742013-10-31 17:18:24 +00007093
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007094 // Adjust <numArgs> to account for any arguments that have been passed on the
7095 // stack instead.
Andrew Trick74f4c742013-10-31 17:18:24 +00007096 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007097 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
7098 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007099 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, MVT::i32));
7100
7101 // Add the calling convention
Juergen Ributzka87ed9062013-11-09 01:51:33 +00007102 Ops.push_back(DAG.getTargetConstant((unsigned)CC, MVT::i32));
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007103
7104 // Add the arguments we omitted previously. The register allocator should
7105 // place these in any free register.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007106 if (IsAnyRegCC)
Andrew Tricka2428e02013-11-22 19:07:33 +00007107 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007108 Ops.push_back(getValue(CS.getArgument(i)));
Andrew Trick74f4c742013-10-31 17:18:24 +00007109
Andrew Tricka2428e02013-11-22 19:07:33 +00007110 // Push the arguments from the call instruction up to the register mask.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007111 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00007112 Ops.append(Call->op_begin() + 2, e);
Andrew Trick74f4c742013-10-31 17:18:24 +00007113
7114 // Push live variables for the stack map.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007115 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, Ops, *this);
Andrew Trick74f4c742013-10-31 17:18:24 +00007116
7117 // Push the register mask info.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007118 if (HasGlue)
Andrew Trick74f4c742013-10-31 17:18:24 +00007119 Ops.push_back(*(Call->op_end()-2));
7120 else
7121 Ops.push_back(*(Call->op_end()-1));
7122
7123 // Push the chain (this is originally the first operand of the call, but
7124 // becomes now the last or second to last operand).
7125 Ops.push_back(*(Call->op_begin()));
7126
7127 // Push the glue flag (last operand).
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007128 if (HasGlue)
Andrew Trick74f4c742013-10-31 17:18:24 +00007129 Ops.push_back(*(Call->op_end()-1));
7130
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007131 SDVTList NodeTys;
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007132 if (IsAnyRegCC && HasDef) {
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007133 // Create the return types based on the intrinsic definition
7134 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7135 SmallVector<EVT, 3> ValueVTs;
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007136 ComputeValueVTs(TLI, CS->getType(), ValueVTs);
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007137 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
Andrew Trick6664df12013-11-05 22:44:04 +00007138
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007139 // There is always a chain and a glue type at the end
7140 ValueVTs.push_back(MVT::Other);
7141 ValueVTs.push_back(MVT::Glue);
Craig Topperabb4ac72014-04-16 06:10:51 +00007142 NodeTys = DAG.getVTList(ValueVTs);
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007143 } else
7144 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7145
7146 // Replace the target specific call node with a PATCHPOINT node.
Andrew Trick6664df12013-11-05 22:44:04 +00007147 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
7148 getCurSDLoc(), NodeTys, Ops);
7149
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007150 // Update the NodeMap.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007151 if (HasDef) {
7152 if (IsAnyRegCC)
7153 setValue(CS.getInstruction(), SDValue(MN, 0));
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007154 else
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007155 setValue(CS.getInstruction(), Result.first);
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007156 }
Andrew Trick6664df12013-11-05 22:44:04 +00007157
7158 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007159 // call sequence. Furthermore the location of the chain and glue can change
7160 // when the AnyReg calling convention is used and the intrinsic returns a
7161 // value.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007162 if (IsAnyRegCC && HasDef) {
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007163 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
7164 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
7165 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7166 } else
7167 DAG.ReplaceAllUsesWith(Call, MN);
Andrew Trick6664df12013-11-05 22:44:04 +00007168 DAG.DeleteNode(Call);
Juergen Ributzkae8294752013-12-14 06:53:06 +00007169
7170 // Inform the Frame Information that we have a patchpoint in this function.
7171 FuncInfo.MF->getFrameInfo()->setHasPatchPoint();
Andrew Trick74f4c742013-10-31 17:18:24 +00007172}
7173
Tim Northoverd82ed2e2014-06-18 11:52:44 +00007174/// Returns an AttributeSet representing the attributes applied to the return
7175/// value of the given call.
7176static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
7177 SmallVector<Attribute::AttrKind, 2> Attrs;
7178 if (CLI.RetSExt)
7179 Attrs.push_back(Attribute::SExt);
7180 if (CLI.RetZExt)
7181 Attrs.push_back(Attribute::ZExt);
7182 if (CLI.IsInReg)
7183 Attrs.push_back(Attribute::InReg);
7184
7185 return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex,
7186 Attrs);
7187}
7188
Dan Gohman575fad32008-09-03 16:12:24 +00007189/// TargetLowering::LowerCallTo - This is the default LowerCallTo
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007190/// implementation, which just calls LowerCall.
7191/// FIXME: When all targets are
7192/// migrated to using LowerCall, this hook should be integrated into SDISel.
Dan Gohman575fad32008-09-03 16:12:24 +00007193std::pair<SDValue, SDValue>
Justin Holewinskiaa583972012-05-25 16:35:28 +00007194TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
Stephen Lin699808c2013-04-30 22:49:28 +00007195 // Handle the incoming return values from the call.
7196 CLI.Ins.clear();
Tim Northoverd82ed2e2014-06-18 11:52:44 +00007197 Type *OrigRetTy = CLI.RetTy;
Stephen Lin699808c2013-04-30 22:49:28 +00007198 SmallVector<EVT, 4> RetTys;
Tim Northoverd82ed2e2014-06-18 11:52:44 +00007199 SmallVector<uint64_t, 4> Offsets;
7200 ComputeValueVTs(*this, CLI.RetTy, RetTys, &Offsets);
7201
7202 SmallVector<ISD::OutputArg, 4> Outs;
7203 GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this);
7204
7205 bool CanLowerReturn =
7206 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
7207 CLI.IsVarArg, Outs, CLI.RetTy->getContext());
7208
7209 SDValue DemoteStackSlot;
7210 int DemoteStackIdx = -100;
7211 if (!CanLowerReturn) {
7212 // FIXME: equivalent assert?
7213 // assert(!CS.hasInAllocaArgument() &&
7214 // "sret demotion is incompatible with inalloca");
7215 uint64_t TySize = getDataLayout()->getTypeAllocSize(CLI.RetTy);
7216 unsigned Align = getDataLayout()->getPrefTypeAlignment(CLI.RetTy);
7217 MachineFunction &MF = CLI.DAG.getMachineFunction();
7218 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
7219 Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
7220
7221 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy());
7222 ArgListEntry Entry;
7223 Entry.Node = DemoteStackSlot;
7224 Entry.Ty = StackSlotPtrType;
7225 Entry.isSExt = false;
7226 Entry.isZExt = false;
7227 Entry.isInReg = false;
7228 Entry.isSRet = true;
7229 Entry.isNest = false;
7230 Entry.isByVal = false;
7231 Entry.isReturned = false;
7232 Entry.Alignment = Align;
7233 CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
7234 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
7235 } else {
7236 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7237 EVT VT = RetTys[I];
7238 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7239 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7240 for (unsigned i = 0; i != NumRegs; ++i) {
7241 ISD::InputArg MyFlags;
7242 MyFlags.VT = RegisterVT;
7243 MyFlags.ArgVT = VT;
7244 MyFlags.Used = CLI.IsReturnValueUsed;
7245 if (CLI.RetSExt)
7246 MyFlags.Flags.setSExt();
7247 if (CLI.RetZExt)
7248 MyFlags.Flags.setZExt();
7249 if (CLI.IsInReg)
7250 MyFlags.Flags.setInReg();
7251 CLI.Ins.push_back(MyFlags);
7252 }
Stephen Lin699808c2013-04-30 22:49:28 +00007253 }
7254 }
7255
Dan Gohman575fad32008-09-03 16:12:24 +00007256 // Handle all of the outgoing arguments.
Justin Holewinskiaa583972012-05-25 16:35:28 +00007257 CLI.Outs.clear();
7258 CLI.OutVals.clear();
Saleem Abdulrasool9f664c12014-05-17 21:50:01 +00007259 ArgListTy &Args = CLI.getArgs();
Dan Gohman575fad32008-09-03 16:12:24 +00007260 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007261 SmallVector<EVT, 4> ValueVTs;
Dan Gohman575fad32008-09-03 16:12:24 +00007262 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
Oliver Stannardc24f2172014-05-09 14:01:47 +00007263 Type *FinalType = Args[i].Ty;
7264 if (Args[i].isByVal)
7265 FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
7266 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
7267 FinalType, CLI.CallConv, CLI.IsVarArg);
7268 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
7269 ++Value) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007270 EVT VT = ValueVTs[Value];
Justin Holewinskiaa583972012-05-25 16:35:28 +00007271 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
Chris Lattner160e8ab2008-10-18 18:49:30 +00007272 SDValue Op = SDValue(Args[i].Node.getNode(),
7273 Args[i].Node.getResNo() + Value);
Dan Gohman575fad32008-09-03 16:12:24 +00007274 ISD::ArgFlagsTy Flags;
Matt Arsenault443252c2014-04-21 18:39:13 +00007275 unsigned OriginalAlignment = getDataLayout()->getABITypeAlignment(ArgTy);
Dan Gohman575fad32008-09-03 16:12:24 +00007276
7277 if (Args[i].isZExt)
7278 Flags.setZExt();
7279 if (Args[i].isSExt)
7280 Flags.setSExt();
7281 if (Args[i].isInReg)
7282 Flags.setInReg();
7283 if (Args[i].isSRet)
7284 Flags.setSRet();
Reid Klecknerf5b76512014-01-31 23:50:57 +00007285 if (Args[i].isByVal)
Dan Gohman575fad32008-09-03 16:12:24 +00007286 Flags.setByVal();
Reid Klecknerf5b76512014-01-31 23:50:57 +00007287 if (Args[i].isInAlloca) {
7288 Flags.setInAlloca();
7289 // Set the byval flag for CCAssignFn callbacks that don't know about
7290 // inalloca. This way we can know how many bytes we should've allocated
7291 // and how many bytes a callee cleanup function will pop. If we port
7292 // inalloca to more targets, we'll have to add custom inalloca handling
7293 // in the various CC lowering callbacks.
7294 Flags.setByVal();
7295 }
7296 if (Args[i].isByVal || Args[i].isInAlloca) {
Chris Lattner229907c2011-07-18 04:54:35 +00007297 PointerType *Ty = cast<PointerType>(Args[i].Ty);
7298 Type *ElementTy = Ty->getElementType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00007299 Flags.setByValSize(getDataLayout()->getTypeAllocSize(ElementTy));
Dan Gohman575fad32008-09-03 16:12:24 +00007300 // For ByVal, alignment should come from FE. BE will guess if this
7301 // info is not there but there are cases it cannot get right.
Chris Lattner68254fc2011-05-22 23:23:02 +00007302 unsigned FrameAlign;
Dan Gohman575fad32008-09-03 16:12:24 +00007303 if (Args[i].Alignment)
7304 FrameAlign = Args[i].Alignment;
Chris Lattner68254fc2011-05-22 23:23:02 +00007305 else
7306 FrameAlign = getByValTypeAlignment(ElementTy);
Dan Gohman575fad32008-09-03 16:12:24 +00007307 Flags.setByValAlign(FrameAlign);
Dan Gohman575fad32008-09-03 16:12:24 +00007308 }
7309 if (Args[i].isNest)
7310 Flags.setNest();
Tim Northovere95c5b32015-02-24 17:22:34 +00007311 if (NeedsRegBlock)
Oliver Stannardc24f2172014-05-09 14:01:47 +00007312 Flags.setInConsecutiveRegs();
Dan Gohman575fad32008-09-03 16:12:24 +00007313 Flags.setOrigAlign(OriginalAlignment);
7314
Patrik Hagglundbad545c2012-12-19 11:48:16 +00007315 MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
Justin Holewinskiaa583972012-05-25 16:35:28 +00007316 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
Dan Gohman575fad32008-09-03 16:12:24 +00007317 SmallVector<SDValue, 4> Parts(NumParts);
7318 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
7319
7320 if (Args[i].isSExt)
7321 ExtendKind = ISD::SIGN_EXTEND;
7322 else if (Args[i].isZExt)
7323 ExtendKind = ISD::ZERO_EXTEND;
7324
Stephen Lin699808c2013-04-30 22:49:28 +00007325 // Conservatively only handle 'returned' on non-vectors for now
7326 if (Args[i].isReturned && !Op.getValueType().isVector()) {
7327 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
7328 "unexpected use of 'returned'");
7329 // Before passing 'returned' to the target lowering code, ensure that
7330 // either the register MVT and the actual EVT are the same size or that
7331 // the return value and argument are extended in the same way; in these
7332 // cases it's safe to pass the argument register value unchanged as the
7333 // return register value (although it's at the target's option whether
7334 // to do so)
7335 // TODO: allow code generation to take advantage of partially preserved
7336 // registers rather than clobbering the entire register when the
7337 // parameter extension method is not compatible with the return
7338 // extension method
7339 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
7340 (ExtendKind != ISD::ANY_EXTEND &&
7341 CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
7342 Flags.setReturned();
7343 }
7344
Craig Topperc0196b12014-04-14 00:51:57 +00007345 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
7346 CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind);
Dan Gohman575fad32008-09-03 16:12:24 +00007347
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007348 for (unsigned j = 0; j != NumParts; ++j) {
Dan Gohman575fad32008-09-03 16:12:24 +00007349 // if it isn't first piece, alignment must be 1
Tom Stellard8d7d4de2013-10-23 00:44:24 +00007350 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
Manman Ren3d5af272012-11-01 23:49:58 +00007351 i < CLI.NumFixedArgs,
7352 i, j*Parts[j].getValueType().getStoreSize());
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007353 if (NumParts > 1 && j == 0)
7354 MyFlags.Flags.setSplit();
7355 else if (j != 0)
7356 MyFlags.Flags.setOrigAlign(1);
Dan Gohman575fad32008-09-03 16:12:24 +00007357
Justin Holewinskiaa583972012-05-25 16:35:28 +00007358 CLI.Outs.push_back(MyFlags);
7359 CLI.OutVals.push_back(Parts[j]);
Dan Gohman575fad32008-09-03 16:12:24 +00007360 }
Tim Northovere95c5b32015-02-24 17:22:34 +00007361
7362 if (NeedsRegBlock && Value == NumValues - 1)
7363 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
Dan Gohman575fad32008-09-03 16:12:24 +00007364 }
7365 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00007366
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007367 SmallVector<SDValue, 4> InVals;
Justin Holewinskiaa583972012-05-25 16:35:28 +00007368 CLI.Chain = LowerCall(CLI, InVals);
Dan Gohman695d8112009-08-06 15:37:27 +00007369
7370 // Verify that the target's LowerCall behaved as expected.
Justin Holewinskiaa583972012-05-25 16:35:28 +00007371 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
Dan Gohman695d8112009-08-06 15:37:27 +00007372 "LowerCall didn't return a valid chain!");
Justin Holewinskiaa583972012-05-25 16:35:28 +00007373 assert((!CLI.IsTailCall || InVals.empty()) &&
Dan Gohman695d8112009-08-06 15:37:27 +00007374 "LowerCall emitted a return value for a tail call!");
Justin Holewinskiaa583972012-05-25 16:35:28 +00007375 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
Dan Gohman695d8112009-08-06 15:37:27 +00007376 "LowerCall didn't emit the correct number of values!");
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007377
7378 // For a tail call, the return value is merely live-out and there aren't
7379 // any nodes in the DAG representing it. Return a special value to
7380 // indicate that a tail call has been emitted and no more Instructions
7381 // should be processed in the current block.
Justin Holewinskiaa583972012-05-25 16:35:28 +00007382 if (CLI.IsTailCall) {
7383 CLI.DAG.setRoot(CLI.Chain);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007384 return std::make_pair(SDValue(), SDValue());
7385 }
7386
Justin Holewinskiaa583972012-05-25 16:35:28 +00007387 DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
Evan Cheng180704d2010-03-11 19:38:18 +00007388 assert(InVals[i].getNode() &&
7389 "LowerCall emitted a null value!");
Justin Holewinskiaa583972012-05-25 16:35:28 +00007390 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
Evan Cheng180704d2010-03-11 19:38:18 +00007391 "LowerCall emitted a value with the wrong type!");
7392 });
7393
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007394 SmallVector<SDValue, 4> ReturnValues;
Tim Northoverd82ed2e2014-06-18 11:52:44 +00007395 if (!CanLowerReturn) {
7396 // The instruction result is the result of loading from the
7397 // hidden sret parameter.
7398 SmallVector<EVT, 1> PVTs;
7399 Type *PtrRetTy = PointerType::getUnqual(OrigRetTy);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007400
Tim Northoverd82ed2e2014-06-18 11:52:44 +00007401 ComputeValueVTs(*this, PtrRetTy, PVTs);
7402 assert(PVTs.size() == 1 && "Pointers should fit in one register");
7403 EVT PtrVT = PVTs[0];
7404
7405 unsigned NumValues = RetTys.size();
7406 ReturnValues.resize(NumValues);
7407 SmallVector<SDValue, 4> Chains(NumValues);
7408
7409 for (unsigned i = 0; i < NumValues; ++i) {
7410 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
7411 CLI.DAG.getConstant(Offsets[i], PtrVT));
7412 SDValue L = CLI.DAG.getLoad(
7413 RetTys[i], CLI.DL, CLI.Chain, Add,
7414 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]), false,
7415 false, false, 1);
7416 ReturnValues[i] = L;
7417 Chains[i] = L.getValue(1);
7418 }
7419
7420 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
7421 } else {
7422 // Collect the legal value parts into potentially illegal values
7423 // that correspond to the original function's return values.
7424 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7425 if (CLI.RetSExt)
7426 AssertOp = ISD::AssertSext;
7427 else if (CLI.RetZExt)
7428 AssertOp = ISD::AssertZext;
7429 unsigned CurReg = 0;
7430 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7431 EVT VT = RetTys[I];
7432 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7433 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7434
7435 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
7436 NumRegs, RegisterVT, VT, nullptr,
7437 AssertOp));
7438 CurReg += NumRegs;
7439 }
7440
7441 // For a function returning void, there is no return value. We can't create
7442 // such a node, so we just return a null return value in that case. In
7443 // that case, nothing will actually look at the value.
7444 if (ReturnValues.empty())
7445 return std::make_pair(SDValue(), CLI.Chain);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007446 }
7447
Justin Holewinskiaa583972012-05-25 16:35:28 +00007448 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
Craig Topper48d114b2014-04-26 18:35:24 +00007449 CLI.DAG.getVTList(RetTys), ReturnValues);
Justin Holewinskiaa583972012-05-25 16:35:28 +00007450 return std::make_pair(Res, CLI.Chain);
Dan Gohman575fad32008-09-03 16:12:24 +00007451}
7452
Duncan Sandsbe7e4142009-01-21 09:00:29 +00007453void TargetLowering::LowerOperationWrapper(SDNode *N,
7454 SmallVectorImpl<SDValue> &Results,
Dan Gohman21cea8a2010-04-17 15:26:15 +00007455 SelectionDAG &DAG) const {
Duncan Sandsbe7e4142009-01-21 09:00:29 +00007456 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptaa70798c2009-01-21 04:48:39 +00007457 if (Res.getNode())
7458 Results.push_back(Res);
7459}
7460
Dan Gohman21cea8a2010-04-17 15:26:15 +00007461SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
Torok Edwinfbcc6632009-07-14 16:55:14 +00007462 llvm_unreachable("LowerOperation not implemented for this target!");
Dan Gohman575fad32008-09-03 16:12:24 +00007463}
7464
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007465void
7466SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
Dan Gohmand4322232010-07-01 01:59:43 +00007467 SDValue Op = getNonRegisterValue(V);
Dan Gohman575fad32008-09-03 16:12:24 +00007468 assert((Op.getOpcode() != ISD::CopyFromReg ||
7469 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
7470 "Copy from a reg to the same reg!");
7471 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
7472
Eric Christopher58a24612014-10-08 09:50:54 +00007473 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7474 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
Dan Gohman575fad32008-09-03 16:12:24 +00007475 SDValue Chain = DAG.getEntryNode();
Jiangning Liuffbc6902014-09-19 05:30:35 +00007476
7477 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
7478 FuncInfo.PreferredExtendType.end())
7479 ? ISD::ANY_EXTEND
7480 : FuncInfo.PreferredExtendType[V];
7481 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
Dan Gohman575fad32008-09-03 16:12:24 +00007482 PendingExports.push_back(Chain);
7483}
7484
7485#include "llvm/CodeGen/SelectionDAGISel.h"
7486
Eli Friedman441a01a2011-05-05 16:53:34 +00007487/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
7488/// entry block, return true. This includes arguments used by switches, since
7489/// the switch may expand into multiple basic blocks.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007490static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
Eli Friedman441a01a2011-05-05 16:53:34 +00007491 // With FastISel active, we may be splitting blocks, so force creation
7492 // of virtual registers for all non-dead arguments.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007493 if (FastISel)
Eli Friedman441a01a2011-05-05 16:53:34 +00007494 return A->use_empty();
7495
7496 const BasicBlock *Entry = A->getParent()->begin();
Chandler Carruthcdf47882014-03-09 03:16:01 +00007497 for (const User *U : A->users())
Eli Friedman441a01a2011-05-05 16:53:34 +00007498 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
7499 return false; // Use not in entry block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00007500
Eli Friedman441a01a2011-05-05 16:53:34 +00007501 return true;
7502}
7503
Eli Bendersky33ebf832013-02-28 23:09:18 +00007504void SelectionDAGISel::LowerArguments(const Function &F) {
Dan Gohman1a6c47f2009-11-23 18:04:58 +00007505 SelectionDAG &DAG = SDB->DAG;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007506 SDLoc dl = SDB->getCurSDLoc();
Rafael Espindola5f57f462014-02-21 18:34:28 +00007507 const DataLayout *DL = TLI->getDataLayout();
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007508 SmallVector<ISD::InputArg, 16> Ins;
Dan Gohman575fad32008-09-03 16:12:24 +00007509
Dan Gohmand16aa542010-05-29 17:03:36 +00007510 if (!FuncInfo->CanLowerReturn) {
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007511 // Put in an sret pointer parameter before all the other parameters.
7512 SmallVector<EVT, 1> ValueVTs;
Eric Christopherb17140d2014-10-08 07:32:17 +00007513 ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007514
7515 // NOTE: Assuming that a pointer will never break down to more than one VT
7516 // or one register.
7517 ISD::ArgFlagsTy Flags;
7518 Flags.setSRet();
Bill Wendlingf7719082013-06-06 00:43:09 +00007519 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
Andrew Trick05938a52015-02-16 18:10:47 +00007520 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
7521 ISD::InputArg::NoArgIndex, 0);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007522 Ins.push_back(RetArg);
7523 }
Kenneth Uildriks07119732009-11-07 02:11:54 +00007524
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007525 // Set up the incoming argument description vector.
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007526 unsigned Idx = 1;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007527 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007528 I != E; ++I, ++Idx) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007529 SmallVector<EVT, 4> ValueVTs;
Bill Wendlingf7719082013-06-06 00:43:09 +00007530 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007531 bool isArgValueUsed = !I->use_empty();
Tom Stellard8d7d4de2013-10-23 00:44:24 +00007532 unsigned PartBase = 0;
Oliver Stannardc24f2172014-05-09 14:01:47 +00007533 Type *FinalType = I->getType();
7534 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7535 FinalType = cast<PointerType>(FinalType)->getElementType();
7536 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
7537 FinalType, F.getCallingConv(), F.isVarArg());
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007538 for (unsigned Value = 0, NumValues = ValueVTs.size();
7539 Value != NumValues; ++Value) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007540 EVT VT = ValueVTs[Value];
Chris Lattner229907c2011-07-18 04:54:35 +00007541 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007542 ISD::ArgFlagsTy Flags;
Matt Arsenault443252c2014-04-21 18:39:13 +00007543 unsigned OriginalAlignment = DL->getABITypeAlignment(ArgTy);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007544
Bill Wendling94dcaf82012-12-30 12:45:13 +00007545 if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007546 Flags.setZExt();
Bill Wendling94dcaf82012-12-30 12:45:13 +00007547 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007548 Flags.setSExt();
Bill Wendling94dcaf82012-12-30 12:45:13 +00007549 if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007550 Flags.setInReg();
Bill Wendling94dcaf82012-12-30 12:45:13 +00007551 if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007552 Flags.setSRet();
Reid Klecknerf5b76512014-01-31 23:50:57 +00007553 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007554 Flags.setByVal();
Reid Klecknerf5b76512014-01-31 23:50:57 +00007555 if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) {
7556 Flags.setInAlloca();
7557 // Set the byval flag for CCAssignFn callbacks that don't know about
7558 // inalloca. This way we can know how many bytes we should've allocated
7559 // and how many bytes a callee cleanup function will pop. If we port
7560 // inalloca to more targets, we'll have to add custom inalloca handling
7561 // in the various CC lowering callbacks.
7562 Flags.setByVal();
7563 }
7564 if (Flags.isByVal() || Flags.isInAlloca()) {
Chris Lattner229907c2011-07-18 04:54:35 +00007565 PointerType *Ty = cast<PointerType>(I->getType());
7566 Type *ElementTy = Ty->getElementType();
Rafael Espindola5f57f462014-02-21 18:34:28 +00007567 Flags.setByValSize(DL->getTypeAllocSize(ElementTy));
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007568 // For ByVal, alignment should be passed from FE. BE will guess if
7569 // this info is not there but there are cases it cannot get right.
Chris Lattner68254fc2011-05-22 23:23:02 +00007570 unsigned FrameAlign;
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007571 if (F.getParamAlignment(Idx))
7572 FrameAlign = F.getParamAlignment(Idx);
Chris Lattner68254fc2011-05-22 23:23:02 +00007573 else
Bill Wendlingf7719082013-06-06 00:43:09 +00007574 FrameAlign = TLI->getByValTypeAlignment(ElementTy);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007575 Flags.setByValAlign(FrameAlign);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007576 }
Bill Wendling94dcaf82012-12-30 12:45:13 +00007577 if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007578 Flags.setNest();
Tim Northovere95c5b32015-02-24 17:22:34 +00007579 if (NeedsRegBlock)
Oliver Stannardc24f2172014-05-09 14:01:47 +00007580 Flags.setInConsecutiveRegs();
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007581 Flags.setOrigAlign(OriginalAlignment);
7582
Bill Wendlingf7719082013-06-06 00:43:09 +00007583 MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7584 unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007585 for (unsigned i = 0; i != NumRegs; ++i) {
Tom Stellard8d7d4de2013-10-23 00:44:24 +00007586 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
7587 Idx-1, PartBase+i*RegisterVT.getStoreSize());
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007588 if (NumRegs > 1 && i == 0)
7589 MyFlags.Flags.setSplit();
7590 // if it isn't first piece, alignment must be 1
7591 else if (i > 0)
7592 MyFlags.Flags.setOrigAlign(1);
7593 Ins.push_back(MyFlags);
7594 }
Tim Northovere95c5b32015-02-24 17:22:34 +00007595 if (NeedsRegBlock && Value == NumValues - 1)
7596 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
Tom Stellard8d7d4de2013-10-23 00:44:24 +00007597 PartBase += VT.getStoreSize();
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007598 }
7599 }
7600
7601 // Call the target to set up the argument values.
7602 SmallVector<SDValue, 8> InVals;
Eric Christopherb17140d2014-10-08 07:32:17 +00007603 SDValue NewRoot = TLI->LowerFormalArguments(
7604 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
Dan Gohman695d8112009-08-06 15:37:27 +00007605
7606 // Verify that the target's LowerFormalArguments behaved as expected.
Owen Anderson9f944592009-08-11 20:47:22 +00007607 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
Dan Gohman695d8112009-08-06 15:37:27 +00007608 "LowerFormalArguments didn't return a valid chain!");
7609 assert(InVals.size() == Ins.size() &&
7610 "LowerFormalArguments didn't emit the correct number of values!");
Bill Wendlingd8549812009-12-22 21:35:02 +00007611 DEBUG({
7612 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
7613 assert(InVals[i].getNode() &&
7614 "LowerFormalArguments emitted a null value!");
Duncan Sandsf5dda012010-11-03 11:35:31 +00007615 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
Bill Wendlingd8549812009-12-22 21:35:02 +00007616 "LowerFormalArguments emitted a value with the wrong type!");
7617 }
7618 });
Bill Wendling919b7aa2009-12-22 02:10:19 +00007619
Dan Gohman695d8112009-08-06 15:37:27 +00007620 // Update the DAG with the new chain value resulting from argument lowering.
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007621 DAG.setRoot(NewRoot);
7622
7623 // Set up the argument values.
7624 unsigned i = 0;
7625 Idx = 1;
Dan Gohmand16aa542010-05-29 17:03:36 +00007626 if (!FuncInfo->CanLowerReturn) {
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007627 // Create a virtual register for the sret pointer, and put in a copy
7628 // from the sret argument into it.
7629 SmallVector<EVT, 1> ValueVTs;
Bill Wendlingf7719082013-06-06 00:43:09 +00007630 ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
Patrik Hagglund5e6c3612012-12-13 06:34:11 +00007631 MVT VT = ValueVTs[0].getSimpleVT();
Bill Wendlingf7719082013-06-06 00:43:09 +00007632 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007633 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Bill Wendling78c5b7a2010-03-02 01:55:18 +00007634 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
Craig Topperc0196b12014-04-14 00:51:57 +00007635 RegVT, VT, nullptr, AssertOp);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007636
Dan Gohman1a6c47f2009-11-23 18:04:58 +00007637 MachineFunction& MF = SDB->DAG.getMachineFunction();
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007638 MachineRegisterInfo& RegInfo = MF.getRegInfo();
Bill Wendlingf7719082013-06-06 00:43:09 +00007639 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
Dan Gohmand16aa542010-05-29 17:03:36 +00007640 FuncInfo->DemoteRegister = SRetReg;
Eric Christopher58a24612014-10-08 09:50:54 +00007641 NewRoot =
7642 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007643 DAG.setRoot(NewRoot);
Bill Wendling919b7aa2009-12-22 02:10:19 +00007644
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007645 // i indexes lowered arguments. Bump it past the hidden sret argument.
7646 // Idx indexes LLVM arguments. Don't touch it.
7647 ++i;
7648 }
Bill Wendling919b7aa2009-12-22 02:10:19 +00007649
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007650 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007651 ++I, ++Idx) {
7652 SmallVector<SDValue, 4> ArgValues;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007653 SmallVector<EVT, 4> ValueVTs;
Bill Wendlingf7719082013-06-06 00:43:09 +00007654 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00007655 unsigned NumValues = ValueVTs.size();
Devang Patelb0c76392010-06-01 19:59:01 +00007656
7657 // If this argument is unused then remember its value. It is used to generate
7658 // debugging information.
Adrian Prantl9c930592013-05-16 23:44:12 +00007659 if (I->use_empty() && NumValues) {
Devang Patelb0c76392010-06-01 19:59:01 +00007660 SDB->setUnusedArgValue(I, InVals[i]);
7661
Adrian Prantl9c930592013-05-16 23:44:12 +00007662 // Also remember any frame index for use in FastISel.
7663 if (FrameIndexSDNode *FI =
7664 dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
7665 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7666 }
7667
Eli Friedman441a01a2011-05-05 16:53:34 +00007668 for (unsigned Val = 0; Val != NumValues; ++Val) {
7669 EVT VT = ValueVTs[Val];
Bill Wendlingf7719082013-06-06 00:43:09 +00007670 MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7671 unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007672
7673 if (!I->use_empty()) {
7674 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Bill Wendling94dcaf82012-12-30 12:45:13 +00007675 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007676 AssertOp = ISD::AssertSext;
Bill Wendling94dcaf82012-12-30 12:45:13 +00007677 else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007678 AssertOp = ISD::AssertZext;
7679
Bill Wendling78c5b7a2010-03-02 01:55:18 +00007680 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
Bill Wendling919b7aa2009-12-22 02:10:19 +00007681 NumParts, PartVT, VT,
Craig Topperc0196b12014-04-14 00:51:57 +00007682 nullptr, AssertOp));
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007683 }
Bill Wendling919b7aa2009-12-22 02:10:19 +00007684
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007685 i += NumParts;
7686 }
Bill Wendling919b7aa2009-12-22 02:10:19 +00007687
Eli Friedman441a01a2011-05-05 16:53:34 +00007688 // We don't need to do anything else for unused arguments.
7689 if (ArgValues.empty())
7690 continue;
7691
Devang Patel9d904e12011-09-08 22:59:09 +00007692 // Note down frame index.
7693 if (FrameIndexSDNode *FI =
Bill Wendlingd1634052012-07-19 00:04:14 +00007694 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
Devang Patel9d904e12011-09-08 22:59:09 +00007695 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
Devang Patel86ec8b32010-08-31 22:22:42 +00007696
Craig Topper2d2aa0c2014-04-30 07:17:30 +00007697 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007698 SDB->getCurSDLoc());
Devang Patel9d904e12011-09-08 22:59:09 +00007699
Eli Friedman441a01a2011-05-05 16:53:34 +00007700 SDB->setValue(I, Res);
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007701 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
Stephen Lincfe7f352013-07-08 00:37:03 +00007702 if (LoadSDNode *LNode =
Devang Patel9d904e12011-09-08 22:59:09 +00007703 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
7704 if (FrameIndexSDNode *FI =
7705 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
7706 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7707 }
Bill Wendling919b7aa2009-12-22 02:10:19 +00007708
Eli Friedman441a01a2011-05-05 16:53:34 +00007709 // If this argument is live outside of the entry block, insert a copy from
7710 // wherever we got it to the vreg that other BB's will reference it as.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007711 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
Eli Friedman441a01a2011-05-05 16:53:34 +00007712 // If we can, though, try to skip creating an unnecessary vreg.
7713 // FIXME: This isn't very clean... it would be nice to make this more
Eli Friedman768de0a2011-05-10 21:50:58 +00007714 // general. It's also subtly incompatible with the hacks FastISel
7715 // uses with vregs.
Eli Friedman441a01a2011-05-05 16:53:34 +00007716 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
7717 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
7718 FuncInfo->ValueMap[I] = Reg;
7719 continue;
7720 }
7721 }
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007722 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
Eli Friedman441a01a2011-05-05 16:53:34 +00007723 FuncInfo->InitializeRegForValue(I);
Dan Gohman1a6c47f2009-11-23 18:04:58 +00007724 SDB->CopyToExportRegsIfNeeded(I);
Dan Gohman575fad32008-09-03 16:12:24 +00007725 }
Dan Gohman575fad32008-09-03 16:12:24 +00007726 }
Bill Wendling919b7aa2009-12-22 02:10:19 +00007727
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007728 assert(i == InVals.size() && "Argument register count mismatch!");
Dan Gohman575fad32008-09-03 16:12:24 +00007729
7730 // Finally, if the target has anything special to do, allow it to do so.
Dan Gohmanc87b74d2010-04-14 20:17:22 +00007731 EmitFunctionEntryCode();
Dan Gohman575fad32008-09-03 16:12:24 +00007732}
7733
7734/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
7735/// ensure constants are generated when needed. Remember the virtual registers
7736/// that need to be added to the Machine PHI nodes as input. We cannot just
7737/// directly add them, because expansion might result in multiple MBB's for one
7738/// BB. As such, the start of the BB might correspond to a different MBB than
7739/// the end.
7740///
7741void
Dan Gohmanc594eab2010-04-22 20:46:50 +00007742SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007743 const TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohman575fad32008-09-03 16:12:24 +00007744
7745 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
7746
7747 // Check successor nodes' PHI nodes that expect a constant to be available
7748 // from this block.
7749 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007750 const BasicBlock *SuccBB = TI->getSuccessor(succ);
Dan Gohman575fad32008-09-03 16:12:24 +00007751 if (!isa<PHINode>(SuccBB->begin())) continue;
Dan Gohmanc594eab2010-04-22 20:46:50 +00007752 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00007753
Dan Gohman575fad32008-09-03 16:12:24 +00007754 // If this terminator has multiple identical successors (common for
7755 // switches), only handle each succ once.
David Blaikie70573dc2014-11-19 07:49:26 +00007756 if (!SuccsHandled.insert(SuccMBB).second)
7757 continue;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00007758
Dan Gohman575fad32008-09-03 16:12:24 +00007759 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Dan Gohman575fad32008-09-03 16:12:24 +00007760
7761 // At this point we know that there is a 1-1 correspondence between LLVM PHI
7762 // nodes and Machine PHI nodes, but the incoming operands have not been
7763 // emitted yet.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007764 for (BasicBlock::const_iterator I = SuccBB->begin();
7765 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Dan Gohman575fad32008-09-03 16:12:24 +00007766 // Ignore dead phi's.
7767 if (PN->use_empty()) continue;
7768
Rafael Espindolae53b7d12011-05-13 15:18:06 +00007769 // Skip empty types
7770 if (PN->getType()->isEmptyTy())
7771 continue;
7772
Dan Gohman575fad32008-09-03 16:12:24 +00007773 unsigned Reg;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007774 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Dan Gohman575fad32008-09-03 16:12:24 +00007775
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007776 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
Dan Gohmanc594eab2010-04-22 20:46:50 +00007777 unsigned &RegOut = ConstantsOut[C];
Dan Gohman575fad32008-09-03 16:12:24 +00007778 if (RegOut == 0) {
Dan Gohman93f59202010-07-02 00:10:16 +00007779 RegOut = FuncInfo.CreateRegs(C->getType());
Dan Gohmanc594eab2010-04-22 20:46:50 +00007780 CopyValueToVirtualRegister(C, RegOut);
Dan Gohman575fad32008-09-03 16:12:24 +00007781 }
7782 Reg = RegOut;
7783 } else {
Dan Gohman9576645a2010-07-01 01:33:21 +00007784 DenseMap<const Value *, unsigned>::iterator I =
7785 FuncInfo.ValueMap.find(PHIOp);
7786 if (I != FuncInfo.ValueMap.end())
7787 Reg = I->second;
7788 else {
Dan Gohman575fad32008-09-03 16:12:24 +00007789 assert(isa<AllocaInst>(PHIOp) &&
Dan Gohmanc594eab2010-04-22 20:46:50 +00007790 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
Dan Gohman575fad32008-09-03 16:12:24 +00007791 "Didn't codegen value into a register!??");
Dan Gohman93f59202010-07-02 00:10:16 +00007792 Reg = FuncInfo.CreateRegs(PHIOp->getType());
Dan Gohmanc594eab2010-04-22 20:46:50 +00007793 CopyValueToVirtualRegister(PHIOp, Reg);
Dan Gohman575fad32008-09-03 16:12:24 +00007794 }
7795 }
7796
7797 // Remember that this register needs to added to the machine PHI node as
7798 // the input for this MBB.
Owen Anderson53aa7a92009-08-10 22:56:29 +00007799 SmallVector<EVT, 4> ValueVTs;
Eric Christopher58a24612014-10-08 09:50:54 +00007800 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7801 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00007802 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007803 EVT VT = ValueVTs[vti];
Eric Christopher58a24612014-10-08 09:50:54 +00007804 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
Dan Gohman575fad32008-09-03 16:12:24 +00007805 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Dan Gohmanc594eab2010-04-22 20:46:50 +00007806 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Dan Gohman575fad32008-09-03 16:12:24 +00007807 Reg += NumRegisters;
7808 }
7809 }
7810 }
Bill Wendlinga3cd3502013-06-19 21:36:55 +00007811
Dan Gohmanc594eab2010-04-22 20:46:50 +00007812 ConstantsOut.clear();
Dan Gohman7bda51f2008-09-03 23:12:08 +00007813}
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00007814
7815/// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
7816/// is 0.
7817MachineBasicBlock *
7818SelectionDAGBuilder::StackProtectorDescriptor::
7819AddSuccessorMBB(const BasicBlock *BB,
7820 MachineBasicBlock *ParentMBB,
Akira Hatanakab9991a22014-12-01 04:27:03 +00007821 bool IsLikely,
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00007822 MachineBasicBlock *SuccMBB) {
7823 // If SuccBB has not been created yet, create it.
7824 if (!SuccMBB) {
7825 MachineFunction *MF = ParentMBB->getParent();
7826 MachineFunction::iterator BBI = ParentMBB;
7827 SuccMBB = MF->CreateMachineBasicBlock(BB);
7828 MF->insert(++BBI, SuccMBB);
7829 }
7830 // Add it as a successor of ParentMBB.
Akira Hatanakab9991a22014-12-01 04:27:03 +00007831 ParentMBB->addSuccessor(
7832 SuccMBB, BranchProbabilityInfo::getBranchWeightStackProtector(IsLikely));
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00007833 return SuccMBB;
7834}