blob: c3b197e97eb5836be7bbf9937e4c7e825b8b03a5 [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"
Nadav Rotem7c277da2012-09-06 09:17:37 +000023#include "llvm/Analysis/ValueTracking.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/CodeGen/Analysis.h"
25#include "llvm/CodeGen/FastISel.h"
26#include "llvm/CodeGen/FunctionLoweringInfo.h"
27#include "llvm/CodeGen/GCMetadata.h"
28#include "llvm/CodeGen/GCStrategy.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineInstrBuilder.h"
32#include "llvm/CodeGen/MachineJumpTableInfo.h"
33#include "llvm/CodeGen/MachineModuleInfo.h"
34#include "llvm/CodeGen/MachineRegisterInfo.h"
35#include "llvm/CodeGen/SelectionDAG.h"
Andrew Trick153ebe62013-10-31 22:11:56 +000036#include "llvm/CodeGen/StackMaps.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/CallingConv.h"
38#include "llvm/IR/Constants.h"
39#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000040#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/DerivedTypes.h"
42#include "llvm/IR/Function.h"
43#include "llvm/IR/GlobalVariable.h"
44#include "llvm/IR/InlineAsm.h"
45#include "llvm/IR/Instructions.h"
46#include "llvm/IR/IntrinsicInst.h"
47#include "llvm/IR/Intrinsics.h"
48#include "llvm/IR/LLVMContext.h"
49#include "llvm/IR/Module.h"
Philip Reames1a1bdb22014-12-02 18:50:36 +000050#include "llvm/IR/Statepoint.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000051#include "llvm/Support/CommandLine.h"
52#include "llvm/Support/Debug.h"
53#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000054#include "llvm/Support/MathExtras.h"
55#include "llvm/Support/raw_ostream.h"
Anton Korobeynikov2f931282011-01-10 12:39:04 +000056#include "llvm/Target/TargetFrameLowering.h"
Dan Gohman575fad32008-09-03 16:12:24 +000057#include "llvm/Target/TargetInstrInfo.h"
Dale Johannesenb842d522009-02-05 01:49:45 +000058#include "llvm/Target/TargetIntrinsicInfo.h"
Owen Andersonbb15fec2011-12-08 22:15:21 +000059#include "llvm/Target/TargetLibraryInfo.h"
Dan Gohman575fad32008-09-03 16:12:24 +000060#include "llvm/Target/TargetLowering.h"
Dan Gohman575fad32008-09-03 16:12:24 +000061#include "llvm/Target/TargetOptions.h"
Richard Sandiford564681c2013-08-12 10:28:10 +000062#include "llvm/Target/TargetSelectionDAGInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000063#include "llvm/Target/TargetSubtargetInfo.h"
Dan Gohman575fad32008-09-03 16:12:24 +000064#include <algorithm>
65using namespace llvm;
66
Chandler Carruth1b9dde02014-04-22 02:02:50 +000067#define DEBUG_TYPE "isel"
68
Dale Johannesenf2a52bb2008-09-05 01:48:15 +000069/// LimitFloatPrecision - Generate low-precision inline sequences for
70/// some float libcalls (6, 8 or 12 bits).
71static unsigned LimitFloatPrecision;
72
73static cl::opt<unsigned, true>
74LimitFPPrecision("limit-float-precision",
75 cl::desc("Generate low-precision inline sequences "
76 "for some float libcalls"),
77 cl::location(LimitFloatPrecision),
78 cl::init(0));
79
Andrew Trick116efac2010-11-12 17:50:46 +000080// Limit the width of DAG chains. This is important in general to prevent
81// prevent DAG-based analysis from blowing up. For example, alias analysis and
82// load clustering may not complete in reasonable time. It is difficult to
83// recognize and avoid this situation within each individual analysis, and
84// future analyses are likely to have the same behavior. Limiting DAG width is
Andrew Trickcf7fefb2010-11-20 07:26:51 +000085// the safe approach, and will be especially important with global DAGs.
Andrew Trick116efac2010-11-12 17:50:46 +000086//
87// MaxParallelChains default is arbitrarily high to avoid affecting
88// optimization, but could be lowered to improve compile time. Any ld-ld-st-st
Andrew Trickcf7fefb2010-11-20 07:26:51 +000089// sequence over this should have been converted to llvm.memcpy by the
90// frontend. It easy to induce this behavior with .ll code such as:
91// %buffer = alloca [4096 x i8]
92// %data = load [4096 x i8]* %argPtr
93// store [4096 x i8] %data, [4096 x i8]* %buffer
Andrew Trick710d5da2011-03-11 17:46:59 +000094static const unsigned MaxParallelChains = 64;
Andrew Trick116efac2010-11-12 17:50:46 +000095
Andrew Trickef9de2a2013-05-25 02:42:55 +000096static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
Chris Lattner05bcb482010-08-24 23:20:40 +000097 const SDValue *Parts, unsigned NumParts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +000098 MVT PartVT, EVT ValueVT, const Value *V);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +000099
Dan Gohman575fad32008-09-03 16:12:24 +0000100/// getCopyFromParts - Create a value that contains the specified legal parts
101/// combined into the value they represent. If the parts combine to a type
102/// larger then ValueVT then AssertOp can be used to specify whether the extra
103/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
104/// (ISD::AssertSext).
Andrew Trickef9de2a2013-05-25 02:42:55 +0000105static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
Dale Johannesendb7c5f62009-01-31 02:22:37 +0000106 const SDValue *Parts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000107 unsigned NumParts, MVT PartVT, EVT ValueVT,
Bill Wendling81406f62012-09-26 04:04:19 +0000108 const Value *V,
Duncan Sandsba21b7d2009-01-28 14:42:54 +0000109 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Chris Lattner05bcb482010-08-24 23:20:40 +0000110 if (ValueVT.isVector())
Bill Wendling81406f62012-09-26 04:04:19 +0000111 return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
112 PartVT, ValueVT, V);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000113
Dan Gohman575fad32008-09-03 16:12:24 +0000114 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohman91febd12009-01-15 16:58:17 +0000115 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman575fad32008-09-03 16:12:24 +0000116 SDValue Val = Parts[0];
117
118 if (NumParts > 1) {
119 // Assemble the value from multiple parts.
Chris Lattner05bcb482010-08-24 23:20:40 +0000120 if (ValueVT.isInteger()) {
Dan Gohman575fad32008-09-03 16:12:24 +0000121 unsigned PartBits = PartVT.getSizeInBits();
122 unsigned ValueBits = ValueVT.getSizeInBits();
123
124 // Assemble the power of 2 part.
125 unsigned RoundParts = NumParts & (NumParts - 1) ?
126 1 << Log2_32(NumParts) : NumParts;
127 unsigned RoundBits = PartBits * RoundParts;
Owen Anderson53aa7a92009-08-10 22:56:29 +0000128 EVT RoundVT = RoundBits == ValueBits ?
Owen Anderson117c9e82009-08-12 00:36:31 +0000129 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
Dan Gohman575fad32008-09-03 16:12:24 +0000130 SDValue Lo, Hi;
131
Owen Anderson117c9e82009-08-12 00:36:31 +0000132 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
Duncan Sands17e678b2008-10-29 14:22:20 +0000133
Dan Gohman575fad32008-09-03 16:12:24 +0000134 if (RoundParts > 2) {
Chris Lattner05bcb482010-08-24 23:20:40 +0000135 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
Bill Wendling81406f62012-09-26 04:04:19 +0000136 PartVT, HalfVT, V);
Chris Lattner05bcb482010-08-24 23:20:40 +0000137 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
Bill Wendling81406f62012-09-26 04:04:19 +0000138 RoundParts / 2, PartVT, HalfVT, V);
Dan Gohman575fad32008-09-03 16:12:24 +0000139 } else {
Wesley Peck527da1b2010-11-23 03:31:01 +0000140 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
141 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
Dan Gohman575fad32008-09-03 16:12:24 +0000142 }
Bill Wendling919b7aa2009-12-22 02:10:19 +0000143
Dan Gohman575fad32008-09-03 16:12:24 +0000144 if (TLI.isBigEndian())
145 std::swap(Lo, Hi);
Bill Wendling919b7aa2009-12-22 02:10:19 +0000146
Chris Lattner05bcb482010-08-24 23:20:40 +0000147 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
Dan Gohman575fad32008-09-03 16:12:24 +0000148
149 if (RoundParts < NumParts) {
150 // Assemble the trailing non-power-of-2 part.
151 unsigned OddParts = NumParts - RoundParts;
Owen Anderson117c9e82009-08-12 00:36:31 +0000152 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
Chris Lattner05bcb482010-08-24 23:20:40 +0000153 Hi = getCopyFromParts(DAG, DL,
Bill Wendling81406f62012-09-26 04:04:19 +0000154 Parts + RoundParts, OddParts, PartVT, OddVT, V);
Dan Gohman575fad32008-09-03 16:12:24 +0000155
156 // Combine the round and odd parts.
157 Lo = Val;
158 if (TLI.isBigEndian())
159 std::swap(Lo, Hi);
Owen Anderson117c9e82009-08-12 00:36:31 +0000160 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Chris Lattner05bcb482010-08-24 23:20:40 +0000161 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
162 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
Dan Gohman575fad32008-09-03 16:12:24 +0000163 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands41826032009-01-31 15:50:11 +0000164 TLI.getPointerTy()));
Chris Lattner05bcb482010-08-24 23:20:40 +0000165 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
166 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
Dan Gohman575fad32008-09-03 16:12:24 +0000167 }
Eli Friedman9030c352009-05-20 06:02:09 +0000168 } else if (PartVT.isFloatingPoint()) {
169 // FP split into multiple FP parts (for ppcf128)
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000170 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
Eli Friedman9030c352009-05-20 06:02:09 +0000171 "Unexpected split");
172 SDValue Lo, Hi;
Wesley Peck527da1b2010-11-23 03:31:01 +0000173 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
174 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
Ulrich Weigandf236bb12014-07-03 15:06:47 +0000175 if (TLI.hasBigEndianPartOrdering(ValueVT))
Eli Friedman9030c352009-05-20 06:02:09 +0000176 std::swap(Lo, Hi);
Chris Lattner05bcb482010-08-24 23:20:40 +0000177 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
Eli Friedman9030c352009-05-20 06:02:09 +0000178 } else {
179 // FP split into integer parts (soft fp)
180 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
181 !PartVT.isVector() && "Unexpected split");
Owen Anderson117c9e82009-08-12 00:36:31 +0000182 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
Bill Wendling81406f62012-09-26 04:04:19 +0000183 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
Dan Gohman575fad32008-09-03 16:12:24 +0000184 }
185 }
186
187 // There is now one part, held in Val. Correct it to match ValueVT.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000188 EVT PartEVT = Val.getValueType();
Dan Gohman575fad32008-09-03 16:12:24 +0000189
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000190 if (PartEVT == ValueVT)
Dan Gohman575fad32008-09-03 16:12:24 +0000191 return Val;
192
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000193 if (PartEVT.isInteger() && ValueVT.isInteger()) {
194 if (ValueVT.bitsLT(PartEVT)) {
Dan Gohman575fad32008-09-03 16:12:24 +0000195 // For a truncate, see if we have any information to
196 // indicate whether the truncated bits will always be
197 // zero or sign-extension.
198 if (AssertOp != ISD::DELETED_NODE)
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000199 Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
Dan Gohman575fad32008-09-03 16:12:24 +0000200 DAG.getValueType(ValueVT));
Chris Lattner05bcb482010-08-24 23:20:40 +0000201 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
Dan Gohman575fad32008-09-03 16:12:24 +0000202 }
Chris Lattner05bcb482010-08-24 23:20:40 +0000203 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
Dan Gohman575fad32008-09-03 16:12:24 +0000204 }
205
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000206 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Chris Lattner05bcb482010-08-24 23:20:40 +0000207 // FP_ROUND's are always exact here.
208 if (ValueVT.bitsLT(Val.getValueType()))
209 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
Pete Coopere3d305a2012-01-17 01:54:07 +0000210 DAG.getTargetConstant(1, TLI.getPointerTy()));
Bill Wendling919b7aa2009-12-22 02:10:19 +0000211
Chris Lattner05bcb482010-08-24 23:20:40 +0000212 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
Dan Gohman575fad32008-09-03 16:12:24 +0000213 }
214
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000215 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
Wesley Peck527da1b2010-11-23 03:31:01 +0000216 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
Dan Gohman575fad32008-09-03 16:12:24 +0000217
Torok Edwinfbcc6632009-07-14 16:55:14 +0000218 llvm_unreachable("Unknown mismatch!");
Dan Gohman575fad32008-09-03 16:12:24 +0000219}
220
Benjamin Kramerfd719b92014-03-29 16:54:29 +0000221static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
222 const Twine &ErrMsg) {
223 const Instruction *I = dyn_cast_or_null<Instruction>(V);
224 if (!V)
225 return Ctx.emitError(ErrMsg);
226
227 const char *AsmError = ", possible invalid constraint for vector type";
228 if (const CallInst *CI = dyn_cast<CallInst>(I))
229 if (isa<InlineAsm>(CI->getCalledValue()))
230 return Ctx.emitError(I, ErrMsg + AsmError);
231
232 return Ctx.emitError(I, ErrMsg);
233}
234
Bill Wendling81406f62012-09-26 04:04:19 +0000235/// getCopyFromPartsVector - Create a value that contains the specified legal
236/// parts combined into the value they represent. If the parts combine to a
237/// type larger then ValueVT then AssertOp can be used to specify whether the
238/// extra bits are known to be zero (ISD::AssertZext) or sign extended from
239/// ValueVT (ISD::AssertSext).
Andrew Trickef9de2a2013-05-25 02:42:55 +0000240static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
Chris Lattner05bcb482010-08-24 23:20:40 +0000241 const SDValue *Parts, unsigned NumParts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000242 MVT PartVT, EVT ValueVT, const Value *V) {
Chris Lattner05bcb482010-08-24 23:20:40 +0000243 assert(ValueVT.isVector() && "Not a vector value");
244 assert(NumParts > 0 && "No parts to assemble!");
245 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
246 SDValue Val = Parts[0];
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000247
Chris Lattner05bcb482010-08-24 23:20:40 +0000248 // Handle a multi-element vector.
249 if (NumParts > 1) {
Patrik Hagglund3f1905192012-12-19 11:53:21 +0000250 EVT IntermediateVT;
251 MVT RegisterVT;
Chris Lattner05bcb482010-08-24 23:20:40 +0000252 unsigned NumIntermediates;
253 unsigned NumRegs =
254 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
255 NumIntermediates, RegisterVT);
256 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
257 NumParts = NumRegs; // Silence a compiler warning.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000258 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
Patrik Hagglund3f1905192012-12-19 11:53:21 +0000259 assert(RegisterVT == Parts[0].getSimpleValueType() &&
Chris Lattner05bcb482010-08-24 23:20:40 +0000260 "Part type doesn't match part!");
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000261
Chris Lattner05bcb482010-08-24 23:20:40 +0000262 // Assemble the parts into intermediate operands.
263 SmallVector<SDValue, 8> Ops(NumIntermediates);
264 if (NumIntermediates == NumParts) {
265 // If the register was not expanded, truncate or copy the value,
266 // as appropriate.
267 for (unsigned i = 0; i != NumParts; ++i)
268 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
Bill Wendling81406f62012-09-26 04:04:19 +0000269 PartVT, IntermediateVT, V);
Chris Lattner05bcb482010-08-24 23:20:40 +0000270 } else if (NumParts > 0) {
271 // If the intermediate type was expanded, build the intermediate
272 // operands from the parts.
273 assert(NumParts % NumIntermediates == 0 &&
274 "Must expand into a divisible number of parts!");
275 unsigned Factor = NumParts / NumIntermediates;
276 for (unsigned i = 0; i != NumIntermediates; ++i)
277 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
Bill Wendling81406f62012-09-26 04:04:19 +0000278 PartVT, IntermediateVT, V);
Chris Lattner05bcb482010-08-24 23:20:40 +0000279 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000280
Chris Lattner05bcb482010-08-24 23:20:40 +0000281 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
282 // intermediate operands.
Craig Topper48d114b2014-04-26 18:35:24 +0000283 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
284 : ISD::BUILD_VECTOR,
285 DL, ValueVT, Ops);
Chris Lattner05bcb482010-08-24 23:20:40 +0000286 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000287
Chris Lattner05bcb482010-08-24 23:20:40 +0000288 // There is now one part, held in Val. Correct it to match ValueVT.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000289 EVT PartEVT = Val.getValueType();
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000290
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000291 if (PartEVT == ValueVT)
Chris Lattner05bcb482010-08-24 23:20:40 +0000292 return Val;
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000293
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000294 if (PartEVT.isVector()) {
Chris Lattner75ff0532010-08-25 22:49:25 +0000295 // If the element type of the source/dest vectors are the same, but the
296 // parts vector has more elements than the value vector, then we have a
297 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
298 // elements we want.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000299 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
300 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
Chris Lattner75ff0532010-08-25 22:49:25 +0000301 "Cannot narrow, it would be a lossy transformation");
302 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
Tom Stellardd42c5942013-08-05 22:22:01 +0000303 DAG.getConstant(0, TLI.getVectorIdxTy()));
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000304 }
305
Chris Lattner75ff0532010-08-25 22:49:25 +0000306 // Vector/Vector bitcast.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000307 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000308 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
309
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000310 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000311 "Cannot handle this kind of promotion");
312 // Promoted vector extract
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000313 bool Smaller = ValueVT.bitsLE(PartEVT);
Nadav Rotem083837e2011-06-12 14:49:38 +0000314 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
315 DL, ValueVT, Val);
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000316
Chris Lattner75ff0532010-08-25 22:49:25 +0000317 }
Eric Christopher0713a9d2011-06-08 23:55:35 +0000318
Eric Christopher690030c2011-06-01 19:55:10 +0000319 // Trivial bitcast if the types are the same size and the destination
320 // vector type is legal.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000321 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
Eric Christopher690030c2011-06-01 19:55:10 +0000322 TLI.isTypeLegal(ValueVT))
323 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000324
Nadav Rotem083837e2011-06-12 14:49:38 +0000325 // Handle cases such as i8 -> <1 x i1>
Bill Wendling81406f62012-09-26 04:04:19 +0000326 if (ValueVT.getVectorNumElements() != 1) {
Benjamin Kramerfd719b92014-03-29 16:54:29 +0000327 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
328 "non-trivial scalar-to-vector conversion");
Chad Rosier8e4824f2013-05-01 19:49:26 +0000329 return DAG.getUNDEF(ValueVT);
Bill Wendling81406f62012-09-26 04:04:19 +0000330 }
Nadav Rotem083837e2011-06-12 14:49:38 +0000331
332 if (ValueVT.getVectorNumElements() == 1 &&
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000333 ValueVT.getVectorElementType() != PartEVT) {
334 bool Smaller = ValueVT.bitsLE(PartEVT);
Nadav Rotem083837e2011-06-12 14:49:38 +0000335 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
336 DL, ValueVT.getScalarType(), Val);
337 }
338
Chris Lattner05bcb482010-08-24 23:20:40 +0000339 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
340}
341
Andrew Trickef9de2a2013-05-25 02:42:55 +0000342static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
Chris Lattner96a77eb2010-08-24 23:10:06 +0000343 SDValue Val, SDValue *Parts, unsigned NumParts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000344 MVT PartVT, const Value *V);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000345
Dan Gohman575fad32008-09-03 16:12:24 +0000346/// getCopyToParts - Create a series of nodes that contain the specified value
347/// split into legal parts. If the parts contain more bits than Val, then, for
348/// integers, ExtendKind can be used to specify how to generate the extra bits.
Andrew Trickef9de2a2013-05-25 02:42:55 +0000349static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
Bill Wendling919b7aa2009-12-22 02:10:19 +0000350 SDValue Val, SDValue *Parts, unsigned NumParts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000351 MVT PartVT, const Value *V,
Dan Gohman575fad32008-09-03 16:12:24 +0000352 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000353 EVT ValueVT = Val.getValueType();
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000354
Chris Lattner96a77eb2010-08-24 23:10:06 +0000355 // Handle the vector case separately.
356 if (ValueVT.isVector())
Bill Wendling5def8912012-09-26 06:16:18 +0000357 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000358
Chris Lattner96a77eb2010-08-24 23:10:06 +0000359 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman575fad32008-09-03 16:12:24 +0000360 unsigned PartBits = PartVT.getSizeInBits();
Dale Johannesen7d12ea02009-02-25 22:39:13 +0000361 unsigned OrigNumParts = NumParts;
Dan Gohman575fad32008-09-03 16:12:24 +0000362 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
363
Chris Lattner96a77eb2010-08-24 23:10:06 +0000364 if (NumParts == 0)
Dan Gohman575fad32008-09-03 16:12:24 +0000365 return;
366
Chris Lattner96a77eb2010-08-24 23:10:06 +0000367 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000368 EVT PartEVT = PartVT;
369 if (PartEVT == ValueVT) {
Chris Lattner96a77eb2010-08-24 23:10:06 +0000370 assert(NumParts == 1 && "No-op copy with multiple parts!");
Dan Gohman575fad32008-09-03 16:12:24 +0000371 Parts[0] = Val;
372 return;
373 }
374
Chris Lattner96a77eb2010-08-24 23:10:06 +0000375 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
376 // If the parts cover more bits than the value has, promote the value.
377 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
378 assert(NumParts == 1 && "Do not know what to promote to!");
379 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
380 } else {
Bill Wendling38b31612012-02-23 23:25:25 +0000381 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
382 ValueVT.isInteger() &&
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000383 "Unknown mismatch!");
Chris Lattner96a77eb2010-08-24 23:10:06 +0000384 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
385 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
Bill Wendling38b31612012-02-23 23:25:25 +0000386 if (PartVT == MVT::x86mmx)
387 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattner96a77eb2010-08-24 23:10:06 +0000388 }
389 } else if (PartBits == ValueVT.getSizeInBits()) {
390 // Different types of the same size.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000391 assert(NumParts == 1 && PartEVT != ValueVT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000392 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattner96a77eb2010-08-24 23:10:06 +0000393 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
394 // If the parts cover less bits than value has, truncate the value.
Bill Wendling38b31612012-02-23 23:25:25 +0000395 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
396 ValueVT.isInteger() &&
Chris Lattner96a77eb2010-08-24 23:10:06 +0000397 "Unknown mismatch!");
398 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
399 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
Bill Wendling38b31612012-02-23 23:25:25 +0000400 if (PartVT == MVT::x86mmx)
401 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattner96a77eb2010-08-24 23:10:06 +0000402 }
403
404 // The value may have changed - recompute ValueVT.
405 ValueVT = Val.getValueType();
406 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
407 "Failed to tile the value with PartVT!");
408
409 if (NumParts == 1) {
Benjamin Kramerfd719b92014-03-29 16:54:29 +0000410 if (PartEVT != ValueVT)
411 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
412 "scalar-to-vector conversion failed");
Bill Wendling5def8912012-09-26 06:16:18 +0000413
Chris Lattner96a77eb2010-08-24 23:10:06 +0000414 Parts[0] = Val;
415 return;
416 }
417
418 // Expand the value into multiple parts.
419 if (NumParts & (NumParts - 1)) {
420 // The number of parts is not a power of 2. Split off and copy the tail.
421 assert(PartVT.isInteger() && ValueVT.isInteger() &&
422 "Do not know what to expand to!");
423 unsigned RoundParts = 1 << Log2_32(NumParts);
424 unsigned RoundBits = RoundParts * PartBits;
425 unsigned OddParts = NumParts - RoundParts;
426 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
427 DAG.getIntPtrConstant(RoundBits));
Bill Wendling5def8912012-09-26 06:16:18 +0000428 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
Chris Lattner96a77eb2010-08-24 23:10:06 +0000429
430 if (TLI.isBigEndian())
431 // The odd parts were reversed by getCopyToParts - unreverse them.
432 std::reverse(Parts + RoundParts, Parts + NumParts);
433
434 NumParts = RoundParts;
435 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
436 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
437 }
438
439 // The number of parts is a power of 2. Repeatedly bisect the value using
440 // EXTRACT_ELEMENT.
Wesley Peck527da1b2010-11-23 03:31:01 +0000441 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
Chris Lattner96a77eb2010-08-24 23:10:06 +0000442 EVT::getIntegerVT(*DAG.getContext(),
443 ValueVT.getSizeInBits()),
444 Val);
445
446 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
447 for (unsigned i = 0; i < NumParts; i += StepSize) {
448 unsigned ThisBits = StepSize * PartBits / 2;
449 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
450 SDValue &Part0 = Parts[i];
451 SDValue &Part1 = Parts[i+StepSize/2];
452
453 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
454 ThisVT, Part0, DAG.getIntPtrConstant(1));
455 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
456 ThisVT, Part0, DAG.getIntPtrConstant(0));
457
458 if (ThisBits == PartBits && ThisVT != PartVT) {
Wesley Peck527da1b2010-11-23 03:31:01 +0000459 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
460 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
Chris Lattner96a77eb2010-08-24 23:10:06 +0000461 }
462 }
463 }
464
465 if (TLI.isBigEndian())
466 std::reverse(Parts, Parts + OrigNumParts);
467}
468
469
470/// getCopyToPartsVector - Create a series of nodes that contain the specified
471/// value split into legal parts.
Andrew Trickef9de2a2013-05-25 02:42:55 +0000472static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
Chris Lattner96a77eb2010-08-24 23:10:06 +0000473 SDValue Val, SDValue *Parts, unsigned NumParts,
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000474 MVT PartVT, const Value *V) {
Chris Lattner96a77eb2010-08-24 23:10:06 +0000475 EVT ValueVT = Val.getValueType();
476 assert(ValueVT.isVector() && "Not a vector");
477 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000478
Chris Lattner96a77eb2010-08-24 23:10:06 +0000479 if (NumParts == 1) {
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000480 EVT PartEVT = PartVT;
481 if (PartEVT == ValueVT) {
Chris Lattner75ff0532010-08-25 22:49:25 +0000482 // Nothing to do.
483 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
484 // Bitconvert vector->vector case.
Wesley Peck527da1b2010-11-23 03:31:01 +0000485 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattner75ff0532010-08-25 22:49:25 +0000486 } else if (PartVT.isVector() &&
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000487 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
488 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
Chris Lattner75ff0532010-08-25 22:49:25 +0000489 EVT ElementVT = PartVT.getVectorElementType();
490 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
491 // undef elements.
492 SmallVector<SDValue, 16> Ops;
493 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
494 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
Tom Stellardd42c5942013-08-05 22:22:01 +0000495 ElementVT, Val, DAG.getConstant(i,
496 TLI.getVectorIdxTy())));
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000497
Chris Lattner75ff0532010-08-25 22:49:25 +0000498 for (unsigned i = ValueVT.getVectorNumElements(),
499 e = PartVT.getVectorNumElements(); i != e; ++i)
500 Ops.push_back(DAG.getUNDEF(ElementVT));
501
Craig Topper48d114b2014-04-26 18:35:24 +0000502 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
Chris Lattner75ff0532010-08-25 22:49:25 +0000503
504 // FIXME: Use CONCAT for 2x -> 4x.
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000505
Chris Lattner75ff0532010-08-25 22:49:25 +0000506 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
507 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000508 } else if (PartVT.isVector() &&
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000509 PartEVT.getVectorElementType().bitsGE(
Nadav Rotem083837e2011-06-12 14:49:38 +0000510 ValueVT.getVectorElementType()) &&
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000511 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000512
513 // Promoted vector extract
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000514 bool Smaller = PartEVT.bitsLE(ValueVT);
Nadav Rotem36896bf2011-06-19 08:49:38 +0000515 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
516 DL, PartVT, Val);
Nadav Rotem06bd6d32011-06-04 20:58:08 +0000517 } else{
Chris Lattner75ff0532010-08-25 22:49:25 +0000518 // Vector -> scalar conversion.
Nadav Rotem083837e2011-06-12 14:49:38 +0000519 assert(ValueVT.getVectorNumElements() == 1 &&
Chris Lattner75ff0532010-08-25 22:49:25 +0000520 "Only trivial vector-to-scalar conversions should get here!");
521 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
Tom Stellardd42c5942013-08-05 22:22:01 +0000522 PartVT, Val, DAG.getConstant(0, TLI.getVectorIdxTy()));
Nadav Rotem083837e2011-06-12 14:49:38 +0000523
524 bool Smaller = ValueVT.bitsLE(PartVT);
525 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
526 DL, PartVT, Val);
Chris Lattner96a77eb2010-08-24 23:10:06 +0000527 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000528
Chris Lattner96a77eb2010-08-24 23:10:06 +0000529 Parts[0] = Val;
530 return;
531 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000532
Dan Gohman575fad32008-09-03 16:12:24 +0000533 // Handle a multi-element vector.
Patrik Hagglund3f1905192012-12-19 11:53:21 +0000534 EVT IntermediateVT;
535 MVT RegisterVT;
Dan Gohman575fad32008-09-03 16:12:24 +0000536 unsigned NumIntermediates;
Owen Anderson117c9e82009-08-12 00:36:31 +0000537 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
Devang Patel977057f2010-08-26 20:32:32 +0000538 IntermediateVT,
539 NumIntermediates, RegisterVT);
Dan Gohman575fad32008-09-03 16:12:24 +0000540 unsigned NumElements = ValueVT.getVectorNumElements();
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000541
Dan Gohman575fad32008-09-03 16:12:24 +0000542 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
543 NumParts = NumRegs; // Silence a compiler warning.
Patrik Hagglund00e7a112012-12-19 12:33:30 +0000544 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000545
Dan Gohman575fad32008-09-03 16:12:24 +0000546 // Split the vector into intermediate operands.
547 SmallVector<SDValue, 8> Ops(NumIntermediates);
Bill Wendling919b7aa2009-12-22 02:10:19 +0000548 for (unsigned i = 0; i != NumIntermediates; ++i) {
Dan Gohman575fad32008-09-03 16:12:24 +0000549 if (IntermediateVT.isVector())
Chris Lattner96a77eb2010-08-24 23:10:06 +0000550 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
Dan Gohman575fad32008-09-03 16:12:24 +0000551 IntermediateVT, Val,
Tom Stellardd42c5942013-08-05 22:22:01 +0000552 DAG.getConstant(i * (NumElements / NumIntermediates),
553 TLI.getVectorIdxTy()));
Dan Gohman575fad32008-09-03 16:12:24 +0000554 else
Chris Lattner96a77eb2010-08-24 23:10:06 +0000555 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
Tom Stellardd42c5942013-08-05 22:22:01 +0000556 IntermediateVT, Val,
557 DAG.getConstant(i, TLI.getVectorIdxTy()));
Bill Wendling919b7aa2009-12-22 02:10:19 +0000558 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +0000559
Dan Gohman575fad32008-09-03 16:12:24 +0000560 // Split the intermediate operands into legal parts.
561 if (NumParts == NumIntermediates) {
562 // If the register was not expanded, promote or copy the value,
563 // as appropriate.
564 for (unsigned i = 0; i != NumParts; ++i)
Bill Wendling5def8912012-09-26 06:16:18 +0000565 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
Dan Gohman575fad32008-09-03 16:12:24 +0000566 } else if (NumParts > 0) {
567 // If the intermediate type was expanded, split each the value into
568 // legal parts.
569 assert(NumParts % NumIntermediates == 0 &&
570 "Must expand into a divisible number of parts!");
571 unsigned Factor = NumParts / NumIntermediates;
572 for (unsigned i = 0; i != NumIntermediates; ++i)
Bill Wendling5def8912012-09-26 06:16:18 +0000573 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
Dan Gohman575fad32008-09-03 16:12:24 +0000574 }
575}
576
Dan Gohman4db93c92010-05-29 17:53:24 +0000577namespace {
578 /// RegsForValue - This struct represents the registers (physical or virtual)
579 /// that a particular set of values is assigned, and the type information
580 /// about the value. The most common situation is to represent one value at a
581 /// time, but struct or array values are handled element-wise as multiple
582 /// values. The splitting of aggregates is performed recursively, so that we
583 /// never have aggregate-typed registers. The values at this point do not
584 /// necessarily have legal types, so each value may require one or more
585 /// registers of some legal type.
586 ///
587 struct RegsForValue {
588 /// ValueVTs - The value types of the values, which may not be legal, and
589 /// may need be promoted or synthesized from one or more registers.
590 ///
591 SmallVector<EVT, 4> ValueVTs;
592
593 /// RegVTs - The value types of the registers. This is the same size as
594 /// ValueVTs and it records, for each value, what the type of the assigned
595 /// register or registers are. (Individual values are never synthesized
596 /// from more than one type of register.)
597 ///
598 /// With virtual registers, the contents of RegVTs is redundant with TLI's
599 /// getRegisterType member function, however when with physical registers
600 /// it is necessary to have a separate record of the types.
601 ///
Patrik Hagglund4e0f8282012-12-19 12:23:01 +0000602 SmallVector<MVT, 4> RegVTs;
Dan Gohman4db93c92010-05-29 17:53:24 +0000603
604 /// Regs - This list holds the registers assigned to the values.
605 /// Each legal or promoted value requires one register, and each
606 /// expanded value requires multiple registers.
607 ///
608 SmallVector<unsigned, 4> Regs;
609
610 RegsForValue() {}
611
612 RegsForValue(const SmallVector<unsigned, 4> &regs,
Patrik Hagglund4e0f8282012-12-19 12:23:01 +0000613 MVT regvt, EVT valuevt)
Dan Gohman4db93c92010-05-29 17:53:24 +0000614 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
615
Dan Gohman4db93c92010-05-29 17:53:24 +0000616 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
Chris Lattner229907c2011-07-18 04:54:35 +0000617 unsigned Reg, Type *Ty) {
Dan Gohman4db93c92010-05-29 17:53:24 +0000618 ComputeValueVTs(tli, Ty, ValueVTs);
619
620 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
621 EVT ValueVT = ValueVTs[Value];
622 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
Patrik Hagglundbad545c2012-12-19 11:48:16 +0000623 MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
Dan Gohman4db93c92010-05-29 17:53:24 +0000624 for (unsigned i = 0; i != NumRegs; ++i)
625 Regs.push_back(Reg + i);
626 RegVTs.push_back(RegisterVT);
627 Reg += NumRegs;
628 }
629 }
630
Dan Gohman4db93c92010-05-29 17:53:24 +0000631 /// append - Add the specified values to this one.
632 void append(const RegsForValue &RHS) {
633 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
634 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
635 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
636 }
637
638 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
639 /// this value and returns the result as a ValueVTs value. This uses
640 /// Chain/Flag as the input and updates them for the output Chain/Flag.
641 /// If the Flag pointer is NULL, no flag is used.
642 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000643 SDLoc dl,
Bill Wendling81406f62012-09-26 04:04:19 +0000644 SDValue &Chain, SDValue *Flag,
Craig Topperc0196b12014-04-14 00:51:57 +0000645 const Value *V = nullptr) const;
Dan Gohman4db93c92010-05-29 17:53:24 +0000646
647 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
648 /// specified value into the registers specified by this object. This uses
649 /// Chain/Flag as the input and updates them for the output Chain/Flag.
650 /// If the Flag pointer is NULL, no flag is used.
Jiangning Liuffbc6902014-09-19 05:30:35 +0000651 void
652 getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl, SDValue &Chain,
653 SDValue *Flag, const Value *V,
654 ISD::NodeType PreferredExtendType = ISD::ANY_EXTEND) const;
Dan Gohman4db93c92010-05-29 17:53:24 +0000655
656 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
657 /// operand list. This adds the code marker, matching input operand index
658 /// (if applicable), and includes the number of values added into it.
659 void AddInlineAsmOperands(unsigned Kind,
660 bool HasMatching, unsigned MatchingIdx,
661 SelectionDAG &DAG,
662 std::vector<SDValue> &Ops) const;
663 };
664}
665
666/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
667/// this value and returns the result as a ValueVT value. This uses
668/// Chain/Flag as the input and updates them for the output Chain/Flag.
669/// If the Flag pointer is NULL, no flag is used.
670SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
671 FunctionLoweringInfo &FuncInfo,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000672 SDLoc dl,
Bill Wendling81406f62012-09-26 04:04:19 +0000673 SDValue &Chain, SDValue *Flag,
674 const Value *V) const {
Dan Gohman2810bac2010-07-26 18:15:41 +0000675 // A Value with type {} or [0 x %t] needs no registers.
676 if (ValueVTs.empty())
677 return SDValue();
678
Dan Gohman4db93c92010-05-29 17:53:24 +0000679 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
680
681 // Assemble the legal parts into the final values.
682 SmallVector<SDValue, 4> Values(ValueVTs.size());
683 SmallVector<SDValue, 8> Parts;
684 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
685 // Copy the legal parts from the registers.
686 EVT ValueVT = ValueVTs[Value];
687 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
Patrik Hagglund4e0f8282012-12-19 12:23:01 +0000688 MVT RegisterVT = RegVTs[Value];
Dan Gohman4db93c92010-05-29 17:53:24 +0000689
690 Parts.resize(NumRegs);
691 for (unsigned i = 0; i != NumRegs; ++i) {
692 SDValue P;
Craig Topperc0196b12014-04-14 00:51:57 +0000693 if (!Flag) {
Dan Gohman4db93c92010-05-29 17:53:24 +0000694 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
695 } else {
696 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
697 *Flag = P.getValue(2);
698 }
699
700 Chain = P.getValue(1);
Chris Lattnercb404362010-12-13 01:11:17 +0000701 Parts[i] = P;
Dan Gohman4db93c92010-05-29 17:53:24 +0000702
703 // If the source register was virtual and if we know something about it,
704 // add an assert node.
Chris Lattnercb404362010-12-13 01:11:17 +0000705 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
Cameron Zwarich64706472011-02-24 10:00:08 +0000706 !RegisterVT.isInteger() || RegisterVT.isVector())
Chris Lattnercb404362010-12-13 01:11:17 +0000707 continue;
Cameron Zwarich64706472011-02-24 10:00:08 +0000708
709 const FunctionLoweringInfo::LiveOutInfo *LOI =
710 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
711 if (!LOI)
712 continue;
Dan Gohman4db93c92010-05-29 17:53:24 +0000713
Chris Lattnercb404362010-12-13 01:11:17 +0000714 unsigned RegSize = RegisterVT.getSizeInBits();
Cameron Zwarich64706472011-02-24 10:00:08 +0000715 unsigned NumSignBits = LOI->NumSignBits;
716 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
Dan Gohman4db93c92010-05-29 17:53:24 +0000717
Quentin Colombetb51a6862013-06-18 20:14:39 +0000718 if (NumZeroBits == RegSize) {
719 // The current value is a zero.
720 // Explicitly express that as it would be easier for
721 // optimizations to kick in.
722 Parts[i] = DAG.getConstant(0, RegisterVT);
723 continue;
724 }
725
Chris Lattnercb404362010-12-13 01:11:17 +0000726 // FIXME: We capture more information than the dag can represent. For
727 // now, just use the tightest assertzext/assertsext possible.
728 bool isSExt = true;
729 EVT FromVT(MVT::Other);
730 if (NumSignBits == RegSize)
731 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
732 else if (NumZeroBits >= RegSize-1)
733 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
734 else if (NumSignBits > RegSize-8)
735 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
736 else if (NumZeroBits >= RegSize-8)
737 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
738 else if (NumSignBits > RegSize-16)
739 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
740 else if (NumZeroBits >= RegSize-16)
741 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
742 else if (NumSignBits > RegSize-32)
743 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
744 else if (NumZeroBits >= RegSize-32)
745 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
746 else
747 continue;
Dan Gohman4db93c92010-05-29 17:53:24 +0000748
Chris Lattnercb404362010-12-13 01:11:17 +0000749 // Add an assertion node.
750 assert(FromVT != MVT::Other);
751 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
752 RegisterVT, P, DAG.getValueType(FromVT));
Dan Gohman4db93c92010-05-29 17:53:24 +0000753 }
754
755 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
Bill Wendling81406f62012-09-26 04:04:19 +0000756 NumRegs, RegisterVT, ValueVT, V);
Dan Gohman4db93c92010-05-29 17:53:24 +0000757 Part += NumRegs;
758 Parts.clear();
759 }
760
Craig Topper48d114b2014-04-26 18:35:24 +0000761 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
Dan Gohman4db93c92010-05-29 17:53:24 +0000762}
763
764/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
765/// specified value into the registers specified by this object. This uses
766/// Chain/Flag as the input and updates them for the output Chain/Flag.
767/// If the Flag pointer is NULL, no flag is used.
Andrew Trickef9de2a2013-05-25 02:42:55 +0000768void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
Jiangning Liuffbc6902014-09-19 05:30:35 +0000769 SDValue &Chain, SDValue *Flag, const Value *V,
770 ISD::NodeType PreferredExtendType) const {
Dan Gohman4db93c92010-05-29 17:53:24 +0000771 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Jiangning Liuffbc6902014-09-19 05:30:35 +0000772 ISD::NodeType ExtendKind = PreferredExtendType;
Dan Gohman4db93c92010-05-29 17:53:24 +0000773
774 // Get the list of the values's legal parts.
775 unsigned NumRegs = Regs.size();
776 SmallVector<SDValue, 8> Parts(NumRegs);
777 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
778 EVT ValueVT = ValueVTs[Value];
779 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
Patrik Hagglund4e0f8282012-12-19 12:23:01 +0000780 MVT RegisterVT = RegVTs[Value];
Jiangning Liuffbc6902014-09-19 05:30:35 +0000781
782 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
783 ExtendKind = ISD::ZERO_EXTEND;
Dan Gohman4db93c92010-05-29 17:53:24 +0000784
Chris Lattner05bcb482010-08-24 23:20:40 +0000785 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
Evan Cheng9ec512d2012-12-06 19:13:27 +0000786 &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
Dan Gohman4db93c92010-05-29 17:53:24 +0000787 Part += NumParts;
788 }
789
790 // Copy the parts into the registers.
791 SmallVector<SDValue, 8> Chains(NumRegs);
792 for (unsigned i = 0; i != NumRegs; ++i) {
793 SDValue Part;
Craig Topperc0196b12014-04-14 00:51:57 +0000794 if (!Flag) {
Dan Gohman4db93c92010-05-29 17:53:24 +0000795 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
796 } else {
797 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
798 *Flag = Part.getValue(1);
799 }
800
801 Chains[i] = Part.getValue(0);
802 }
803
804 if (NumRegs == 1 || Flag)
805 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
806 // flagged to it. That is the CopyToReg nodes and the user are considered
807 // a single scheduling unit. If we create a TokenFactor and return it as
808 // chain, then the TokenFactor is both a predecessor (operand) of the
809 // user as well as a successor (the TF operands are flagged to the user).
810 // c1, f1 = CopyToReg
811 // c2, f2 = CopyToReg
812 // c3 = TokenFactor c1, c2
813 // ...
814 // = op c3, ..., f2
815 Chain = Chains[NumRegs-1];
816 else
Craig Topper48d114b2014-04-26 18:35:24 +0000817 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
Dan Gohman4db93c92010-05-29 17:53:24 +0000818}
819
820/// AddInlineAsmOperands - Add this value to the specified inlineasm node
821/// operand list. This adds the code marker and includes the number of
822/// values added into it.
823void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
824 unsigned MatchingIdx,
825 SelectionDAG &DAG,
826 std::vector<SDValue> &Ops) const {
827 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
828
829 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
830 if (HasMatching)
831 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
Jakob Stoklund Olesen24abd9d2011-10-12 23:37:29 +0000832 else if (!Regs.empty() &&
833 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
834 // Put the register class of the virtual registers in the flag word. That
835 // way, later passes can recompute register class constraints for inline
836 // assembly as well as normal instructions.
837 // Don't do this for tied operands that can use the regclass information
838 // from the def.
839 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
840 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
841 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
842 }
843
Dan Gohman4db93c92010-05-29 17:53:24 +0000844 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
845 Ops.push_back(Res);
846
Reid Kleckneree088972013-12-10 18:27:32 +0000847 unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
Dan Gohman4db93c92010-05-29 17:53:24 +0000848 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
849 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
Patrik Hagglund4e0f8282012-12-19 12:23:01 +0000850 MVT RegisterVT = RegVTs[Value];
Dan Gohman4db93c92010-05-29 17:53:24 +0000851 for (unsigned i = 0; i != NumRegs; ++i) {
852 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Reid Kleckneree088972013-12-10 18:27:32 +0000853 unsigned TheReg = Regs[Reg++];
854 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
855
Reid Kleckneree088972013-12-10 18:27:32 +0000856 if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
Hans Wennborgacb842d2014-03-05 02:43:26 +0000857 // If we clobbered the stack pointer, MFI should know about it.
858 assert(DAG.getMachineFunction().getFrameInfo()->
859 hasInlineAsmWithSPAdjust());
Reid Kleckneree088972013-12-10 18:27:32 +0000860 }
Dan Gohman4db93c92010-05-29 17:53:24 +0000861 }
862 }
863}
Dan Gohman575fad32008-09-03 16:12:24 +0000864
Owen Andersonbb15fec2011-12-08 22:15:21 +0000865void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
866 const TargetLibraryInfo *li) {
Dan Gohman575fad32008-09-03 16:12:24 +0000867 AA = &aa;
868 GFI = gfi;
Owen Andersonbb15fec2011-12-08 22:15:21 +0000869 LibInfo = li;
Eric Christopherfc6de422014-08-05 02:39:49 +0000870 DL = DAG.getSubtarget().getDataLayout();
Richard Smith3fb20472012-08-22 00:42:39 +0000871 Context = DAG.getContext();
Bill Wendling2730a002011-10-15 01:00:26 +0000872 LPadToCallSiteMap.clear();
Dan Gohman575fad32008-09-03 16:12:24 +0000873}
874
Dan Gohmanf5cca352010-04-14 18:24:06 +0000875/// clear - Clear out the current SelectionDAG and the associated
Dan Gohman1a6c47f2009-11-23 18:04:58 +0000876/// state and prepare this SelectionDAGBuilder object to be used
Dan Gohman575fad32008-09-03 16:12:24 +0000877/// for a new block. This doesn't clear out information about
878/// additional blocks that are needed to complete switch lowering
879/// or PHI node updating; that information is cleared out as it is
880/// consumed.
Dan Gohman1a6c47f2009-11-23 18:04:58 +0000881void SelectionDAGBuilder::clear() {
Dan Gohman575fad32008-09-03 16:12:24 +0000882 NodeMap.clear();
Devang Patelb0c76392010-06-01 19:59:01 +0000883 UnusedArgNodeMap.clear();
Dan Gohman575fad32008-09-03 16:12:24 +0000884 PendingLoads.clear();
885 PendingExports.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000886 CurInst = nullptr;
Dan Gohmanf9bbcd12009-08-05 01:29:28 +0000887 HasTailCall = false;
Nico Rieckb5262d62014-01-12 14:09:17 +0000888 SDNodeOrder = LowestSDNodeOrder;
Philip Reames1a1bdb22014-12-02 18:50:36 +0000889 StatepointLowering.clear();
Dan Gohman575fad32008-09-03 16:12:24 +0000890}
891
Devang Patel799288382011-05-23 17:44:13 +0000892/// clearDanglingDebugInfo - Clear the dangling debug information
Benjamin Kramerbde91762012-06-02 10:20:22 +0000893/// map. This function is separated from the clear so that debug
Devang Patel799288382011-05-23 17:44:13 +0000894/// information that is dangling in a basic block can be properly
895/// resolved in a different basic block. This allows the
896/// SelectionDAG to resolve dangling debug information attached
897/// to PHI nodes.
898void SelectionDAGBuilder::clearDanglingDebugInfo() {
899 DanglingDebugInfoMap.clear();
900}
901
Dan Gohman575fad32008-09-03 16:12:24 +0000902/// getRoot - Return the current virtual root of the Selection DAG,
903/// flushing any PendingLoad items. This must be done before emitting
904/// a store or any other node that may need to be ordered after any
905/// prior load instructions.
906///
Dan Gohman1a6c47f2009-11-23 18:04:58 +0000907SDValue SelectionDAGBuilder::getRoot() {
Dan Gohman575fad32008-09-03 16:12:24 +0000908 if (PendingLoads.empty())
909 return DAG.getRoot();
910
911 if (PendingLoads.size() == 1) {
912 SDValue Root = PendingLoads[0];
913 DAG.setRoot(Root);
914 PendingLoads.clear();
915 return Root;
916 }
917
918 // Otherwise, we have to make a token factor node.
Andrew Trickef9de2a2013-05-25 02:42:55 +0000919 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +0000920 PendingLoads);
Dan Gohman575fad32008-09-03 16:12:24 +0000921 PendingLoads.clear();
922 DAG.setRoot(Root);
923 return Root;
924}
925
926/// getControlRoot - Similar to getRoot, but instead of flushing all the
927/// PendingLoad items, flush all the PendingExports items. It is necessary
928/// to do this before emitting a terminator instruction.
929///
Dan Gohman1a6c47f2009-11-23 18:04:58 +0000930SDValue SelectionDAGBuilder::getControlRoot() {
Dan Gohman575fad32008-09-03 16:12:24 +0000931 SDValue Root = DAG.getRoot();
932
933 if (PendingExports.empty())
934 return Root;
935
936 // Turn all of the CopyToReg chains into one factored node.
937 if (Root.getOpcode() != ISD::EntryToken) {
938 unsigned i = 0, e = PendingExports.size();
939 for (; i != e; ++i) {
940 assert(PendingExports[i].getNode()->getNumOperands() > 1);
941 if (PendingExports[i].getNode()->getOperand(0) == Root)
942 break; // Don't add the root if we already indirectly depend on it.
943 }
944
945 if (i == e)
946 PendingExports.push_back(Root);
947 }
948
Andrew Trickef9de2a2013-05-25 02:42:55 +0000949 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +0000950 PendingExports);
Dan Gohman575fad32008-09-03 16:12:24 +0000951 PendingExports.clear();
952 DAG.setRoot(Root);
953 return Root;
954}
955
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000956void SelectionDAGBuilder::visit(const Instruction &I) {
Dan Gohman5b43aa02010-04-22 20:55:53 +0000957 // Set up outgoing PHI node register values before emitting the terminator.
958 if (isa<TerminatorInst>(&I))
959 HandlePHINodesInSuccessorBlocks(I.getParent());
960
Andrew Tricke2431c62013-05-25 03:08:10 +0000961 ++SDNodeOrder;
962
Andrew Trick175143b2013-05-25 02:20:36 +0000963 CurInst = &I;
Dan Gohmane450d742010-04-20 00:48:35 +0000964
Dan Gohman575fad32008-09-03 16:12:24 +0000965 visit(I.getOpcode(), I);
Dan Gohmane450d742010-04-20 00:48:35 +0000966
Dan Gohman950fe782010-04-20 15:03:56 +0000967 if (!isa<TerminatorInst>(&I) && !HasTailCall)
968 CopyToExportRegsIfNeeded(&I);
969
Craig Topperc0196b12014-04-14 00:51:57 +0000970 CurInst = nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +0000971}
972
Dan Gohmanf41ad472010-04-20 15:00:41 +0000973void SelectionDAGBuilder::visitPHI(const PHINode &) {
974 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
975}
976
Dan Gohmanbcaf6812010-04-15 01:51:59 +0000977void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +0000978 // Note: this doesn't use InstVisitor, because it has to work with
979 // ConstantExpr's in addition to instructions.
980 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000981 default: llvm_unreachable("Unknown instruction type encountered!");
Dan Gohman575fad32008-09-03 16:12:24 +0000982 // Build the switch statement using the Instruction.def file.
983#define HANDLE_INST(NUM, OPCODE, CLASS) \
Galina Kistanovaaaf97352012-07-19 04:50:12 +0000984 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000985#include "llvm/IR/Instruction.def"
Dan Gohman575fad32008-09-03 16:12:24 +0000986 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +0000987}
Dan Gohman575fad32008-09-03 16:12:24 +0000988
Dale Johannesenbfd4fd72010-07-16 00:02:08 +0000989// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
990// generate the debug data structures now that we've seen its definition.
991void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
992 SDValue Val) {
993 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
Devang Patelb12ff592010-08-26 23:35:15 +0000994 if (DDI.getDI()) {
995 const DbgValueInst *DI = DDI.getDI();
Dale Johannesenbfd4fd72010-07-16 00:02:08 +0000996 DebugLoc dl = DDI.getdl();
997 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
Devang Patelb12ff592010-08-26 23:35:15 +0000998 MDNode *Variable = DI->getVariable();
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000999 MDNode *Expr = DI->getExpression();
Devang Patelb12ff592010-08-26 23:35:15 +00001000 uint64_t Offset = DI->getOffset();
Adrian Prantl32da8892014-04-25 20:49:25 +00001001 // A dbg.value for an alloca is always indirect.
1002 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00001003 SDDbgValue *SDV;
1004 if (Val.getNode()) {
Adrian Prantl87b7eb92014-10-01 18:55:02 +00001005 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, Offset, IsIndirect,
1006 Val)) {
1007 SDV = DAG.getDbgValue(Variable, Expr, Val.getNode(), Val.getResNo(),
1008 IsIndirect, Offset, dl, DbgSDNodeOrder);
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00001009 DAG.AddDbgValue(SDV, Val.getNode(), false);
1010 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00001011 } else
Adrian Prantl0d1e5592013-05-22 18:02:19 +00001012 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00001013 DanglingDebugInfoMap[V] = DanglingDebugInfo();
1014 }
1015}
1016
Nick Lewyckyf40df1d2011-09-30 22:19:53 +00001017/// getValue - Return an SDValue for the given Value.
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001018SDValue SelectionDAGBuilder::getValue(const Value *V) {
Dan Gohmand4322232010-07-01 01:59:43 +00001019 // If we already have an SDValue for this value, use it. It's important
1020 // to do this first, so that we don't create a CopyFromReg if we already
1021 // have a regular SDValue.
Dan Gohman575fad32008-09-03 16:12:24 +00001022 SDValue &N = NodeMap[V];
1023 if (N.getNode()) return N;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001024
Dan Gohmand4322232010-07-01 01:59:43 +00001025 // If there's a virtual register allocated and initialized for this
1026 // value, use it.
1027 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1028 if (It != FuncInfo.ValueMap.end()) {
1029 unsigned InReg = It->second;
Eric Christopher58a24612014-10-08 09:50:54 +00001030 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), InReg,
Eric Christopherd9134482014-08-04 21:25:23 +00001031 V->getType());
Dan Gohmand4322232010-07-01 01:59:43 +00001032 SDValue Chain = DAG.getEntryNode();
Craig Topperc0196b12014-04-14 00:51:57 +00001033 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
Devang Patel70f8e592011-01-25 18:09:58 +00001034 resolveDanglingDebugInfo(V, N);
1035 return N;
Dan Gohmand4322232010-07-01 01:59:43 +00001036 }
1037
1038 // Otherwise create a new SDValue and remember it.
1039 SDValue Val = getValueImpl(V);
1040 NodeMap[V] = Val;
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00001041 resolveDanglingDebugInfo(V, Val);
Dan Gohmand4322232010-07-01 01:59:43 +00001042 return Val;
1043}
1044
1045/// getNonRegisterValue - Return an SDValue for the given Value, but
1046/// don't look in FuncInfo.ValueMap for a virtual register.
1047SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1048 // If we already have an SDValue for this value, use it.
1049 SDValue &N = NodeMap[V];
1050 if (N.getNode()) return N;
1051
1052 // Otherwise create a new SDValue and remember it.
1053 SDValue Val = getValueImpl(V);
1054 NodeMap[V] = Val;
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00001055 resolveDanglingDebugInfo(V, Val);
Dan Gohmand4322232010-07-01 01:59:43 +00001056 return Val;
1057}
1058
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00001059/// getValueImpl - Helper function for getValue and getNonRegisterValue.
Dan Gohmand4322232010-07-01 01:59:43 +00001060/// Create an SDValue for the given value.
1061SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
Eric Christopher58a24612014-10-08 09:50:54 +00001062 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00001063
Dan Gohman8422e572010-04-17 15:32:28 +00001064 if (const Constant *C = dyn_cast<Constant>(V)) {
Eric Christopher58a24612014-10-08 09:50:54 +00001065 EVT VT = TLI.getValueType(V->getType(), true);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001066
Dan Gohman8422e572010-04-17 15:32:28 +00001067 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohmand4322232010-07-01 01:59:43 +00001068 return DAG.getConstant(*CI, VT);
Dan Gohman575fad32008-09-03 16:12:24 +00001069
Dan Gohman8422e572010-04-17 15:32:28 +00001070 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001071 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001072
Matt Arsenault19231e62013-11-16 20:24:41 +00001073 if (isa<ConstantPointerNull>(C)) {
1074 unsigned AS = V->getType()->getPointerAddressSpace();
Eric Christopher58a24612014-10-08 09:50:54 +00001075 return DAG.getConstant(0, TLI.getPointerTy(AS));
Matt Arsenault19231e62013-11-16 20:24:41 +00001076 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001077
Dan Gohman8422e572010-04-17 15:32:28 +00001078 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohmand4322232010-07-01 01:59:43 +00001079 return DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001080
Nate Begeman8d6d4b92009-04-27 18:41:29 +00001081 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
Dan Gohmand4322232010-07-01 01:59:43 +00001082 return DAG.getUNDEF(VT);
Dan Gohman575fad32008-09-03 16:12:24 +00001083
Dan Gohman8422e572010-04-17 15:32:28 +00001084 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Dan Gohman575fad32008-09-03 16:12:24 +00001085 visit(CE->getOpcode(), *CE);
1086 SDValue N1 = NodeMap[V];
Dan Gohman5664b9f2010-04-16 16:55:18 +00001087 assert(N1.getNode() && "visit didn't populate the NodeMap!");
Dan Gohman575fad32008-09-03 16:12:24 +00001088 return N1;
1089 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001090
Dan Gohman575fad32008-09-03 16:12:24 +00001091 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1092 SmallVector<SDValue, 4> Constants;
1093 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1094 OI != OE; ++OI) {
1095 SDNode *Val = getValue(*OI).getNode();
Dan Gohmanf4a0f0f2009-09-08 01:44:02 +00001096 // If the operand is an empty aggregate, there are no values.
1097 if (!Val) continue;
1098 // Add each leaf value from the operand to the Constants list
1099 // to form a flattened list of all the values.
Dan Gohman575fad32008-09-03 16:12:24 +00001100 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1101 Constants.push_back(SDValue(Val, i));
1102 }
Bill Wendlingc6b47342009-12-21 23:47:40 +00001103
Craig Topper64941d92014-04-27 19:20:57 +00001104 return DAG.getMergeValues(Constants, getCurSDLoc());
Dan Gohman575fad32008-09-03 16:12:24 +00001105 }
Stephen Lincfe7f352013-07-08 00:37:03 +00001106
Chris Lattner00245f42012-01-24 13:41:11 +00001107 if (const ConstantDataSequential *CDS =
1108 dyn_cast<ConstantDataSequential>(C)) {
1109 SmallVector<SDValue, 4> Ops;
Chris Lattner9be59592012-01-25 01:27:20 +00001110 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Chris Lattner00245f42012-01-24 13:41:11 +00001111 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1112 // Add each leaf value from the operand to the Constants list
1113 // to form a flattened list of all the values.
1114 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1115 Ops.push_back(SDValue(Val, i));
1116 }
1117
1118 if (isa<ArrayType>(CDS->getType()))
Craig Topper64941d92014-04-27 19:20:57 +00001119 return DAG.getMergeValues(Ops, getCurSDLoc());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001120 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00001121 VT, Ops);
Chris Lattner00245f42012-01-24 13:41:11 +00001122 }
Dan Gohman575fad32008-09-03 16:12:24 +00001123
Duncan Sands19d0b472010-02-16 11:11:14 +00001124 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
Dan Gohman575fad32008-09-03 16:12:24 +00001125 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1126 "Unknown struct or array constant!");
1127
Owen Anderson53aa7a92009-08-10 22:56:29 +00001128 SmallVector<EVT, 4> ValueVTs;
Eric Christopher58a24612014-10-08 09:50:54 +00001129 ComputeValueVTs(TLI, C->getType(), ValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00001130 unsigned NumElts = ValueVTs.size();
1131 if (NumElts == 0)
1132 return SDValue(); // empty struct
1133 SmallVector<SDValue, 4> Constants(NumElts);
1134 for (unsigned i = 0; i != NumElts; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001135 EVT EltVT = ValueVTs[i];
Dan Gohman575fad32008-09-03 16:12:24 +00001136 if (isa<UndefValue>(C))
Dale Johannesen84935752009-02-06 23:05:02 +00001137 Constants[i] = DAG.getUNDEF(EltVT);
Dan Gohman575fad32008-09-03 16:12:24 +00001138 else if (EltVT.isFloatingPoint())
1139 Constants[i] = DAG.getConstantFP(0, EltVT);
1140 else
1141 Constants[i] = DAG.getConstant(0, EltVT);
1142 }
Bill Wendlingc6b47342009-12-21 23:47:40 +00001143
Craig Topper64941d92014-04-27 19:20:57 +00001144 return DAG.getMergeValues(Constants, getCurSDLoc());
Dan Gohman575fad32008-09-03 16:12:24 +00001145 }
1146
Dan Gohman8422e572010-04-17 15:32:28 +00001147 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
Dan Gohman7a6611792009-11-20 23:18:13 +00001148 return DAG.getBlockAddress(BA, VT);
Dan Gohman6c938802009-10-30 01:27:03 +00001149
Chris Lattner229907c2011-07-18 04:54:35 +00001150 VectorType *VecTy = cast<VectorType>(V->getType());
Dan Gohman575fad32008-09-03 16:12:24 +00001151 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001152
Dan Gohman575fad32008-09-03 16:12:24 +00001153 // Now that we know the number and type of the elements, get that number of
1154 // elements into the Ops array based on what kind of constant it is.
1155 SmallVector<SDValue, 16> Ops;
Chris Lattner00245f42012-01-24 13:41:11 +00001156 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
Dan Gohman575fad32008-09-03 16:12:24 +00001157 for (unsigned i = 0; i != NumElements; ++i)
Chris Lattner00245f42012-01-24 13:41:11 +00001158 Ops.push_back(getValue(CV->getOperand(i)));
Dan Gohman575fad32008-09-03 16:12:24 +00001159 } else {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00001160 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Eric Christopher58a24612014-10-08 09:50:54 +00001161 EVT EltVT = TLI.getValueType(VecTy->getElementType());
Dan Gohman575fad32008-09-03 16:12:24 +00001162
1163 SDValue Op;
Nate Begeman8d6d4b92009-04-27 18:41:29 +00001164 if (EltVT.isFloatingPoint())
Dan Gohman575fad32008-09-03 16:12:24 +00001165 Op = DAG.getConstantFP(0, EltVT);
1166 else
1167 Op = DAG.getConstant(0, EltVT);
1168 Ops.assign(NumElements, Op);
1169 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001170
Dan Gohman575fad32008-09-03 16:12:24 +00001171 // Create a BUILD_VECTOR node.
Craig Topper48d114b2014-04-26 18:35:24 +00001172 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
Dan Gohman575fad32008-09-03 16:12:24 +00001173 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001174
Dan Gohman575fad32008-09-03 16:12:24 +00001175 // If this is a static alloca, generate it as the frameindex instead of
1176 // computation.
1177 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1178 DenseMap<const AllocaInst*, int>::iterator SI =
1179 FuncInfo.StaticAllocaMap.find(AI);
1180 if (SI != FuncInfo.StaticAllocaMap.end())
Eric Christopher58a24612014-10-08 09:50:54 +00001181 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
Dan Gohman575fad32008-09-03 16:12:24 +00001182 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001183
Dan Gohmand4322232010-07-01 01:59:43 +00001184 // If this is an instruction which fast-isel has deferred, select it now.
1185 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +00001186 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
Eric Christopher58a24612014-10-08 09:50:54 +00001187 RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
Dan Gohmand7b5ce32010-07-10 09:00:22 +00001188 SDValue Chain = DAG.getEntryNode();
Craig Topperc0196b12014-04-14 00:51:57 +00001189 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
Dan Gohmand4322232010-07-01 01:59:43 +00001190 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001191
Dan Gohmand4322232010-07-01 01:59:43 +00001192 llvm_unreachable("Can't get register for value!");
Dan Gohman575fad32008-09-03 16:12:24 +00001193}
1194
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001195void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
Eric Christopher58a24612014-10-08 09:50:54 +00001196 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00001197 SDValue Chain = getControlRoot();
1198 SmallVector<ISD::OutputArg, 8> Outs;
Dan Gohmanfe7532a2010-07-07 15:54:55 +00001199 SmallVector<SDValue, 8> OutVals;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00001200
Dan Gohmand16aa542010-05-29 17:03:36 +00001201 if (!FuncInfo.CanLowerReturn) {
1202 unsigned DemoteReg = FuncInfo.DemoteRegister;
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001203 const Function *F = I.getParent()->getParent();
1204
1205 // Emit a store of the return value through the virtual register.
1206 // Leave Outs empty so that LowerReturn won't try to load return
1207 // registers the usual way.
1208 SmallVector<EVT, 1> PtrValueVTs;
Eric Christopher58a24612014-10-08 09:50:54 +00001209 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001210 PtrValueVTs);
1211
1212 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1213 SDValue RetOp = getValue(I.getOperand(0));
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00001214
Owen Anderson53aa7a92009-08-10 22:56:29 +00001215 SmallVector<EVT, 4> ValueVTs;
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001216 SmallVector<uint64_t, 4> Offsets;
Eric Christopher58a24612014-10-08 09:50:54 +00001217 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
Dan Gohman8b44b882008-10-21 20:00:42 +00001218 unsigned NumValues = ValueVTs.size();
Dan Gohman8b44b882008-10-21 20:00:42 +00001219
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001220 SmallVector<SDValue, 4> Chains(NumValues);
Bill Wendlingc6b47342009-12-21 23:47:40 +00001221 for (unsigned i = 0; i != NumValues; ++i) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001222 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
Chris Lattner96a77eb2010-08-24 23:10:06 +00001223 RetPtr.getValueType(), RetPtr,
1224 DAG.getIntPtrConstant(Offsets[i]));
Bill Wendlingc6b47342009-12-21 23:47:40 +00001225 Chains[i] =
Andrew Trickef9de2a2013-05-25 02:42:55 +00001226 DAG.getStore(Chain, getCurSDLoc(),
Bill Wendlingc6b47342009-12-21 23:47:40 +00001227 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
Chris Lattnera4f19972010-09-21 18:58:22 +00001228 // FIXME: better loc info would be nice.
1229 Add, MachinePointerInfo(), false, false, 0);
Bill Wendlingc6b47342009-12-21 23:47:40 +00001230 }
1231
Andrew Trickef9de2a2013-05-25 02:42:55 +00001232 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00001233 MVT::Other, Chains);
Chris Lattnerb1af8652010-02-28 18:53:13 +00001234 } else if (I.getNumOperands() != 0) {
1235 SmallVector<EVT, 4> ValueVTs;
Eric Christopher58a24612014-10-08 09:50:54 +00001236 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
Chris Lattnerb1af8652010-02-28 18:53:13 +00001237 unsigned NumValues = ValueVTs.size();
1238 if (NumValues) {
1239 SDValue RetOp = getValue(I.getOperand(0));
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001240 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1241 EVT VT = ValueVTs[j];
Dan Gohman575fad32008-09-03 16:12:24 +00001242
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001243 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001244
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001245 const Function *F = I.getParent()->getParent();
Bill Wendling74dba872012-12-30 13:01:51 +00001246 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1247 Attribute::SExt))
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001248 ExtendKind = ISD::SIGN_EXTEND;
Bill Wendling74dba872012-12-30 13:01:51 +00001249 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1250 Attribute::ZExt))
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001251 ExtendKind = ISD::ZERO_EXTEND;
Dan Gohman575fad32008-09-03 16:12:24 +00001252
Cameron Zwarich2ef0c692011-03-17 14:53:37 +00001253 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
Eric Christopher58a24612014-10-08 09:50:54 +00001254 VT = TLI.getTypeForExtArgOrReturn(*DAG.getContext(), VT, ExtendKind);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001255
Eric Christopher58a24612014-10-08 09:50:54 +00001256 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
1257 MVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001258 SmallVector<SDValue, 4> Parts(NumParts);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001259 getCopyToParts(DAG, getCurSDLoc(),
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001260 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
Bill Wendling5def8912012-09-26 06:16:18 +00001261 &Parts[0], NumParts, PartVT, &I, ExtendKind);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001262
1263 // 'inreg' on function refers to return value
1264 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Bill Wendling74dba872012-12-30 13:01:51 +00001265 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1266 Attribute::InReg))
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001267 Flags.setInReg();
1268
1269 // Propagate extension type if any
Cameron Zwarichd1ad9bc2011-03-16 22:20:07 +00001270 if (ExtendKind == ISD::SIGN_EXTEND)
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001271 Flags.setSExt();
Cameron Zwarichd1ad9bc2011-03-16 22:20:07 +00001272 else if (ExtendKind == ISD::ZERO_EXTEND)
Kenneth Uildriks9f344062009-11-11 19:59:24 +00001273 Flags.setZExt();
1274
Dan Gohmanfe7532a2010-07-07 15:54:55 +00001275 for (unsigned i = 0; i < NumParts; ++i) {
1276 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
Tom Stellard8d7d4de2013-10-23 00:44:24 +00001277 VT, /*isfixed=*/true, 0, 0));
Dan Gohmanfe7532a2010-07-07 15:54:55 +00001278 OutVals.push_back(Parts[i]);
1279 }
Evan Cheng2e9f42b2009-03-25 20:20:11 +00001280 }
Dan Gohman575fad32008-09-03 16:12:24 +00001281 }
1282 }
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00001283
1284 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
Sandeep Patel68c5f472009-09-02 08:44:58 +00001285 CallingConv::ID CallConv =
1286 DAG.getMachineFunction().getFunction()->getCallingConv();
Eric Christopher58a24612014-10-08 09:50:54 +00001287 Chain = DAG.getTargetLoweringInfo().LowerReturn(
Eric Christopherd9134482014-08-04 21:25:23 +00001288 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
Dan Gohman695d8112009-08-06 15:37:27 +00001289
1290 // Verify that the target's LowerReturn behaved as expected.
Owen Anderson9f944592009-08-11 20:47:22 +00001291 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman695d8112009-08-06 15:37:27 +00001292 "LowerReturn didn't return a valid chain!");
1293
1294 // Update the DAG with the new chain value resulting from return lowering.
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00001295 DAG.setRoot(Chain);
Dan Gohman575fad32008-09-03 16:12:24 +00001296}
1297
Dan Gohman9478c3f2009-04-23 23:13:24 +00001298/// CopyToExportRegsIfNeeded - If the given value has virtual registers
1299/// created for it, emit nodes to copy the value into the virtual
1300/// registers.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001301void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
Rafael Espindolae53b7d12011-05-13 15:18:06 +00001302 // Skip empty types
1303 if (V->getType()->isEmptyTy())
1304 return;
1305
Dan Gohman3a7ee8e2010-04-16 17:15:02 +00001306 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1307 if (VMI != FuncInfo.ValueMap.end()) {
1308 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1309 CopyValueToVirtualRegister(V, VMI->second);
Dan Gohman9478c3f2009-04-23 23:13:24 +00001310 }
1311}
1312
Dan Gohman575fad32008-09-03 16:12:24 +00001313/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1314/// the current basic block, add it to ValueMap now so that we'll get a
1315/// CopyTo/FromReg.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001316void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
Dan Gohman575fad32008-09-03 16:12:24 +00001317 // No need to export constants.
1318 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001319
Dan Gohman575fad32008-09-03 16:12:24 +00001320 // Already exported?
1321 if (FuncInfo.isExportedInst(V)) return;
1322
1323 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1324 CopyValueToVirtualRegister(V, Reg);
1325}
1326
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001327bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001328 const BasicBlock *FromBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00001329 // The operands of the setcc have to be in this block. We don't know
1330 // how to export them from some other block.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001331 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
Dan Gohman575fad32008-09-03 16:12:24 +00001332 // Can export from current BB.
1333 if (VI->getParent() == FromBB)
1334 return true;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001335
Dan Gohman575fad32008-09-03 16:12:24 +00001336 // Is already exported, noop.
1337 return FuncInfo.isExportedInst(V);
1338 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001339
Dan Gohman575fad32008-09-03 16:12:24 +00001340 // If this is an argument, we can export it if the BB is the entry block or
1341 // if it is already exported.
1342 if (isa<Argument>(V)) {
1343 if (FromBB == &FromBB->getParent()->getEntryBlock())
1344 return true;
1345
1346 // Otherwise, can only export this if it is already exported.
1347 return FuncInfo.isExportedInst(V);
1348 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001349
Dan Gohman575fad32008-09-03 16:12:24 +00001350 // Otherwise, constants can always be exported.
1351 return true;
1352}
1353
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001354/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
Jakub Staszak96f8c552011-12-20 20:03:10 +00001355uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1356 const MachineBasicBlock *Dst) const {
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001357 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1358 if (!BPI)
1359 return 0;
Jakub Staszak539db982011-07-29 20:05:36 +00001360 const BasicBlock *SrcBB = Src->getBasicBlock();
1361 const BasicBlock *DstBB = Dst->getBasicBlock();
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001362 return BPI->getEdgeWeight(SrcBB, DstBB);
1363}
1364
Jakub Staszak0480a8f2011-07-29 22:25:21 +00001365void SelectionDAGBuilder::
1366addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1367 uint32_t Weight /* = 0 */) {
1368 if (!Weight)
1369 Weight = getEdgeWeight(Src, Dst);
1370 Src->addSuccessor(Dst, Weight);
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001371}
1372
1373
Dan Gohman575fad32008-09-03 16:12:24 +00001374static bool InBlock(const Value *V, const BasicBlock *BB) {
1375 if (const Instruction *I = dyn_cast<Instruction>(V))
1376 return I->getParent() == BB;
1377 return true;
1378}
1379
Dan Gohmand01ddb52008-10-17 21:16:08 +00001380/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1381/// This function emits a branch and is used at the leaves of an OR or an
1382/// AND operator tree.
1383///
1384void
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001385SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001386 MachineBasicBlock *TBB,
1387 MachineBasicBlock *FBB,
Dan Gohman7c0303a2010-04-19 22:41:47 +00001388 MachineBasicBlock *CurBB,
Manman Ren4ece7452014-01-31 00:42:44 +00001389 MachineBasicBlock *SwitchBB,
1390 uint32_t TWeight,
1391 uint32_t FWeight) {
Dan Gohmand01ddb52008-10-17 21:16:08 +00001392 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohman575fad32008-09-03 16:12:24 +00001393
Dan Gohmand01ddb52008-10-17 21:16:08 +00001394 // If the leaf of the tree is a comparison, merge the condition into
1395 // the caseblock.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001396 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
Dan Gohmand01ddb52008-10-17 21:16:08 +00001397 // The operands of the cmp have to be in this block. We don't know
1398 // how to export them from some other block. If this is the first block
1399 // of the sequence, no exporting is needed.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001400 if (CurBB == SwitchBB ||
Dan Gohmand01ddb52008-10-17 21:16:08 +00001401 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1402 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohman575fad32008-09-03 16:12:24 +00001403 ISD::CondCode Condition;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001404 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman293abcc2008-10-17 18:18:45 +00001405 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001406 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman293abcc2008-10-17 18:18:45 +00001407 Condition = getFCmpCondCode(FC->getPredicate());
Nick Lewycky50f02cb2011-12-02 22:16:29 +00001408 if (TM.Options.NoNaNsFPMath)
1409 Condition = getFCmpCodeWithoutNaN(Condition);
Dan Gohman575fad32008-09-03 16:12:24 +00001410 } else {
1411 Condition = ISD::SETEQ; // silence warning.
Torok Edwinfbcc6632009-07-14 16:55:14 +00001412 llvm_unreachable("Unknown compare instruction");
Dan Gohman575fad32008-09-03 16:12:24 +00001413 }
Dan Gohmand01ddb52008-10-17 21:16:08 +00001414
Craig Topperc0196b12014-04-14 00:51:57 +00001415 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1416 TBB, FBB, CurBB, TWeight, FWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001417 SwitchCases.push_back(CB);
1418 return;
1419 }
Dan Gohmand01ddb52008-10-17 21:16:08 +00001420 }
1421
1422 // Create a CaseBlock record representing this branch.
Owen Anderson23a204d2009-07-31 17:39:07 +00001423 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
Craig Topperc0196b12014-04-14 00:51:57 +00001424 nullptr, TBB, FBB, CurBB, TWeight, FWeight);
Dan Gohmand01ddb52008-10-17 21:16:08 +00001425 SwitchCases.push_back(CB);
1426}
1427
Manman Ren4ece7452014-01-31 00:42:44 +00001428/// Scale down both weights to fit into uint32_t.
1429static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
1430 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1431 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1432 NewTrue = NewTrue / Scale;
1433 NewFalse = NewFalse / Scale;
1434}
1435
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001436/// FindMergedConditions - If Cond is an expression like
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001437void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001438 MachineBasicBlock *TBB,
1439 MachineBasicBlock *FBB,
1440 MachineBasicBlock *CurBB,
Dan Gohman7c0303a2010-04-19 22:41:47 +00001441 MachineBasicBlock *SwitchBB,
Manman Ren4ece7452014-01-31 00:42:44 +00001442 unsigned Opc, uint32_t TWeight,
1443 uint32_t FWeight) {
Dan Gohmand01ddb52008-10-17 21:16:08 +00001444 // If this node is not part of the or/and tree, emit it as a branch.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001445 const Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001446 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmand01ddb52008-10-17 21:16:08 +00001447 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1448 BOp->getParent() != CurBB->getBasicBlock() ||
1449 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1450 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Manman Ren4ece7452014-01-31 00:42:44 +00001451 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1452 TWeight, FWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001453 return;
1454 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001455
Dan Gohman575fad32008-09-03 16:12:24 +00001456 // Create TmpBB after CurBB.
1457 MachineFunction::iterator BBI = CurBB;
1458 MachineFunction &MF = DAG.getMachineFunction();
1459 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1460 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001461
Dan Gohman575fad32008-09-03 16:12:24 +00001462 if (Opc == Instruction::Or) {
1463 // Codegen X | Y as:
Manman Ren4ece7452014-01-31 00:42:44 +00001464 // BB1:
Dan Gohman575fad32008-09-03 16:12:24 +00001465 // jmp_if_X TBB
1466 // jmp TmpBB
1467 // TmpBB:
1468 // jmp_if_Y TBB
1469 // jmp FBB
1470 //
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001471
Manman Ren4ece7452014-01-31 00:42:44 +00001472 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1473 // The requirement is that
1474 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1475 // = TrueProb for orignal BB.
1476 // Assuming the orignal weights are A and B, one choice is to set BB1's
1477 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
1478 // assumes that
1479 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1480 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1481 // TmpBB, but the math is more complicated.
Manman Ren104e0c82014-01-30 00:24:37 +00001482
Manman Ren4ece7452014-01-31 00:42:44 +00001483 uint64_t NewTrueWeight = TWeight;
1484 uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
1485 ScaleWeights(NewTrueWeight, NewFalseWeight);
1486 // Emit the LHS condition.
1487 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1488 NewTrueWeight, NewFalseWeight);
1489
1490 NewTrueWeight = TWeight;
1491 NewFalseWeight = 2 * (uint64_t)FWeight;
1492 ScaleWeights(NewTrueWeight, NewFalseWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001493 // Emit the RHS condition into TmpBB.
Manman Ren4ece7452014-01-31 00:42:44 +00001494 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1495 NewTrueWeight, NewFalseWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001496 } else {
1497 assert(Opc == Instruction::And && "Unknown merge op!");
1498 // Codegen X & Y as:
Manman Ren4ece7452014-01-31 00:42:44 +00001499 // BB1:
Dan Gohman575fad32008-09-03 16:12:24 +00001500 // jmp_if_X TmpBB
1501 // jmp FBB
1502 // TmpBB:
1503 // jmp_if_Y TBB
1504 // jmp FBB
1505 //
1506 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001507
Manman Ren4ece7452014-01-31 00:42:44 +00001508 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1509 // The requirement is that
1510 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1511 // = FalseProb for orignal BB.
1512 // Assuming the orignal weights are A and B, one choice is to set BB1's
1513 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
1514 // assumes that
1515 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
Manman Ren104e0c82014-01-30 00:24:37 +00001516
Manman Ren4ece7452014-01-31 00:42:44 +00001517 uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
1518 uint64_t NewFalseWeight = FWeight;
1519 ScaleWeights(NewTrueWeight, NewFalseWeight);
1520 // Emit the LHS condition.
1521 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1522 NewTrueWeight, NewFalseWeight);
1523
1524 NewTrueWeight = 2 * (uint64_t)TWeight;
1525 NewFalseWeight = FWeight;
1526 ScaleWeights(NewTrueWeight, NewFalseWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001527 // Emit the RHS condition into TmpBB.
Manman Ren4ece7452014-01-31 00:42:44 +00001528 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1529 NewTrueWeight, NewFalseWeight);
Dan Gohman575fad32008-09-03 16:12:24 +00001530 }
1531}
1532
1533/// If the set of cases should be emitted as a series of branches, return true.
1534/// If we should emit this as a bunch of and/or'd together conditions, return
1535/// false.
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001536bool
Stephen Lin6d715e82013-07-06 21:44:25 +00001537SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
Dan Gohman575fad32008-09-03 16:12:24 +00001538 if (Cases.size() != 2) return true;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001539
Dan Gohman575fad32008-09-03 16:12:24 +00001540 // If this is two comparisons of the same values or'd or and'd together, they
1541 // will get folded into a single comparison, so don't emit two blocks.
1542 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1543 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1544 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1545 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1546 return false;
1547 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001548
Chris Lattner1eea3b02010-01-02 00:00:03 +00001549 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1550 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1551 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1552 Cases[0].CC == Cases[1].CC &&
1553 isa<Constant>(Cases[0].CmpRHS) &&
1554 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1555 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1556 return false;
1557 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1558 return false;
1559 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00001560
Dan Gohman575fad32008-09-03 16:12:24 +00001561 return true;
1562}
1563
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001564void SelectionDAGBuilder::visitBr(const BranchInst &I) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +00001565 MachineBasicBlock *BrMBB = FuncInfo.MBB;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001566
Dan Gohman575fad32008-09-03 16:12:24 +00001567 // Update machine-CFG edges.
1568 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1569
1570 // Figure out which block is immediately after the current one.
Craig Topperc0196b12014-04-14 00:51:57 +00001571 MachineBasicBlock *NextBlock = nullptr;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001572 MachineFunction::iterator BBI = BrMBB;
Dan Gohmane8c913e2009-08-15 02:06:22 +00001573 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00001574 NextBlock = BBI;
1575
1576 if (I.isUnconditional()) {
1577 // Update machine-CFG edges.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001578 BrMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001579
Eric Christopherbfb38ba2014-04-03 12:11:51 +00001580 // If this is not a fall-through branch or optimizations are switched off,
1581 // emit the branch.
1582 if (Succ0MBB != NextBlock || TM.getOptLevel() == CodeGenOpt::None)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001583 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
Owen Anderson9f944592009-08-11 20:47:22 +00001584 MVT::Other, getControlRoot(),
Bill Wendling954cb182010-01-28 21:51:40 +00001585 DAG.getBasicBlock(Succ0MBB)));
Bill Wendling7f5eb532009-12-21 19:59:38 +00001586
Dan Gohman575fad32008-09-03 16:12:24 +00001587 return;
1588 }
1589
1590 // If this condition is one of the special cases we handle, do special stuff
1591 // now.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001592 const Value *CondVal = I.getCondition();
Dan Gohman575fad32008-09-03 16:12:24 +00001593 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1594
1595 // If this is a series of conditions that are or'd or and'd together, emit
1596 // this as a sequence of branches instead of setcc's with and/or operations.
Chris Lattnerea41dfe2010-11-30 18:12:52 +00001597 // As long as jumps are not expensive, this should improve performance.
Dan Gohman575fad32008-09-03 16:12:24 +00001598 // For example, instead of something like:
1599 // cmp A, B
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001600 // C = seteq
Dan Gohman575fad32008-09-03 16:12:24 +00001601 // cmp D, E
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001602 // F = setle
Dan Gohman575fad32008-09-03 16:12:24 +00001603 // or C, F
1604 // jnz foo
1605 // Emit:
1606 // cmp A, B
1607 // je foo
1608 // cmp D, E
1609 // jle foo
1610 //
Dan Gohmanbcaf6812010-04-15 01:51:59 +00001611 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Eric Christopher58a24612014-10-08 09:50:54 +00001612 if (!DAG.getTargetLoweringInfo().isJumpExpensive() &&
Eric Christopherd9134482014-08-04 21:25:23 +00001613 BOp->hasOneUse() && (BOp->getOpcode() == Instruction::And ||
1614 BOp->getOpcode() == Instruction::Or)) {
Dan Gohman7c0303a2010-04-19 22:41:47 +00001615 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
Manman Ren4ece7452014-01-31 00:42:44 +00001616 BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB),
1617 getEdgeWeight(BrMBB, Succ1MBB));
Dan Gohman575fad32008-09-03 16:12:24 +00001618 // If the compares in later blocks need to use values not currently
1619 // exported from this block, export them now. This block should always
1620 // be the first entry.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001621 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001622
Dan Gohman575fad32008-09-03 16:12:24 +00001623 // Allow some cases to be rejected.
1624 if (ShouldEmitAsBranches(SwitchCases)) {
1625 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1626 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1627 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1628 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001629
Dan Gohman575fad32008-09-03 16:12:24 +00001630 // Emit the branch for this block.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001631 visitSwitchCase(SwitchCases[0], BrMBB);
Dan Gohman575fad32008-09-03 16:12:24 +00001632 SwitchCases.erase(SwitchCases.begin());
1633 return;
1634 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001635
Dan Gohman575fad32008-09-03 16:12:24 +00001636 // Okay, we decided not to do this, remove any inserted MBB's and clear
1637 // SwitchCases.
1638 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
Dan Gohmane8c913e2009-08-15 02:06:22 +00001639 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001640
Dan Gohman575fad32008-09-03 16:12:24 +00001641 SwitchCases.clear();
1642 }
1643 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00001644
Dan Gohman575fad32008-09-03 16:12:24 +00001645 // Create a CaseBlock record representing this branch.
Owen Anderson23a204d2009-07-31 17:39:07 +00001646 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
Craig Topperc0196b12014-04-14 00:51:57 +00001647 nullptr, Succ0MBB, Succ1MBB, BrMBB);
Bill Wendling7f5eb532009-12-21 19:59:38 +00001648
Dan Gohman575fad32008-09-03 16:12:24 +00001649 // Use visitSwitchCase to actually insert the fast branch sequence for this
1650 // cond branch.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001651 visitSwitchCase(CB, BrMBB);
Dan Gohman575fad32008-09-03 16:12:24 +00001652}
1653
1654/// visitSwitchCase - Emits the necessary code to represent a single node in
1655/// the binary search tree resulting from lowering a switch instruction.
Dan Gohman7c0303a2010-04-19 22:41:47 +00001656void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1657 MachineBasicBlock *SwitchBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00001658 SDValue Cond;
1659 SDValue CondLHS = getValue(CB.CmpLHS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001660 SDLoc dl = getCurSDLoc();
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001661
1662 // Build the setcc now.
Craig Topperc0196b12014-04-14 00:51:57 +00001663 if (!CB.CmpMHS) {
Dan Gohman575fad32008-09-03 16:12:24 +00001664 // Fold "(X == true)" to X and "(X == false)" to !X to
1665 // handle common cases produced by branch lowering.
Owen Anderson23a204d2009-07-31 17:39:07 +00001666 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
Owen Anderson2ad52172009-07-21 02:47:59 +00001667 CB.CC == ISD::SETEQ)
Dan Gohman575fad32008-09-03 16:12:24 +00001668 Cond = CondLHS;
Owen Anderson23a204d2009-07-31 17:39:07 +00001669 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
Owen Anderson2ad52172009-07-21 02:47:59 +00001670 CB.CC == ISD::SETEQ) {
Dan Gohman575fad32008-09-03 16:12:24 +00001671 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf2bb6f02009-02-04 01:48:28 +00001672 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohman575fad32008-09-03 16:12:24 +00001673 } else
Owen Anderson9f944592009-08-11 20:47:22 +00001674 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohman575fad32008-09-03 16:12:24 +00001675 } else {
Bob Wilsone4077362013-09-09 19:14:35 +00001676 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Dan Gohman575fad32008-09-03 16:12:24 +00001677
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001678 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1679 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohman575fad32008-09-03 16:12:24 +00001680
1681 SDValue CmpOp = getValue(CB.CmpMHS);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001682 EVT VT = CmpOp.getValueType();
Stephen Lincfe7f352013-07-08 00:37:03 +00001683
Bob Wilsone4077362013-09-09 19:14:35 +00001684 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Owen Anderson9f944592009-08-11 20:47:22 +00001685 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Bob Wilsone4077362013-09-09 19:14:35 +00001686 ISD::SETLE);
Dan Gohman575fad32008-09-03 16:12:24 +00001687 } else {
Dale Johannesenf2bb6f02009-02-04 01:48:28 +00001688 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesened255b32009-01-30 01:34:22 +00001689 VT, CmpOp, DAG.getConstant(Low, VT));
Owen Anderson9f944592009-08-11 20:47:22 +00001690 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohman575fad32008-09-03 16:12:24 +00001691 DAG.getConstant(High-Low, VT), ISD::SETULE);
1692 }
1693 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001694
Dan Gohman575fad32008-09-03 16:12:24 +00001695 // Update successor info
Jakub Staszak0480a8f2011-07-29 22:25:21 +00001696 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
Jakob Stoklund Olesen7d33c572012-08-20 21:39:52 +00001697 // TrueBB and FalseBB are always different unless the incoming IR is
1698 // degenerate. This only happens when running llc on weird IR.
1699 if (CB.TrueBB != CB.FalseBB)
1700 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001701
Dan Gohman575fad32008-09-03 16:12:24 +00001702 // Set NextBlock to be the MBB immediately after the current one, if any.
1703 // This is used to avoid emitting unnecessary branches to the next block.
Craig Topperc0196b12014-04-14 00:51:57 +00001704 MachineBasicBlock *NextBlock = nullptr;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001705 MachineFunction::iterator BBI = SwitchBB;
Dan Gohmane8c913e2009-08-15 02:06:22 +00001706 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00001707 NextBlock = BBI;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001708
Dan Gohman575fad32008-09-03 16:12:24 +00001709 // If the lhs block is the next block, invert the condition so that we can
1710 // fall through to the lhs instead of the rhs block.
1711 if (CB.TrueBB == NextBlock) {
1712 std::swap(CB.TrueBB, CB.FalseBB);
1713 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf2bb6f02009-02-04 01:48:28 +00001714 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohman575fad32008-09-03 16:12:24 +00001715 }
Bill Wendling7f5eb532009-12-21 19:59:38 +00001716
Dale Johannesenf2bb6f02009-02-04 01:48:28 +00001717 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Owen Anderson9f944592009-08-11 20:47:22 +00001718 MVT::Other, getControlRoot(), Cond,
Dale Johannesened255b32009-01-30 01:34:22 +00001719 DAG.getBasicBlock(CB.TrueBB));
Bill Wendlingc6b47342009-12-21 23:47:40 +00001720
Evan Cheng79687dd2010-09-23 06:51:55 +00001721 // Insert the false branch. Do this even if it's a fall through branch,
1722 // this makes it easier to do DAG optimizations which require inverting
1723 // the branch condition.
1724 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1725 DAG.getBasicBlock(CB.FalseBB));
Bill Wendling7f5eb532009-12-21 19:59:38 +00001726
1727 DAG.setRoot(BrCond);
Dan Gohman575fad32008-09-03 16:12:24 +00001728}
1729
1730/// visitJumpTable - Emit JumpTable node in the current MBB
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001731void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
Dan Gohman575fad32008-09-03 16:12:24 +00001732 // Emit the code for the jump table
1733 assert(JT.Reg != -1U && "Should lower JT Header first!");
Eric Christopher58a24612014-10-08 09:50:54 +00001734 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001735 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
Dale Johannesen3a09f552009-02-03 23:04:43 +00001736 JT.Reg, PTy);
Dan Gohman575fad32008-09-03 16:12:24 +00001737 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001738 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
Bill Wendling7f5eb532009-12-21 19:59:38 +00001739 MVT::Other, Index.getValue(1),
1740 Table, Index);
1741 DAG.setRoot(BrJumpTable);
Dan Gohman575fad32008-09-03 16:12:24 +00001742}
1743
1744/// visitJumpTableHeader - This function emits necessary code to produce index
1745/// in the JumpTable from switch case.
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001746void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
Dan Gohman7c0303a2010-04-19 22:41:47 +00001747 JumpTableHeader &JTH,
1748 MachineBasicBlock *SwitchBB) {
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001749 // Subtract the lowest switch case value from the value being switched on and
1750 // conditional branch to default mbb if the result is greater than the
Dan Gohman575fad32008-09-03 16:12:24 +00001751 // difference between smallest and largest cases.
1752 SDValue SwitchOp = getValue(JTH.SValue);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001753 EVT VT = SwitchOp.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001754 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001755 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001756
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001757 // The SDNode we just created, which holds the value being switched on minus
Dan Gohman4a618822010-02-10 16:03:48 +00001758 // the smallest case value, needs to be copied to a virtual register so it
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001759 // can be used as an index into the jump table in a subsequent basic block.
1760 // This value may be smaller or larger than the target's pointer type, and
1761 // therefore require extension or truncating.
Eric Christopher58a24612014-10-08 09:50:54 +00001762 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1763 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI.getPointerTy());
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001764
Eric Christopher58a24612014-10-08 09:50:54 +00001765 unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001766 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
Dale Johannesen3a09f552009-02-03 23:04:43 +00001767 JumpTableReg, SwitchOp);
Dan Gohman575fad32008-09-03 16:12:24 +00001768 JT.Reg = JumpTableReg;
1769
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001770 // Emit the range check for the jump table, and branch to the default block
1771 // for the switch statement if the value being switched on exceeds the largest
1772 // case in the switch.
Eric Christopher58a24612014-10-08 09:50:54 +00001773 SDValue CMP =
1774 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1775 Sub.getValueType()),
1776 Sub, DAG.getConstant(JTH.Last - JTH.First, VT), ISD::SETUGT);
Dan Gohman575fad32008-09-03 16:12:24 +00001777
1778 // Set NextBlock to be the MBB immediately after the current one, if any.
1779 // This is used to avoid emitting unnecessary branches to the next block.
Craig Topperc0196b12014-04-14 00:51:57 +00001780 MachineBasicBlock *NextBlock = nullptr;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001781 MachineFunction::iterator BBI = SwitchBB;
Bill Wendlingc6b47342009-12-21 23:47:40 +00001782
Dan Gohmane8c913e2009-08-15 02:06:22 +00001783 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00001784 NextBlock = BBI;
1785
Andrew Trickef9de2a2013-05-25 02:42:55 +00001786 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
Owen Anderson9f944592009-08-11 20:47:22 +00001787 MVT::Other, CopyTo, CMP,
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001788 DAG.getBasicBlock(JT.Default));
Dan Gohman575fad32008-09-03 16:12:24 +00001789
Bill Wendling954cb182010-01-28 21:51:40 +00001790 if (JT.MBB != NextBlock)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001791 BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
Bill Wendling7f5eb532009-12-21 19:59:38 +00001792 DAG.getBasicBlock(JT.MBB));
Bill Wendling7f5eb532009-12-21 19:59:38 +00001793
Bill Wendlingc6b47342009-12-21 23:47:40 +00001794 DAG.setRoot(BrCond);
Dan Gohman575fad32008-09-03 16:12:24 +00001795}
1796
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00001797/// Codegen a new tail for a stack protector check ParentMBB which has had its
1798/// tail spliced into a stack protector check success bb.
1799///
1800/// For a high level explanation of how this fits into the stack protector
1801/// generation see the comment on the declaration of class
1802/// StackProtectorDescriptor.
1803void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1804 MachineBasicBlock *ParentBB) {
1805
1806 // First create the loads to the guard/stack slot for the comparison.
Eric Christopher58a24612014-10-08 09:50:54 +00001807 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1808 EVT PtrTy = TLI.getPointerTy();
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00001809
1810 MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1811 int FI = MFI->getStackProtectorIndex();
1812
1813 const Value *IRGuard = SPD.getGuard();
1814 SDValue GuardPtr = getValue(IRGuard);
1815 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1816
1817 unsigned Align =
Eric Christopher58a24612014-10-08 09:50:54 +00001818 TLI.getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00001819
1820 SDValue Guard;
1821
Akira Hatanaka5acc58f2014-08-07 23:08:24 +00001822 // If GuardReg is set and useLoadStackGuardNode returns true, retrieve the
1823 // guard value from the virtual register holding the value. Otherwise, emit a
1824 // volatile load to retrieve the stack guard value.
1825 unsigned GuardReg = SPD.getGuardReg();
1826
Eric Christopher58a24612014-10-08 09:50:54 +00001827 if (GuardReg && TLI.useLoadStackGuardNode())
Akira Hatanaka5acc58f2014-08-07 23:08:24 +00001828 Guard = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), GuardReg,
1829 PtrTy);
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00001830 else
1831 Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1832 GuardPtr, MachinePointerInfo(IRGuard, 0),
1833 true, false, false, Align);
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00001834
1835 SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1836 StackSlotPtr,
1837 MachinePointerInfo::getFixedStack(FI),
1838 true, false, false, Align);
1839
1840 // Perform the comparison via a subtract/getsetcc.
1841 EVT VT = Guard.getValueType();
1842 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
1843
Eric Christopher58a24612014-10-08 09:50:54 +00001844 SDValue Cmp =
1845 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1846 Sub.getValueType()),
1847 Sub, DAG.getConstant(0, VT), ISD::SETNE);
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00001848
1849 // If the sub is not 0, then we know the guard/stackslot do not equal, so
1850 // branch to failure MBB.
1851 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1852 MVT::Other, StackSlot.getOperand(0),
1853 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1854 // Otherwise branch to success MBB.
1855 SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
1856 MVT::Other, BrCond,
1857 DAG.getBasicBlock(SPD.getSuccessMBB()));
1858
1859 DAG.setRoot(Br);
1860}
1861
1862/// Codegen the failure basic block for a stack protector check.
1863///
1864/// A failure stack protector machine basic block consists simply of a call to
1865/// __stack_chk_fail().
1866///
1867/// For a high level explanation of how this fits into the stack protector
1868/// generation see the comment on the declaration of class
1869/// StackProtectorDescriptor.
1870void
1871SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
Eric Christopher58a24612014-10-08 09:50:54 +00001872 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1873 SDValue Chain =
1874 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
1875 nullptr, 0, false, getCurSDLoc(), false, false).second;
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00001876 DAG.setRoot(Chain);
1877}
1878
Dan Gohman575fad32008-09-03 16:12:24 +00001879/// visitBitTestHeader - This function emits necessary code to produce value
1880/// suitable for "bit tests"
Dan Gohman7c0303a2010-04-19 22:41:47 +00001881void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1882 MachineBasicBlock *SwitchBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00001883 // Subtract the minimum value
1884 SDValue SwitchOp = getValue(B.SValue);
Patrik Hagglunde98b7a02012-12-11 11:14:33 +00001885 EVT VT = SwitchOp.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001886 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001887 DAG.getConstant(B.First, VT));
Dan Gohman575fad32008-09-03 16:12:24 +00001888
1889 // Check range
Eric Christopher58a24612014-10-08 09:50:54 +00001890 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1891 SDValue RangeCmp =
1892 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
Matt Arsenault758659232013-05-18 00:21:46 +00001893 Sub.getValueType()),
Eric Christopher58a24612014-10-08 09:50:54 +00001894 Sub, DAG.getConstant(B.Range, VT), ISD::SETUGT);
Dan Gohman575fad32008-09-03 16:12:24 +00001895
Evan Chengac730dd2011-01-06 01:02:44 +00001896 // Determine the type of the test operands.
1897 bool UsePtrType = false;
Eric Christopher58a24612014-10-08 09:50:54 +00001898 if (!TLI.isTypeLegal(VT))
Evan Chengac730dd2011-01-06 01:02:44 +00001899 UsePtrType = true;
1900 else {
1901 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
Eli Friedman979009e2011-10-12 22:46:45 +00001902 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
Evan Chengac730dd2011-01-06 01:02:44 +00001903 // Switch table case range are encoded into series of masks.
1904 // Just use pointer type, it's guaranteed to fit.
1905 UsePtrType = true;
1906 break;
1907 }
1908 }
1909 if (UsePtrType) {
Eric Christopher58a24612014-10-08 09:50:54 +00001910 VT = TLI.getPointerTy();
Andrew Trickef9de2a2013-05-25 02:42:55 +00001911 Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
Evan Chengac730dd2011-01-06 01:02:44 +00001912 }
Dan Gohman575fad32008-09-03 16:12:24 +00001913
Patrik Hagglund5e6c3612012-12-13 06:34:11 +00001914 B.RegVT = VT.getSimpleVT();
Patrik Hagglund4e0f8282012-12-19 12:23:01 +00001915 B.Reg = FuncInfo.CreateReg(B.RegVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001916 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
Evan Chengac730dd2011-01-06 01:02:44 +00001917 B.Reg, Sub);
Dan Gohman575fad32008-09-03 16:12:24 +00001918
1919 // Set NextBlock to be the MBB immediately after the current one, if any.
1920 // This is used to avoid emitting unnecessary branches to the next block.
Craig Topperc0196b12014-04-14 00:51:57 +00001921 MachineBasicBlock *NextBlock = nullptr;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001922 MachineFunction::iterator BBI = SwitchBB;
Dan Gohmane8c913e2009-08-15 02:06:22 +00001923 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00001924 NextBlock = BBI;
1925
1926 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1927
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001928 addSuccessorWithWeight(SwitchBB, B.Default);
1929 addSuccessorWithWeight(SwitchBB, MBB);
Dan Gohman575fad32008-09-03 16:12:24 +00001930
Andrew Trickef9de2a2013-05-25 02:42:55 +00001931 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
Owen Anderson9f944592009-08-11 20:47:22 +00001932 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov05149ba2008-12-23 22:25:45 +00001933 DAG.getBasicBlock(B.Default));
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001934
Evan Cheng6b8b2b72010-09-23 18:32:19 +00001935 if (MBB != NextBlock)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001936 BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
Evan Cheng6b8b2b72010-09-23 18:32:19 +00001937 DAG.getBasicBlock(MBB));
Bill Wendling7f5eb532009-12-21 19:59:38 +00001938
Bill Wendlingc6b47342009-12-21 23:47:40 +00001939 DAG.setRoot(BrRange);
Dan Gohman575fad32008-09-03 16:12:24 +00001940}
1941
1942/// visitBitTestCase - this function produces one "bit test"
Evan Chengac730dd2011-01-06 01:02:44 +00001943void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1944 MachineBasicBlock* NextMBB,
Manman Rencf104462012-08-24 18:14:27 +00001945 uint32_t BranchWeightToNext,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00001946 unsigned Reg,
Dan Gohman7c0303a2010-04-19 22:41:47 +00001947 BitTestCase &B,
1948 MachineBasicBlock *SwitchBB) {
Patrik Hagglund4e0f8282012-12-19 12:23:01 +00001949 MVT VT = BB.RegVT;
Andrew Trickef9de2a2013-05-25 02:42:55 +00001950 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
Evan Chengac730dd2011-01-06 01:02:44 +00001951 Reg, VT);
Dan Gohman0695e092010-06-24 02:06:24 +00001952 SDValue Cmp;
Benjamin Kramer15cd5a32011-07-14 01:38:42 +00001953 unsigned PopCount = CountPopulation_64(B.Mask);
Eric Christopher58a24612014-10-08 09:50:54 +00001954 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Benjamin Kramer15cd5a32011-07-14 01:38:42 +00001955 if (PopCount == 1) {
Dan Gohman0695e092010-06-24 02:06:24 +00001956 // Testing for a single bit; just compare the shift count with what it
1957 // would need to be to shift a 1 bit in that position.
Eric Christopher58a24612014-10-08 09:50:54 +00001958 Cmp = DAG.getSetCC(
1959 getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1960 DAG.getConstant(countTrailingZeros(B.Mask), VT), ISD::SETEQ);
Benjamin Kramer15cd5a32011-07-14 01:38:42 +00001961 } else if (PopCount == BB.Range) {
1962 // There is only one zero bit in the range, test for it directly.
Eric Christopher58a24612014-10-08 09:50:54 +00001963 Cmp = DAG.getSetCC(
1964 getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1965 DAG.getConstant(CountTrailingOnes_64(B.Mask), VT), ISD::SETNE);
Dan Gohman0695e092010-06-24 02:06:24 +00001966 } else {
1967 // Make desired shift
Andrew Trickef9de2a2013-05-25 02:42:55 +00001968 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
Evan Chengac730dd2011-01-06 01:02:44 +00001969 DAG.getConstant(1, VT), ShiftOp);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001970
Dan Gohman0695e092010-06-24 02:06:24 +00001971 // Emit bit tests and jumps
Andrew Trickef9de2a2013-05-25 02:42:55 +00001972 SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
Evan Chengac730dd2011-01-06 01:02:44 +00001973 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001974 Cmp = DAG.getSetCC(getCurSDLoc(),
Eric Christopher58a24612014-10-08 09:50:54 +00001975 TLI.getSetCCResultType(*DAG.getContext(), VT), AndOp,
1976 DAG.getConstant(0, VT), ISD::SETNE);
Dan Gohman0695e092010-06-24 02:06:24 +00001977 }
Dan Gohman575fad32008-09-03 16:12:24 +00001978
Manman Rencf104462012-08-24 18:14:27 +00001979 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
1980 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
1981 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
1982 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00001983
Andrew Trickef9de2a2013-05-25 02:42:55 +00001984 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
Owen Anderson9f944592009-08-11 20:47:22 +00001985 MVT::Other, getControlRoot(),
Dan Gohman0695e092010-06-24 02:06:24 +00001986 Cmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohman575fad32008-09-03 16:12:24 +00001987
1988 // Set NextBlock to be the MBB immediately after the current one, if any.
1989 // This is used to avoid emitting unnecessary branches to the next block.
Craig Topperc0196b12014-04-14 00:51:57 +00001990 MachineBasicBlock *NextBlock = nullptr;
Dan Gohman7c0303a2010-04-19 22:41:47 +00001991 MachineFunction::iterator BBI = SwitchBB;
Dan Gohmane8c913e2009-08-15 02:06:22 +00001992 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00001993 NextBlock = BBI;
1994
Evan Cheng6b8b2b72010-09-23 18:32:19 +00001995 if (NextMBB != NextBlock)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001996 BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
Evan Cheng6b8b2b72010-09-23 18:32:19 +00001997 DAG.getBasicBlock(NextMBB));
Bill Wendling28727f32009-12-21 21:59:52 +00001998
Bill Wendlingc6b47342009-12-21 23:47:40 +00001999 DAG.setRoot(BrAnd);
Dan Gohman575fad32008-09-03 16:12:24 +00002000}
2001
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002002void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +00002003 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
Dan Gohman7c0303a2010-04-19 22:41:47 +00002004
Dan Gohman575fad32008-09-03 16:12:24 +00002005 // Retrieve successors.
2006 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2007 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
2008
Gabor Greif08a4c282009-01-15 11:10:44 +00002009 const Value *Callee(I.getCalledValue());
Nuno Lopesec9653b2012-06-28 22:30:12 +00002010 const Function *Fn = dyn_cast<Function>(Callee);
Gabor Greif08a4c282009-01-15 11:10:44 +00002011 if (isa<InlineAsm>(Callee))
Dan Gohman575fad32008-09-03 16:12:24 +00002012 visitInlineAsm(&I);
Nuno Lopesec9653b2012-06-28 22:30:12 +00002013 else if (Fn && Fn->isIntrinsic()) {
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00002014 switch (Fn->getIntrinsicID()) {
2015 default:
2016 llvm_unreachable("Cannot invoke this intrinsic");
2017 case Intrinsic::donothing:
2018 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2019 break;
2020 case Intrinsic::experimental_patchpoint_void:
2021 case Intrinsic::experimental_patchpoint_i64:
2022 visitPatchpoint(&I, LandingPad);
2023 break;
2024 }
Nuno Lopesec9653b2012-06-28 22:30:12 +00002025 } else
Gabor Greif08a4c282009-01-15 11:10:44 +00002026 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohman575fad32008-09-03 16:12:24 +00002027
2028 // If the value of the invoke is used outside of its defining block, make it
2029 // available as a virtual register.
Dan Gohman9478c3f2009-04-23 23:13:24 +00002030 CopyToExportRegsIfNeeded(&I);
Dan Gohman575fad32008-09-03 16:12:24 +00002031
2032 // Update successor info
Chandler Carruthe2530dc2011-11-22 11:37:46 +00002033 addSuccessorWithWeight(InvokeMBB, Return);
2034 addSuccessorWithWeight(InvokeMBB, LandingPad);
Dan Gohman575fad32008-09-03 16:12:24 +00002035
2036 // Drop into normal successor.
Andrew Trickef9de2a2013-05-25 02:42:55 +00002037 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00002038 MVT::Other, getControlRoot(),
2039 DAG.getBasicBlock(Return)));
Dan Gohman575fad32008-09-03 16:12:24 +00002040}
2041
Bill Wendlingf891bf82011-07-31 06:30:59 +00002042void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2043 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2044}
2045
Bill Wendling247fd3b2011-08-17 21:56:44 +00002046void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2047 assert(FuncInfo.MBB->isLandingPad() &&
2048 "Call to landingpad not in landing pad!");
2049
2050 MachineBasicBlock *MBB = FuncInfo.MBB;
2051 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
2052 AddLandingPadInfo(LP, MMI, MBB);
2053
Bill Wendling05d6f2f2012-02-13 23:47:16 +00002054 // If there aren't registers to copy the values into (e.g., during SjLj
2055 // exceptions), then don't bother to create these DAG nodes.
Eric Christopher58a24612014-10-08 09:50:54 +00002056 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2057 if (TLI.getExceptionPointerRegister() == 0 &&
2058 TLI.getExceptionSelectorRegister() == 0)
Bill Wendling05d6f2f2012-02-13 23:47:16 +00002059 return;
2060
Bill Wendling247fd3b2011-08-17 21:56:44 +00002061 SmallVector<EVT, 2> ValueVTs;
Eric Christopher58a24612014-10-08 09:50:54 +00002062 ComputeValueVTs(TLI, LP.getType(), ValueVTs);
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002063 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
Bill Wendling247fd3b2011-08-17 21:56:44 +00002064
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002065 // Get the two live-in registers as SDValues. The physregs have already been
2066 // copied into virtual registers.
Bill Wendling247fd3b2011-08-17 21:56:44 +00002067 SDValue Ops[2];
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002068 Ops[0] = DAG.getZExtOrTrunc(
Eric Christopher58a24612014-10-08 09:50:54 +00002069 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2070 FuncInfo.ExceptionPointerVirtReg, TLI.getPointerTy()),
2071 getCurSDLoc(), ValueVTs[0]);
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002072 Ops[1] = DAG.getZExtOrTrunc(
Eric Christopher58a24612014-10-08 09:50:54 +00002073 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2074 FuncInfo.ExceptionSelectorVirtReg, TLI.getPointerTy()),
2075 getCurSDLoc(), ValueVTs[1]);
Bill Wendling247fd3b2011-08-17 21:56:44 +00002076
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002077 // Merge into one.
Andrew Trickef9de2a2013-05-25 02:42:55 +00002078 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00002079 DAG.getVTList(ValueVTs), Ops);
Jakob Stoklund Olesenfee2a202013-07-04 04:53:45 +00002080 setValue(&LP, Res);
Bill Wendling247fd3b2011-08-17 21:56:44 +00002081}
2082
Dan Gohman575fad32008-09-03 16:12:24 +00002083/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
2084/// small case ranges).
Dan Gohman1a6c47f2009-11-23 18:04:58 +00002085bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
2086 CaseRecVector& WorkList,
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002087 const Value* SV,
Dan Gohman7c0303a2010-04-19 22:41:47 +00002088 MachineBasicBlock *Default,
2089 MachineBasicBlock *SwitchBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00002090 // Size is the number of Cases represented by this range.
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002091 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohman575fad32008-09-03 16:12:24 +00002092 if (Size > 3)
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002093 return false;
2094
Dan Gohman575fad32008-09-03 16:12:24 +00002095 // Get the MachineFunction which holds the current MBB. This is used when
2096 // inserting any additional MBBs necessary to represent the switch.
Dan Gohmane8c913e2009-08-15 02:06:22 +00002097 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohman575fad32008-09-03 16:12:24 +00002098
2099 // Figure out which block is immediately after the current one.
Craig Topperc0196b12014-04-14 00:51:57 +00002100 MachineBasicBlock *NextBlock = nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00002101 MachineFunction::iterator BBI = CR.CaseBB;
2102
Dan Gohmane8c913e2009-08-15 02:06:22 +00002103 if (++BBI != FuncInfo.MF->end())
Dan Gohman575fad32008-09-03 16:12:24 +00002104 NextBlock = BBI;
2105
Manman Rencf104462012-08-24 18:14:27 +00002106 BranchProbabilityInfo *BPI = FuncInfo.BPI;
Benjamin Kramer24656c92010-11-22 09:45:38 +00002107 // If any two of the cases has the same destination, and if one value
Dan Gohman575fad32008-09-03 16:12:24 +00002108 // is the same as the other, but has one bit unset that the other has set,
2109 // use bit manipulation to do two compares at once. For example:
2110 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Benjamin Kramer24656c92010-11-22 09:45:38 +00002111 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
2112 // TODO: Handle cases where CR.CaseBB != SwitchBB.
2113 if (Size == 2 && CR.CaseBB == SwitchBB) {
2114 Case &Small = *CR.Range.first;
2115 Case &Big = *(CR.Range.second-1);
2116
2117 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
2118 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
2119 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
2120
2121 // Check that there is only one bit different.
2122 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
2123 (SmallValue | BigValue) == BigValue) {
2124 // Isolate the common bit.
2125 APInt CommonBit = BigValue & ~SmallValue;
2126 assert((SmallValue | CommonBit) == BigValue &&
2127 CommonBit.countPopulation() == 1 && "Not a common bit?");
2128
2129 SDValue CondLHS = getValue(SV);
2130 EVT VT = CondLHS.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002131 SDLoc DL = getCurSDLoc();
Benjamin Kramer24656c92010-11-22 09:45:38 +00002132
2133 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
2134 DAG.getConstant(CommonBit, VT));
2135 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
2136 Or, DAG.getConstant(BigValue, VT),
2137 ISD::SETEQ);
2138
2139 // Update successor info.
Manman Rencf104462012-08-24 18:14:27 +00002140 // Both Small and Big will jump to Small.BB, so we sum up the weights.
2141 addSuccessorWithWeight(SwitchBB, Small.BB,
2142 Small.ExtraWeight + Big.ExtraWeight);
2143 addSuccessorWithWeight(SwitchBB, Default,
2144 // The default destination is the first successor in IR.
2145 BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
Benjamin Kramer24656c92010-11-22 09:45:38 +00002146
2147 // Insert the true branch.
2148 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
2149 getControlRoot(), Cond,
2150 DAG.getBasicBlock(Small.BB));
2151
2152 // Insert the false branch.
2153 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
2154 DAG.getBasicBlock(Default));
2155
2156 DAG.setRoot(BrCond);
2157 return true;
2158 }
2159 }
2160 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002161
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002162 // Order cases by weight so the most likely case will be checked first.
Manman Rencf104462012-08-24 18:14:27 +00002163 uint32_t UnhandledWeights = 0;
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002164 if (BPI) {
2165 for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
Manman Rencf104462012-08-24 18:14:27 +00002166 uint32_t IWeight = I->ExtraWeight;
2167 UnhandledWeights += IWeight;
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002168 for (CaseItr J = CR.Range.first; J < I; ++J) {
Manman Rencf104462012-08-24 18:14:27 +00002169 uint32_t JWeight = J->ExtraWeight;
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002170 if (IWeight > JWeight)
2171 std::swap(*I, *J);
2172 }
2173 }
2174 }
Dan Gohman575fad32008-09-03 16:12:24 +00002175 // Rearrange the case blocks so that the last one falls through if possible.
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002176 Case &BackCase = *(CR.Range.second-1);
Benjamin Kramer5aad8722012-05-26 21:19:12 +00002177 if (Size > 1 &&
2178 NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Dan Gohman575fad32008-09-03 16:12:24 +00002179 // The last case block won't fall through into 'NextBlock' if we emit the
2180 // branches in this order. See if rearranging a case value would help.
Benjamin Kramerf2beccf2012-05-26 20:01:32 +00002181 // We start at the bottom as it's the case with the least weight.
Stephen Lin6d715e82013-07-06 21:44:25 +00002182 for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
Dan Gohman575fad32008-09-03 16:12:24 +00002183 if (I->BB == NextBlock) {
2184 std::swap(*I, BackCase);
2185 break;
2186 }
Dan Gohman575fad32008-09-03 16:12:24 +00002187 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002188
Dan Gohman575fad32008-09-03 16:12:24 +00002189 // Create a CaseBlock record representing a conditional branch to
2190 // the Case's target mbb if the value being switched on SV is equal
2191 // to C.
2192 MachineBasicBlock *CurBlock = CR.CaseBB;
2193 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2194 MachineBasicBlock *FallThrough;
2195 if (I != E-1) {
2196 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2197 CurMF->insert(BBI, FallThrough);
Dan Gohmane6db8ca2009-04-09 02:33:36 +00002198
2199 // Put SV in a virtual register to make it available from the new blocks.
2200 ExportFromCurrentBlock(SV);
Dan Gohman575fad32008-09-03 16:12:24 +00002201 } else {
2202 // If the last case doesn't match, go to the default block.
2203 FallThrough = Default;
2204 }
2205
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002206 const Value *RHS, *LHS, *MHS;
Dan Gohman575fad32008-09-03 16:12:24 +00002207 ISD::CondCode CC;
2208 if (I->High == I->Low) {
2209 // This is just small small case range :) containing exactly 1 case
2210 CC = ISD::SETEQ;
Craig Topperc0196b12014-04-14 00:51:57 +00002211 LHS = SV; RHS = I->High; MHS = nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00002212 } else {
Bob Wilsone4077362013-09-09 19:14:35 +00002213 CC = ISD::SETLE;
Dan Gohman575fad32008-09-03 16:12:24 +00002214 LHS = I->Low; MHS = SV; RHS = I->High;
2215 }
Jakub Staszak0480a8f2011-07-29 22:25:21 +00002216
Manman Rencf104462012-08-24 18:14:27 +00002217 // The false weight should be sum of all un-handled cases.
2218 UnhandledWeights -= I->ExtraWeight;
Jakub Staszak0480a8f2011-07-29 22:25:21 +00002219 CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
2220 /* me */ CurBlock,
Manman Rencf104462012-08-24 18:14:27 +00002221 /* trueweight */ I->ExtraWeight,
2222 /* falseweight */ UnhandledWeights);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002223
Dan Gohman575fad32008-09-03 16:12:24 +00002224 // If emitting the first comparison, just call visitSwitchCase to emit the
2225 // code into the current block. Otherwise, push the CaseBlock onto the
2226 // vector to be later processed by SDISel, and insert the node's MBB
2227 // before the next MBB.
Dan Gohman7c0303a2010-04-19 22:41:47 +00002228 if (CurBlock == SwitchBB)
2229 visitSwitchCase(CB, SwitchBB);
Dan Gohman575fad32008-09-03 16:12:24 +00002230 else
2231 SwitchCases.push_back(CB);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002232
Dan Gohman575fad32008-09-03 16:12:24 +00002233 CurBlock = FallThrough;
2234 }
2235
2236 return true;
2237}
2238
2239static inline bool areJTsAllowed(const TargetLowering &TLI) {
Eric Christopher79cc1e32014-09-02 22:28:02 +00002240 return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
2241 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
Dan Gohman575fad32008-09-03 16:12:24 +00002242}
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002243
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002244static APInt ComputeRange(const APInt &First, const APInt &Last) {
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002245 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
Bob Wilsone4077362013-09-09 19:14:35 +00002246 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002247 return (LastExt - FirstExt + 1ULL);
2248}
2249
Dan Gohman575fad32008-09-03 16:12:24 +00002250/// handleJTSwitchCase - Emit jumptable for current switch case range
Chris Lattnere74e0c82011-09-09 22:06:59 +00002251bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
2252 CaseRecVector &WorkList,
2253 const Value *SV,
2254 MachineBasicBlock *Default,
Dan Gohman7c0303a2010-04-19 22:41:47 +00002255 MachineBasicBlock *SwitchBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00002256 Case& FrontCase = *CR.Range.first;
2257 Case& BackCase = *(CR.Range.second-1);
2258
Chris Lattner8e1d7222009-11-07 07:50:34 +00002259 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2260 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohman575fad32008-09-03 16:12:24 +00002261
Chris Lattner8e1d7222009-11-07 07:50:34 +00002262 APInt TSize(First.getBitWidth(), 0);
Chris Lattnere74e0c82011-09-09 22:06:59 +00002263 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
Dan Gohman575fad32008-09-03 16:12:24 +00002264 TSize += I->size();
2265
Eric Christopher58a24612014-10-08 09:50:54 +00002266 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2267 if (!areJTsAllowed(TLI) || TSize.ult(TLI.getMinimumJumpTableEntries()))
Dan Gohman575fad32008-09-03 16:12:24 +00002268 return false;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002269
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002270 APInt Range = ComputeRange(First, Last);
Jakob Stoklund Olesene8261a22011-10-26 01:47:48 +00002271 // The density is TSize / Range. Require at least 40%.
2272 // It should not be possible for IntTSize to saturate for sane code, but make
2273 // sure we handle Range saturation correctly.
2274 uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
2275 uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
2276 if (IntTSize * 10 < IntRange * 4)
Dan Gohman575fad32008-09-03 16:12:24 +00002277 return false;
2278
David Greene5730f202010-01-05 01:24:57 +00002279 DEBUG(dbgs() << "Lowering jump table\n"
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002280 << "First entry: " << First << ". Last entry: " << Last << '\n'
Jakob Stoklund Olesene8261a22011-10-26 01:47:48 +00002281 << "Range: " << Range << ". Size: " << TSize << ".\n\n");
Dan Gohman575fad32008-09-03 16:12:24 +00002282
2283 // Get the MachineFunction which holds the current MBB. This is used when
2284 // inserting any additional MBBs necessary to represent the switch.
Dan Gohmane8c913e2009-08-15 02:06:22 +00002285 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohman575fad32008-09-03 16:12:24 +00002286
2287 // Figure out which block is immediately after the current one.
Dan Gohman575fad32008-09-03 16:12:24 +00002288 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands3ee3c172009-09-06 18:03:32 +00002289 ++BBI;
Dan Gohman575fad32008-09-03 16:12:24 +00002290
2291 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2292
2293 // Create a new basic block to hold the code for loading the address
2294 // of the jump table, and jumping to it. Update successor information;
2295 // we will either branch to the default case for the switch, or the jump
2296 // table.
2297 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2298 CurMF->insert(BBI, JumpTableBB);
Jakub Staszak12a43bd2011-06-16 20:22:37 +00002299
2300 addSuccessorWithWeight(CR.CaseBB, Default);
2301 addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002302
Dan Gohman575fad32008-09-03 16:12:24 +00002303 // Build a vector of destination BBs, corresponding to each target
2304 // of the jump table. If the value of the jump table slot corresponds to
2305 // a case statement, push the case's BB onto the vector, otherwise, push
2306 // the default BB.
2307 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002308 APInt TEI = First;
Dan Gohman575fad32008-09-03 16:12:24 +00002309 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Chris Lattnerb6db2c62010-01-25 23:26:13 +00002310 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
2311 const APInt &High = cast<ConstantInt>(I->High)->getValue();
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002312
Bob Wilsone4077362013-09-09 19:14:35 +00002313 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohman575fad32008-09-03 16:12:24 +00002314 DestBBs.push_back(I->BB);
2315 if (TEI==High)
2316 ++I;
2317 } else {
2318 DestBBs.push_back(Default);
2319 }
2320 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002321
Manman Rencf104462012-08-24 18:14:27 +00002322 // Calculate weight for each unique destination in CR.
2323 DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
2324 if (FuncInfo.BPI)
2325 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2326 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2327 DestWeights.find(I->BB);
Stephen Lincfe7f352013-07-08 00:37:03 +00002328 if (Itr != DestWeights.end())
Manman Rencf104462012-08-24 18:14:27 +00002329 Itr->second += I->ExtraWeight;
2330 else
2331 DestWeights[I->BB] = I->ExtraWeight;
2332 }
2333
Dan Gohman575fad32008-09-03 16:12:24 +00002334 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002335 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2336 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohman575fad32008-09-03 16:12:24 +00002337 E = DestBBs.end(); I != E; ++I) {
2338 if (!SuccsHandled[(*I)->getNumber()]) {
2339 SuccsHandled[(*I)->getNumber()] = true;
Manman Rencf104462012-08-24 18:14:27 +00002340 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2341 DestWeights.find(*I);
2342 addSuccessorWithWeight(JumpTableBB, *I,
2343 Itr != DestWeights.end() ? Itr->second : 0);
Dan Gohman575fad32008-09-03 16:12:24 +00002344 }
2345 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002346
Bob Wilson3c7cde42010-03-18 18:42:41 +00002347 // Create a jump table index for this jump table.
Eric Christopher58a24612014-10-08 09:50:54 +00002348 unsigned JTEncoding = TLI.getJumpTableEncoding();
Chris Lattnerb6db2c62010-01-25 23:26:13 +00002349 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
Bob Wilson3c7cde42010-03-18 18:42:41 +00002350 ->createJumpTableIndex(DestBBs);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002351
Dan Gohman575fad32008-09-03 16:12:24 +00002352 // Set the jump table information so that we can codegen it as a second
2353 // MachineBasicBlock
2354 JumpTable JT(-1U, JTI, JumpTableBB, Default);
Dan Gohman7c0303a2010-04-19 22:41:47 +00002355 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2356 if (CR.CaseBB == SwitchBB)
2357 visitJumpTableHeader(JT, JTH, SwitchBB);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002358
Dan Gohman575fad32008-09-03 16:12:24 +00002359 JTCases.push_back(JumpTableBlock(JTH, JT));
Dan Gohman575fad32008-09-03 16:12:24 +00002360 return true;
2361}
2362
2363/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2364/// 2 subtrees.
Dan Gohman1a6c47f2009-11-23 18:04:58 +00002365bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2366 CaseRecVector& WorkList,
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002367 const Value* SV,
Stephen Lin6d715e82013-07-06 21:44:25 +00002368 MachineBasicBlock* SwitchBB) {
Dan Gohman575fad32008-09-03 16:12:24 +00002369 // Get the MachineFunction which holds the current MBB. This is used when
2370 // inserting any additional MBBs necessary to represent the switch.
Dan Gohmane8c913e2009-08-15 02:06:22 +00002371 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohman575fad32008-09-03 16:12:24 +00002372
2373 // Figure out which block is immediately after the current one.
Dan Gohman575fad32008-09-03 16:12:24 +00002374 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands3ee3c172009-09-06 18:03:32 +00002375 ++BBI;
Dan Gohman575fad32008-09-03 16:12:24 +00002376
2377 Case& FrontCase = *CR.Range.first;
2378 Case& BackCase = *(CR.Range.second-1);
2379 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2380
2381 // Size is the number of Cases represented by this range.
2382 unsigned Size = CR.Range.second - CR.Range.first;
2383
Chris Lattner8e1d7222009-11-07 07:50:34 +00002384 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2385 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohman575fad32008-09-03 16:12:24 +00002386 double FMetric = 0;
2387 CaseItr Pivot = CR.Range.first + Size/2;
2388
2389 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2390 // (heuristically) allow us to emit JumpTable's later.
Chris Lattner8e1d7222009-11-07 07:50:34 +00002391 APInt TSize(First.getBitWidth(), 0);
Dan Gohman575fad32008-09-03 16:12:24 +00002392 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2393 I!=E; ++I)
2394 TSize += I->size();
2395
Chris Lattner8e1d7222009-11-07 07:50:34 +00002396 APInt LSize = FrontCase.size();
2397 APInt RSize = TSize-LSize;
David Greene5730f202010-01-05 01:24:57 +00002398 DEBUG(dbgs() << "Selecting best pivot: \n"
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002399 << "First: " << First << ", Last: " << Last <<'\n'
2400 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohman575fad32008-09-03 16:12:24 +00002401 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2402 J!=E; ++I, ++J) {
Chris Lattner8e1d7222009-11-07 07:50:34 +00002403 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2404 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002405 APInt Range = ComputeRange(LEnd, RBegin);
Stepan Dyatkovskiye01e9862012-05-15 06:50:18 +00002406 assert((Range - 2ULL).isNonNegative() &&
2407 "Invalid case distance");
Chris Lattnercfe5aa62011-04-09 06:57:13 +00002408 // Use volatile double here to avoid excess precision issues on some hosts,
2409 // e.g. that use 80-bit X87 registers.
2410 volatile double LDensity =
2411 (double)LSize.roundToDouble() /
Chris Lattner8e1d7222009-11-07 07:50:34 +00002412 (LEnd - First + 1ULL).roundToDouble();
Chris Lattnercfe5aa62011-04-09 06:57:13 +00002413 volatile double RDensity =
2414 (double)RSize.roundToDouble() /
Chris Lattner8e1d7222009-11-07 07:50:34 +00002415 (Last - RBegin + 1ULL).roundToDouble();
Rafael Espindolad50dbc72013-12-05 04:14:33 +00002416 volatile double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohman575fad32008-09-03 16:12:24 +00002417 // Should always split in some non-trivial place
David Greene5730f202010-01-05 01:24:57 +00002418 DEBUG(dbgs() <<"=>Step\n"
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002419 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2420 << "LDensity: " << LDensity
2421 << ", RDensity: " << RDensity << '\n'
2422 << "Metric: " << Metric << '\n');
Dan Gohman575fad32008-09-03 16:12:24 +00002423 if (FMetric < Metric) {
2424 Pivot = J;
2425 FMetric = Metric;
David Greene5730f202010-01-05 01:24:57 +00002426 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
Dan Gohman575fad32008-09-03 16:12:24 +00002427 }
2428
2429 LSize += J->size();
2430 RSize -= J->size();
2431 }
Bill Wendlinga3cd3502013-06-19 21:36:55 +00002432
Eric Christopher58a24612014-10-08 09:50:54 +00002433 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2434 if (areJTsAllowed(TLI)) {
Dan Gohman575fad32008-09-03 16:12:24 +00002435 // If our case is dense we *really* should handle it earlier!
2436 assert((FMetric > 0) && "Should handle dense range earlier!");
2437 } else {
2438 Pivot = CR.Range.first + Size/2;
2439 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002440
Dan Gohman575fad32008-09-03 16:12:24 +00002441 CaseRange LHSR(CR.Range.first, Pivot);
2442 CaseRange RHSR(Pivot, CR.Range.second);
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002443 const Constant *C = Pivot->Low;
Craig Topperc0196b12014-04-14 00:51:57 +00002444 MachineBasicBlock *FalseBB = nullptr, *TrueBB = nullptr;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002445
Dan Gohman575fad32008-09-03 16:12:24 +00002446 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00002447 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohman575fad32008-09-03 16:12:24 +00002448 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00002449 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohman575fad32008-09-03 16:12:24 +00002450 // Pivot's Value, then we can branch directly to the LHS's Target,
2451 // rather than creating a leaf node for it.
2452 if ((LHSR.second - LHSR.first) == 1 &&
2453 LHSR.first->High == CR.GE &&
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002454 cast<ConstantInt>(C)->getValue() ==
2455 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohman575fad32008-09-03 16:12:24 +00002456 TrueBB = LHSR.first->BB;
2457 } else {
2458 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2459 CurMF->insert(BBI, TrueBB);
2460 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Dan Gohmane6db8ca2009-04-09 02:33:36 +00002461
2462 // Put SV in a virtual register to make it available from the new blocks.
2463 ExportFromCurrentBlock(SV);
Dan Gohman575fad32008-09-03 16:12:24 +00002464 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002465
Dan Gohman575fad32008-09-03 16:12:24 +00002466 // Similar to the optimization above, if the Value being switched on is
2467 // known to be less than the Constant CR.LT, and the current Case Value
2468 // is CR.LT - 1, then we can branch directly to the target block for
2469 // the current Case Value, rather than emitting a RHS leaf node for it.
2470 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002471 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2472 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohman575fad32008-09-03 16:12:24 +00002473 FalseBB = RHSR.first->BB;
2474 } else {
2475 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2476 CurMF->insert(BBI, FalseBB);
2477 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Dan Gohmane6db8ca2009-04-09 02:33:36 +00002478
2479 // Put SV in a virtual register to make it available from the new blocks.
2480 ExportFromCurrentBlock(SV);
Dan Gohman575fad32008-09-03 16:12:24 +00002481 }
2482
2483 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00002484 // the LHS node if the value being switched on SV is less than C.
Dan Gohman575fad32008-09-03 16:12:24 +00002485 // Otherwise, branch to LHS.
Craig Topperc0196b12014-04-14 00:51:57 +00002486 CaseBlock CB(ISD::SETLT, SV, C, nullptr, TrueBB, FalseBB, CR.CaseBB);
Dan Gohman575fad32008-09-03 16:12:24 +00002487
Dan Gohman7c0303a2010-04-19 22:41:47 +00002488 if (CR.CaseBB == SwitchBB)
2489 visitSwitchCase(CB, SwitchBB);
Dan Gohman575fad32008-09-03 16:12:24 +00002490 else
2491 SwitchCases.push_back(CB);
2492
2493 return true;
2494}
2495
2496/// handleBitTestsSwitchCase - if current case range has few destination and
2497/// range span less, than machine word bitwidth, encode case range into series
2498/// of masks and emit bit tests with these masks.
Dan Gohman1a6c47f2009-11-23 18:04:58 +00002499bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2500 CaseRecVector& WorkList,
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002501 const Value* SV,
Dan Gohman7c0303a2010-04-19 22:41:47 +00002502 MachineBasicBlock* Default,
Stephen Lin6d715e82013-07-06 21:44:25 +00002503 MachineBasicBlock* SwitchBB) {
Eric Christopher58a24612014-10-08 09:50:54 +00002504 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2505 EVT PTy = TLI.getPointerTy();
Owen Andersonc30530d2009-08-10 18:56:59 +00002506 unsigned IntPtrBits = PTy.getSizeInBits();
Dan Gohman575fad32008-09-03 16:12:24 +00002507
2508 Case& FrontCase = *CR.Range.first;
2509 Case& BackCase = *(CR.Range.second-1);
2510
2511 // Get the MachineFunction which holds the current MBB. This is used when
2512 // inserting any additional MBBs necessary to represent the switch.
Dan Gohmane8c913e2009-08-15 02:06:22 +00002513 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohman575fad32008-09-03 16:12:24 +00002514
Anton Korobeynikovc94dbf52009-05-08 18:51:34 +00002515 // If target does not have legal shift left, do not emit bit tests at all.
Eric Christopher58a24612014-10-08 09:50:54 +00002516 if (!TLI.isOperationLegal(ISD::SHL, PTy))
Anton Korobeynikovc94dbf52009-05-08 18:51:34 +00002517 return false;
2518
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002519 size_t numCmps = 0;
Hans Wennborg6dfb0412014-11-29 21:24:12 +00002520 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002521 // Single case counts one, case range - two.
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002522 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohman575fad32008-09-03 16:12:24 +00002523 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002524
Dan Gohman575fad32008-09-03 16:12:24 +00002525 // Count unique destinations
2526 SmallSet<MachineBasicBlock*, 4> Dests;
Hans Wennborg6dfb0412014-11-29 21:24:12 +00002527 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002528 Dests.insert(I->BB);
2529 if (Dests.size() > 3)
2530 // Don't bother the code below, if there are too much unique destinations
2531 return false;
2532 }
David Greene5730f202010-01-05 01:24:57 +00002533 DEBUG(dbgs() << "Total number of unique destinations: "
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00002534 << Dests.size() << '\n'
2535 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002536
Dan Gohman575fad32008-09-03 16:12:24 +00002537 // Compute span of values.
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002538 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2539 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002540 APInt cmpRange = maxValue - minValue;
2541
David Greene5730f202010-01-05 01:24:57 +00002542 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002543 << "Low bound: " << minValue << '\n'
2544 << "High bound: " << maxValue << '\n');
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002545
Dan Gohman4ce1fb12010-04-08 23:03:40 +00002546 if (cmpRange.uge(IntPtrBits) ||
Dan Gohman575fad32008-09-03 16:12:24 +00002547 (!(Dests.size() == 1 && numCmps >= 3) &&
2548 !(Dests.size() == 2 && numCmps >= 5) &&
2549 !(Dests.size() >= 3 && numCmps >= 6)))
2550 return false;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002551
David Greene5730f202010-01-05 01:24:57 +00002552 DEBUG(dbgs() << "Emitting bit tests\n");
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002553 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2554
Dan Gohman575fad32008-09-03 16:12:24 +00002555 // Optimize the case where all the case values fit in a
2556 // word without having to subtract minValue. In this case,
2557 // we can optimize away the subtraction.
Bob Wilsone4077362013-09-09 19:14:35 +00002558 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002559 cmpRange = maxValue;
Dan Gohman575fad32008-09-03 16:12:24 +00002560 } else {
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002561 lowBound = minValue;
Dan Gohman575fad32008-09-03 16:12:24 +00002562 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002563
Dan Gohman575fad32008-09-03 16:12:24 +00002564 CaseBitsVector CasesBits;
2565 unsigned i, count = 0;
2566
2567 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2568 MachineBasicBlock* Dest = I->BB;
2569 for (i = 0; i < count; ++i)
2570 if (Dest == CasesBits[i].BB)
2571 break;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002572
Dan Gohman575fad32008-09-03 16:12:24 +00002573 if (i == count) {
2574 assert((count < 3) && "Too much destinations to test!");
Manman Rencf104462012-08-24 18:14:27 +00002575 CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
Dan Gohman575fad32008-09-03 16:12:24 +00002576 count++;
2577 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002578
2579 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2580 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2581
2582 uint64_t lo = (lowValue - lowBound).getZExtValue();
2583 uint64_t hi = (highValue - lowBound).getZExtValue();
Manman Rencf104462012-08-24 18:14:27 +00002584 CasesBits[i].ExtraWeight += I->ExtraWeight;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002585
Dan Gohman575fad32008-09-03 16:12:24 +00002586 for (uint64_t j = lo; j <= hi; j++) {
2587 CasesBits[i].Mask |= 1ULL << j;
2588 CasesBits[i].Bits++;
2589 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002590
Dan Gohman575fad32008-09-03 16:12:24 +00002591 }
2592 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002593
Dan Gohman575fad32008-09-03 16:12:24 +00002594 BitTestInfo BTC;
2595
2596 // Figure out which block is immediately after the current one.
2597 MachineFunction::iterator BBI = CR.CaseBB;
2598 ++BBI;
2599
2600 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2601
David Greene5730f202010-01-05 01:24:57 +00002602 DEBUG(dbgs() << "Cases:\n");
Dan Gohman575fad32008-09-03 16:12:24 +00002603 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
David Greene5730f202010-01-05 01:24:57 +00002604 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
Anton Korobeynikovf4a66e82008-12-23 22:26:18 +00002605 << ", Bits: " << CasesBits[i].Bits
2606 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohman575fad32008-09-03 16:12:24 +00002607
2608 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2609 CurMF->insert(BBI, CaseBB);
2610 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2611 CaseBB,
Manman Rencf104462012-08-24 18:14:27 +00002612 CasesBits[i].BB, CasesBits[i].ExtraWeight));
Dan Gohmane6db8ca2009-04-09 02:33:36 +00002613
2614 // Put SV in a virtual register to make it available from the new blocks.
2615 ExportFromCurrentBlock(SV);
Dan Gohman575fad32008-09-03 16:12:24 +00002616 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002617
2618 BitTestBlock BTB(lowBound, cmpRange, SV,
Evan Chengac730dd2011-01-06 01:02:44 +00002619 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +00002620 CR.CaseBB, Default, std::move(BTC));
Dan Gohman575fad32008-09-03 16:12:24 +00002621
Dan Gohman7c0303a2010-04-19 22:41:47 +00002622 if (CR.CaseBB == SwitchBB)
2623 visitBitTestHeader(BTB, SwitchBB);
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002624
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +00002625 BitTestCases.push_back(std::move(BTB));
Dan Gohman575fad32008-09-03 16:12:24 +00002626
2627 return true;
2628}
2629
Dan Gohman575fad32008-09-03 16:12:24 +00002630/// Clusterify - Transform simple list of Cases into list of CaseRange's
Chad Rosierdf82a332014-10-13 19:46:39 +00002631void SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2632 const SwitchInst& SI) {
Manman Rencf104462012-08-24 18:14:27 +00002633 BranchProbabilityInfo *BPI = FuncInfo.BPI;
Hans Wennborg6dfb0412014-11-29 21:24:12 +00002634 // Start with "simple" cases.
2635 for (SwitchInst::ConstCaseIt i : SI.cases()) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002636 const BasicBlock *SuccBB = i.getCaseSuccessor();
Jakub Staszak0480a8f2011-07-29 22:25:21 +00002637 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
2638
Bob Wilsone4077362013-09-09 19:14:35 +00002639 uint32_t ExtraWeight =
2640 BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0;
2641
2642 Cases.push_back(Case(i.getCaseValue(), i.getCaseValue(),
2643 SMBB, ExtraWeight));
Dan Gohman575fad32008-09-03 16:12:24 +00002644 }
Bob Wilsone4077362013-09-09 19:14:35 +00002645 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Stephen Lincfe7f352013-07-08 00:37:03 +00002646
Bob Wilsone4077362013-09-09 19:14:35 +00002647 // Merge case into clusters
2648 if (Cases.size() >= 2)
2649 // Must recompute end() each iteration because it may be
2650 // invalidated by erase if we hold on to it
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002651 for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
Bob Wilsone4077362013-09-09 19:14:35 +00002652 J != Cases.end(); ) {
2653 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2654 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2655 MachineBasicBlock* nextBB = J->BB;
2656 MachineBasicBlock* currentBB = I->BB;
Stephen Lincfe7f352013-07-08 00:37:03 +00002657
Bob Wilsone4077362013-09-09 19:14:35 +00002658 // If the two neighboring cases go to the same destination, merge them
2659 // into a single case.
2660 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2661 I->High = J->High;
2662 I->ExtraWeight += J->ExtraWeight;
2663 J = Cases.erase(J);
2664 } else {
2665 I = J++;
2666 }
2667 }
Dan Gohman575fad32008-09-03 16:12:24 +00002668
Chad Rosierdf82a332014-10-13 19:46:39 +00002669 DEBUG({
2670 size_t numCmps = 0;
2671 for (auto &I : Cases)
2672 // A range counts double, since it requires two compares.
2673 numCmps += I.Low != I.High ? 2 : 1;
Dan Gohman575fad32008-09-03 16:12:24 +00002674
Chad Rosierdf82a332014-10-13 19:46:39 +00002675 dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2676 << ". Total compares: " << numCmps << '\n';
2677 });
Dan Gohman575fad32008-09-03 16:12:24 +00002678}
2679
Jakob Stoklund Olesen665aa6e2010-09-30 19:44:31 +00002680void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2681 MachineBasicBlock *Last) {
2682 // Update JTCases.
2683 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2684 if (JTCases[i].first.HeaderBB == First)
2685 JTCases[i].first.HeaderBB = Last;
2686
2687 // Update BitTestCases.
2688 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2689 if (BitTestCases[i].Parent == First)
2690 BitTestCases[i].Parent = Last;
2691}
2692
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002693void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +00002694 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
Dan Gohman7c0303a2010-04-19 22:41:47 +00002695
Dan Gohman575fad32008-09-03 16:12:24 +00002696 // Figure out which block is immediately after the current one.
Craig Topperc0196b12014-04-14 00:51:57 +00002697 MachineBasicBlock *NextBlock = nullptr;
Hans Wennborg6c42d1a2014-11-29 21:17:05 +00002698 if (SwitchMBB + 1 != FuncInfo.MF->end())
2699 NextBlock = SwitchMBB + 1;
2700
Dan Gohman575fad32008-09-03 16:12:24 +00002701 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2702
Hans Wennborg5bef5b52014-12-01 17:36:43 +00002703 // If there is only the default destination, branch to it if it is not the
2704 // next basic block. Otherwise, just fall through.
2705 if (!SI.getNumCases()) {
Dan Gohman575fad32008-09-03 16:12:24 +00002706 // Update machine-CFG edges.
Hans Wennborg6dfb0412014-11-29 21:24:12 +00002707 SwitchMBB->addSuccessor(Default);
Dan Gohman575fad32008-09-03 16:12:24 +00002708
2709 // If this is not a fall-through branch, emit the branch.
Hans Wennborg5bef5b52014-12-01 17:36:43 +00002710 if (Default != NextBlock)
2711 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2712 MVT::Other, getControlRoot(),
2713 DAG.getBasicBlock(Default)));
2714
Dan Gohman575fad32008-09-03 16:12:24 +00002715 return;
2716 }
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002717
Hans Wennborg5bef5b52014-12-01 17:36:43 +00002718 // If there are any non-default case statements, create a vector of Cases
2719 // representing each one, and sort the vector so that we can efficiently
2720 // create a binary search tree from them.
2721 CaseVector Cases;
2722 Clusterify(Cases, SI);
2723
2724 // Get the Value to be switched on and default basic blocks, which will be
2725 // inserted into CaseBlock records, representing basic blocks in the binary
2726 // search tree.
Eli Friedman95031ed2011-09-29 20:21:17 +00002727 const Value *SV = SI.getCondition();
Dan Gohman575fad32008-09-03 16:12:24 +00002728
2729 // Push the initial CaseRec onto the worklist
2730 CaseRecVector WorkList;
Craig Topperc0196b12014-04-14 00:51:57 +00002731 WorkList.push_back(CaseRec(SwitchMBB,nullptr,nullptr,
Dan Gohman7c0303a2010-04-19 22:41:47 +00002732 CaseRange(Cases.begin(),Cases.end())));
Dan Gohman575fad32008-09-03 16:12:24 +00002733
2734 while (!WorkList.empty()) {
2735 // Grab a record representing a case range to process off the worklist
2736 CaseRec CR = WorkList.back();
2737 WorkList.pop_back();
2738
Dan Gohman7c0303a2010-04-19 22:41:47 +00002739 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohman575fad32008-09-03 16:12:24 +00002740 continue;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002741
Dan Gohman575fad32008-09-03 16:12:24 +00002742 // If the range has few cases (two or less) emit a series of specific
2743 // tests.
Dan Gohman7c0303a2010-04-19 22:41:47 +00002744 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohman575fad32008-09-03 16:12:24 +00002745 continue;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002746
Sebastian Popedb31fa2012-09-25 20:35:36 +00002747 // If the switch has more than N blocks, and is at least 40% dense, and the
Anton Korobeynikovd305d002008-12-23 22:26:01 +00002748 // target supports indirect branches, then emit a jump table rather than
Dan Gohman575fad32008-09-03 16:12:24 +00002749 // lowering the switch to a binary tree of conditional branches.
Sebastian Popedb31fa2012-09-25 20:35:36 +00002750 // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
Dan Gohman7c0303a2010-04-19 22:41:47 +00002751 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohman575fad32008-09-03 16:12:24 +00002752 continue;
Anton Korobeynikov6f219132008-12-23 22:25:27 +00002753
Dan Gohman575fad32008-09-03 16:12:24 +00002754 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2755 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
Chad Rosierdf82a332014-10-13 19:46:39 +00002756 handleBTSplitSwitchCase(CR, WorkList, SV, SwitchMBB);
Dan Gohman575fad32008-09-03 16:12:24 +00002757 }
2758}
2759
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002760void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
Dan Gohmand7b5ce32010-07-10 09:00:22 +00002761 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
Dan Gohman7c0303a2010-04-19 22:41:47 +00002762
Jakob Stoklund Olesen896428d2010-02-11 00:34:18 +00002763 // Update machine-CFG edges with unique successors.
Nadav Rotem33e034a2012-10-23 21:05:33 +00002764 SmallSet<BasicBlock*, 32> Done;
2765 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2766 BasicBlock *BB = I.getSuccessor(i);
David Blaikie70573dc2014-11-19 07:49:26 +00002767 bool Inserted = Done.insert(BB).second;
Nadav Rotem33e034a2012-10-23 21:05:33 +00002768 if (!Inserted)
2769 continue;
2770
2771 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
Jakub Staszak12a43bd2011-06-16 20:22:37 +00002772 addSuccessorWithWeight(IndirectBrMBB, Succ);
2773 }
Dan Gohmana5e078b2009-10-27 22:10:34 +00002774
Andrew Trickef9de2a2013-05-25 02:42:55 +00002775 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00002776 MVT::Other, getControlRoot(),
2777 getValue(I.getAddress())));
Bill Wendling443d0722009-12-21 22:30:11 +00002778}
Dan Gohman575fad32008-09-03 16:12:24 +00002779
Yaron Kerend7ba46b2014-04-19 13:47:43 +00002780void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2781 if (DAG.getTarget().Options.TrapUnreachable)
2782 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2783}
2784
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002785void SelectionDAGBuilder::visitFSub(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002786 // -0.0 - X --> fneg
Chris Lattner229907c2011-07-18 04:54:35 +00002787 Type *Ty = I.getType();
Chris Lattner69229312011-02-15 00:14:00 +00002788 if (isa<Constant>(I.getOperand(0)) &&
2789 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2790 SDValue Op2 = getValue(I.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002791 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
Chris Lattner69229312011-02-15 00:14:00 +00002792 Op2.getValueType(), Op2));
2793 return;
Dan Gohman575fad32008-09-03 16:12:24 +00002794 }
Bill Wendling443d0722009-12-21 22:30:11 +00002795
Dan Gohmana5b96452009-06-04 22:49:04 +00002796 visitBinary(I, ISD::FSUB);
Dan Gohman575fad32008-09-03 16:12:24 +00002797}
2798
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002799void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
Dan Gohman575fad32008-09-03 16:12:24 +00002800 SDValue Op1 = getValue(I.getOperand(0));
2801 SDValue Op2 = getValue(I.getOperand(1));
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00002802
2803 bool nuw = false;
2804 bool nsw = false;
2805 bool exact = false;
2806 if (const OverflowingBinaryOperator *OFBinOp =
2807 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2808 nuw = OFBinOp->hasNoUnsignedWrap();
2809 nsw = OFBinOp->hasNoSignedWrap();
2810 }
2811 if (const PossiblyExactOperator *ExactOp =
2812 dyn_cast<const PossiblyExactOperator>(&I))
2813 exact = ExactOp->isExact();
2814
2815 SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2816 Op1, Op2, nuw, nsw, exact);
2817 setValue(&I, BinNodeValue);
Dan Gohman575fad32008-09-03 16:12:24 +00002818}
2819
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002820void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
Dan Gohman575fad32008-09-03 16:12:24 +00002821 SDValue Op1 = getValue(I.getOperand(0));
2822 SDValue Op2 = getValue(I.getOperand(1));
Owen Andersonb2c80da2011-02-25 21:41:48 +00002823
Eric Christopher58a24612014-10-08 09:50:54 +00002824 EVT ShiftTy =
2825 DAG.getTargetLoweringInfo().getShiftAmountTy(Op2.getValueType());
Owen Andersonb2c80da2011-02-25 21:41:48 +00002826
Chris Lattner2a720d92011-02-13 09:02:52 +00002827 // Coerce the shift amount to the right type if we can.
2828 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
Chris Lattnerd5f0b112011-02-13 09:10:56 +00002829 unsigned ShiftSize = ShiftTy.getSizeInBits();
2830 unsigned Op2Size = Op2.getValueType().getSizeInBits();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002831 SDLoc DL = getCurSDLoc();
Owen Andersonb2c80da2011-02-25 21:41:48 +00002832
Dan Gohman0e8d1992009-04-09 03:51:29 +00002833 // If the operand is smaller than the shift count type, promote it.
Chris Lattner2a720d92011-02-13 09:02:52 +00002834 if (ShiftSize > Op2Size)
2835 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002836
Dan Gohman0e8d1992009-04-09 03:51:29 +00002837 // If the operand is larger than the shift count type but the shift
2838 // count type has enough bits to represent any shift value, truncate
2839 // it now. This is a common case and it exposes the truncate to
2840 // optimization early.
Chris Lattner2a720d92011-02-13 09:02:52 +00002841 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2842 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2843 // Otherwise we'll need to temporarily settle for some other convenient
Chris Lattnere95d1952011-02-13 19:09:16 +00002844 // type. Type legalization will make adjustments once the shiftee is split.
Chris Lattner2a720d92011-02-13 09:02:52 +00002845 else
Chris Lattnere95d1952011-02-13 19:09:16 +00002846 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
Dan Gohman575fad32008-09-03 16:12:24 +00002847 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00002848
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00002849 bool nuw = false;
2850 bool nsw = false;
2851 bool exact = false;
2852
2853 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2854
2855 if (const OverflowingBinaryOperator *OFBinOp =
2856 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2857 nuw = OFBinOp->hasNoUnsignedWrap();
2858 nsw = OFBinOp->hasNoSignedWrap();
2859 }
2860 if (const PossiblyExactOperator *ExactOp =
2861 dyn_cast<const PossiblyExactOperator>(&I))
2862 exact = ExactOp->isExact();
2863 }
2864
2865 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2866 nuw, nsw, exact);
2867 setValue(&I, Res);
Dan Gohman575fad32008-09-03 16:12:24 +00002868}
2869
Benjamin Kramer9960a252011-07-08 10:31:30 +00002870void SelectionDAGBuilder::visitSDiv(const User &I) {
Benjamin Kramer9960a252011-07-08 10:31:30 +00002871 SDValue Op1 = getValue(I.getOperand(0));
2872 SDValue Op2 = getValue(I.getOperand(1));
2873
2874 // Turn exact SDivs into multiplications.
2875 // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2876 // exact bit.
Benjamin Kramer2bb8b262011-07-08 12:08:24 +00002877 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2878 !isa<ConstantSDNode>(Op1) &&
Benjamin Kramer9960a252011-07-08 10:31:30 +00002879 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
Eric Christopher58a24612014-10-08 09:50:54 +00002880 setValue(&I, DAG.getTargetLoweringInfo()
2881 .BuildExactSDIV(Op1, Op2, getCurSDLoc(), DAG));
Benjamin Kramer9960a252011-07-08 10:31:30 +00002882 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00002883 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
Benjamin Kramer9960a252011-07-08 10:31:30 +00002884 Op1, Op2));
2885}
2886
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002887void SelectionDAGBuilder::visitICmp(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002888 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002889 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
Dan Gohman575fad32008-09-03 16:12:24 +00002890 predicate = IC->getPredicate();
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002891 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
Dan Gohman575fad32008-09-03 16:12:24 +00002892 predicate = ICmpInst::Predicate(IC->getPredicate());
2893 SDValue Op1 = getValue(I.getOperand(0));
2894 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman293abcc2008-10-17 18:18:45 +00002895 ISD::CondCode Opcode = getICmpCondCode(predicate);
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00002896
Eric Christopher58a24612014-10-08 09:50:54 +00002897 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002898 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
Dan Gohman575fad32008-09-03 16:12:24 +00002899}
2900
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002901void SelectionDAGBuilder::visitFCmp(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002902 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002903 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
Dan Gohman575fad32008-09-03 16:12:24 +00002904 predicate = FC->getPredicate();
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002905 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
Dan Gohman575fad32008-09-03 16:12:24 +00002906 predicate = FCmpInst::Predicate(FC->getPredicate());
2907 SDValue Op1 = getValue(I.getOperand(0));
2908 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman293abcc2008-10-17 18:18:45 +00002909 ISD::CondCode Condition = getFCmpCondCode(predicate);
Nick Lewycky50f02cb2011-12-02 22:16:29 +00002910 if (TM.Options.NoNaNsFPMath)
2911 Condition = getFCmpCodeWithoutNaN(Condition);
Eric Christopher58a24612014-10-08 09:50:54 +00002912 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002913 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
Dan Gohman575fad32008-09-03 16:12:24 +00002914}
2915
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002916void SelectionDAGBuilder::visitSelect(const User &I) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002917 SmallVector<EVT, 4> ValueVTs;
Eric Christopher58a24612014-10-08 09:50:54 +00002918 ComputeValueVTs(DAG.getTargetLoweringInfo(), I.getType(), ValueVTs);
Dan Gohman8b44b882008-10-21 20:00:42 +00002919 unsigned NumValues = ValueVTs.size();
Bill Wendling443d0722009-12-21 22:30:11 +00002920 if (NumValues == 0) return;
Dan Gohman8b44b882008-10-21 20:00:42 +00002921
Bill Wendling443d0722009-12-21 22:30:11 +00002922 SmallVector<SDValue, 4> Values(NumValues);
2923 SDValue Cond = getValue(I.getOperand(0));
2924 SDValue TrueVal = getValue(I.getOperand(1));
2925 SDValue FalseVal = getValue(I.getOperand(2));
Duncan Sandsf2641e12011-09-06 19:07:46 +00002926 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2927 ISD::VSELECT : ISD::SELECT;
Dan Gohman8b44b882008-10-21 20:00:42 +00002928
Bill Wendling954cb182010-01-28 21:51:40 +00002929 for (unsigned i = 0; i != NumValues; ++i)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002930 Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
Duncan Sandsf2641e12011-09-06 19:07:46 +00002931 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
Chris Lattner53ebf8a2010-03-12 07:15:36 +00002932 Cond,
Bill Wendling443d0722009-12-21 22:30:11 +00002933 SDValue(TrueVal.getNode(),
2934 TrueVal.getResNo() + i),
2935 SDValue(FalseVal.getNode(),
2936 FalseVal.getResNo() + i));
2937
Andrew Trickef9de2a2013-05-25 02:42:55 +00002938 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00002939 DAG.getVTList(ValueVTs), Values));
Bill Wendling443d0722009-12-21 22:30:11 +00002940}
Dan Gohman575fad32008-09-03 16:12:24 +00002941
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002942void SelectionDAGBuilder::visitTrunc(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002943 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2944 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00002945 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002946 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00002947}
2948
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002949void SelectionDAGBuilder::visitZExt(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002950 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2951 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2952 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00002953 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002954 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00002955}
2956
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002957void SelectionDAGBuilder::visitSExt(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002958 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2959 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2960 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00002961 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002962 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00002963}
2964
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002965void SelectionDAGBuilder::visitFPTrunc(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002966 // FPTrunc is never a no-op cast, no need to check
2967 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00002968 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2969 EVT DestVT = TLI.getValueType(I.getType());
2970 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(), DestVT, N,
2971 DAG.getTargetConstant(0, TLI.getPointerTy())));
Dan Gohman575fad32008-09-03 16:12:24 +00002972}
2973
Stephen Lin6d715e82013-07-06 21:44:25 +00002974void SelectionDAGBuilder::visitFPExt(const User &I) {
Hal Finkelbab66782011-10-18 03:51:57 +00002975 // FPExt is never a no-op cast, no need to check
Dan Gohman575fad32008-09-03 16:12:24 +00002976 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00002977 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002978 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00002979}
2980
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002981void SelectionDAGBuilder::visitFPToUI(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002982 // FPToUI is never a no-op cast, no need to check
2983 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00002984 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002985 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00002986}
2987
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002988void SelectionDAGBuilder::visitFPToSI(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002989 // FPToSI is never a no-op cast, no need to check
2990 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00002991 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002992 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00002993}
2994
Dan Gohmanbcaf6812010-04-15 01:51:59 +00002995void SelectionDAGBuilder::visitUIToFP(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00002996 // UIToFP is never a no-op cast, no need to check
2997 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00002998 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002999 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00003000}
3001
Stephen Lin6d715e82013-07-06 21:44:25 +00003002void SelectionDAGBuilder::visitSIToFP(const User &I) {
Bill Wendling6c87bfc2008-10-19 20:34:04 +00003003 // SIToFP is never a no-op cast, no need to check
Dan Gohman575fad32008-09-03 16:12:24 +00003004 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00003005 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003006 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
Dan Gohman575fad32008-09-03 16:12:24 +00003007}
3008
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003009void SelectionDAGBuilder::visitPtrToInt(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003010 // What to do depends on the size of the integer and the size of the pointer.
3011 // We can either truncate, zero extend, or no-op, accordingly.
3012 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00003013 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003014 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
Dan Gohman575fad32008-09-03 16:12:24 +00003015}
3016
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003017void SelectionDAGBuilder::visitIntToPtr(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003018 // What to do depends on the size of the integer and the size of the pointer.
3019 // We can either truncate, zero extend, or no-op, accordingly.
3020 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00003021 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003022 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
Dan Gohman575fad32008-09-03 16:12:24 +00003023}
3024
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003025void SelectionDAGBuilder::visitBitCast(const User &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003026 SDValue N = getValue(I.getOperand(0));
Eric Christopher58a24612014-10-08 09:50:54 +00003027 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
Dan Gohman575fad32008-09-03 16:12:24 +00003028
Bill Wendling443d0722009-12-21 22:30:11 +00003029 // BitCast assures us that source and destination are the same size so this is
Wesley Peck527da1b2010-11-23 03:31:01 +00003030 // either a BITCAST or a no-op.
Bill Wendling954cb182010-01-28 21:51:40 +00003031 if (DestVT != N.getValueType())
Andrew Trickef9de2a2013-05-25 02:42:55 +00003032 setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
Bill Wendling954cb182010-01-28 21:51:40 +00003033 DestVT, N)); // convert types.
Juergen Ributzka2b97f9b2014-02-13 04:19:26 +00003034 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3035 // might fold any kind of constant expression to an integer constant and that
3036 // is not what we are looking for. Only regcognize a bitcast of a genuine
3037 // constant integer as an opaque constant.
3038 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3039 setValue(&I, DAG.getConstant(C->getValue(), DestVT, /*isTarget=*/false,
3040 /*isOpaque*/true));
Bill Wendling954cb182010-01-28 21:51:40 +00003041 else
Bill Wendling443d0722009-12-21 22:30:11 +00003042 setValue(&I, N); // noop cast.
Dan Gohman575fad32008-09-03 16:12:24 +00003043}
3044
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003045void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3046 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3047 const Value *SV = I.getOperand(0);
3048 SDValue N = getValue(SV);
Eric Christopher58a24612014-10-08 09:50:54 +00003049 EVT DestVT = TLI.getValueType(I.getType());
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003050
3051 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3052 unsigned DestAS = I.getType()->getPointerAddressSpace();
3053
3054 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3055 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3056
3057 setValue(&I, N);
3058}
3059
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003060void SelectionDAGBuilder::visitInsertElement(const User &I) {
Tom Stellardd42c5942013-08-05 22:22:01 +00003061 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman575fad32008-09-03 16:12:24 +00003062 SDValue InVec = getValue(I.getOperand(0));
3063 SDValue InVal = getValue(I.getOperand(1));
Tom Stellardd42c5942013-08-05 22:22:01 +00003064 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
3065 getCurSDLoc(), TLI.getVectorIdxTy());
Eric Christopher58a24612014-10-08 09:50:54 +00003066 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3067 TLI.getValueType(I.getType()), InVec, InVal, InIdx));
Dan Gohman575fad32008-09-03 16:12:24 +00003068}
3069
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003070void SelectionDAGBuilder::visitExtractElement(const User &I) {
Tom Stellardd42c5942013-08-05 22:22:01 +00003071 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman575fad32008-09-03 16:12:24 +00003072 SDValue InVec = getValue(I.getOperand(0));
Tom Stellardd42c5942013-08-05 22:22:01 +00003073 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
3074 getCurSDLoc(), TLI.getVectorIdxTy());
Eric Christopher58a24612014-10-08 09:50:54 +00003075 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3076 TLI.getValueType(I.getType()), InVec, InIdx));
Dan Gohman575fad32008-09-03 16:12:24 +00003077}
3078
Craig Topperf726e152012-01-04 09:23:09 +00003079// Utility for visitShuffleVector - Return true if every element in Mask,
Benjamin Kramerbde91762012-06-02 10:20:22 +00003080// beginning from position Pos and ending in Pos+Size, falls within the
Craig Topperf726e152012-01-04 09:23:09 +00003081// specified sequential range [L, L+Pos). or is undef.
3082static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
Craig Topper3ef01cd2012-04-11 03:06:35 +00003083 unsigned Pos, unsigned Size, int Low) {
3084 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
Craig Topperf726e152012-01-04 09:23:09 +00003085 if (Mask[i] >= 0 && Mask[i] != Low)
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003086 return false;
Mon P Wang25f01062008-11-10 04:46:22 +00003087 return true;
3088}
3089
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003090void SelectionDAGBuilder::visitShuffleVector(const User &I) {
Mon P Wangc3113602008-11-21 04:25:21 +00003091 SDValue Src1 = getValue(I.getOperand(0));
3092 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohman575fad32008-09-03 16:12:24 +00003093
Chris Lattnercf129702012-01-26 02:51:13 +00003094 SmallVector<int, 8> Mask;
3095 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3096 unsigned MaskNumElts = Mask.size();
Bill Wendlinga3cd3502013-06-19 21:36:55 +00003097
Eric Christopher58a24612014-10-08 09:50:54 +00003098 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3099 EVT VT = TLI.getValueType(I.getType());
Owen Anderson53aa7a92009-08-10 22:56:29 +00003100 EVT SrcVT = Src1.getValueType();
Nate Begeman5f829d82009-04-29 05:20:52 +00003101 unsigned SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wang25f01062008-11-10 04:46:22 +00003102
Mon P Wang7a824742008-11-16 05:06:27 +00003103 if (SrcNumElts == MaskNumElts) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003104 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
Bill Wendling954cb182010-01-28 21:51:40 +00003105 &Mask[0]));
Mon P Wang25f01062008-11-10 04:46:22 +00003106 return;
3107 }
3108
3109 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wang7a824742008-11-16 05:06:27 +00003110 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
3111 // Mask is longer than the source vectors and is a multiple of the source
3112 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wangc3113602008-11-21 04:25:21 +00003113 // lengths match.
Craig Topperf726e152012-01-04 09:23:09 +00003114 if (SrcNumElts*2 == MaskNumElts) {
3115 // First check for Src1 in low and Src2 in high
3116 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
3117 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
3118 // The shuffle is concatenating two vectors together.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003119 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
Craig Topperf726e152012-01-04 09:23:09 +00003120 VT, Src1, Src2));
3121 return;
3122 }
3123 // Then check for Src2 in low and Src1 in high
3124 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
3125 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
3126 // The shuffle is concatenating two vectors together.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003127 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
Craig Topperf726e152012-01-04 09:23:09 +00003128 VT, Src2, Src1));
3129 return;
3130 }
Mon P Wang25f01062008-11-10 04:46:22 +00003131 }
3132
Mon P Wang7a824742008-11-16 05:06:27 +00003133 // Pad both vectors with undefs to make them the same length as the mask.
3134 unsigned NumConcat = MaskNumElts / SrcNumElts;
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003135 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
3136 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
Dale Johannesen84935752009-02-06 23:05:02 +00003137 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wang25f01062008-11-10 04:46:22 +00003138
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003139 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3140 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
Mon P Wangc3113602008-11-21 04:25:21 +00003141 MOps1[0] = Src1;
3142 MOps2[0] = Src2;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00003143
3144 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
Craig Topper48d114b2014-04-26 18:35:24 +00003145 getCurSDLoc(), VT, MOps1);
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003146 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
Craig Topper48d114b2014-04-26 18:35:24 +00003147 getCurSDLoc(), VT, MOps2);
Mon P Wangc3113602008-11-21 04:25:21 +00003148
Mon P Wang25f01062008-11-10 04:46:22 +00003149 // Readjust mask for new input vector length.
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003150 SmallVector<int, 8> MappedOps;
Nate Begeman5f829d82009-04-29 05:20:52 +00003151 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003152 int Idx = Mask[i];
Craig Topper3ef01cd2012-04-11 03:06:35 +00003153 if (Idx >= (int)SrcNumElts)
3154 Idx -= SrcNumElts - MaskNumElts;
3155 MappedOps.push_back(Idx);
Mon P Wang25f01062008-11-10 04:46:22 +00003156 }
Bill Wendlingfff99f02009-12-21 22:42:14 +00003157
Andrew Trickef9de2a2013-05-25 02:42:55 +00003158 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
Bill Wendling954cb182010-01-28 21:51:40 +00003159 &MappedOps[0]));
Mon P Wang25f01062008-11-10 04:46:22 +00003160 return;
3161 }
3162
Mon P Wang7a824742008-11-16 05:06:27 +00003163 if (SrcNumElts > MaskNumElts) {
Mon P Wang7a824742008-11-16 05:06:27 +00003164 // Analyze the access pattern of the vector to see if we can extract
3165 // two subvectors and do the shuffle. The analysis is done by calculating
3166 // the range of elements the mask access on both vectors.
Craig Topper6148fe62012-04-08 23:15:04 +00003167 int MinRange[2] = { static_cast<int>(SrcNumElts),
3168 static_cast<int>(SrcNumElts)};
Mon P Wang7a824742008-11-16 05:06:27 +00003169 int MaxRange[2] = {-1, -1};
3170
Nate Begeman5f829d82009-04-29 05:20:52 +00003171 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003172 int Idx = Mask[i];
Craig Topper6148fe62012-04-08 23:15:04 +00003173 unsigned Input = 0;
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003174 if (Idx < 0)
3175 continue;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00003176
Nate Begeman5f829d82009-04-29 05:20:52 +00003177 if (Idx >= (int)SrcNumElts) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003178 Input = 1;
3179 Idx -= SrcNumElts;
Mon P Wang25f01062008-11-10 04:46:22 +00003180 }
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003181 if (Idx > MaxRange[Input])
3182 MaxRange[Input] = Idx;
3183 if (Idx < MinRange[Input])
3184 MinRange[Input] = Idx;
Mon P Wang25f01062008-11-10 04:46:22 +00003185 }
Mon P Wang25f01062008-11-10 04:46:22 +00003186
Mon P Wang7a824742008-11-16 05:06:27 +00003187 // Check if the access is smaller than the vector size and can we find
3188 // a reasonable extract index.
Craig Topper6148fe62012-04-08 23:15:04 +00003189 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
3190 // Extract.
Mon P Wang7a824742008-11-16 05:06:27 +00003191 int StartIdx[2]; // StartIdx to extract from
Craig Topper6148fe62012-04-08 23:15:04 +00003192 for (unsigned Input = 0; Input < 2; ++Input) {
3193 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
Mon P Wang7a824742008-11-16 05:06:27 +00003194 RangeUse[Input] = 0; // Unused
3195 StartIdx[Input] = 0;
Craig Topperc8e2d912012-04-08 17:53:33 +00003196 continue;
Mon P Wangc3113602008-11-21 04:25:21 +00003197 }
Craig Topperc8e2d912012-04-08 17:53:33 +00003198
3199 // Find a good start index that is a multiple of the mask length. Then
3200 // see if the rest of the elements are in range.
3201 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
3202 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
3203 StartIdx[Input] + MaskNumElts <= SrcNumElts)
3204 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wang7a824742008-11-16 05:06:27 +00003205 }
3206
Bill Wendlingdff54ef2009-08-21 18:16:06 +00003207 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
Bill Wendling954cb182010-01-28 21:51:40 +00003208 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wang7a824742008-11-16 05:06:27 +00003209 return;
3210 }
Craig Topper6148fe62012-04-08 23:15:04 +00003211 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
Mon P Wang7a824742008-11-16 05:06:27 +00003212 // Extract appropriate subvector and generate a vector shuffle
Craig Topper6148fe62012-04-08 23:15:04 +00003213 for (unsigned Input = 0; Input < 2; ++Input) {
Bill Wendlingc6b47342009-12-21 23:47:40 +00003214 SDValue &Src = Input == 0 ? Src1 : Src2;
Bill Wendlingfff99f02009-12-21 22:42:14 +00003215 if (RangeUse[Input] == 0)
Dale Johannesen84935752009-02-06 23:05:02 +00003216 Src = DAG.getUNDEF(VT);
Bill Wendlingfff99f02009-12-21 22:42:14 +00003217 else
Eric Christopher58a24612014-10-08 09:50:54 +00003218 Src = DAG.getNode(
3219 ISD::EXTRACT_SUBVECTOR, getCurSDLoc(), VT, Src,
3220 DAG.getConstant(StartIdx[Input], TLI.getVectorIdxTy()));
Mon P Wang25f01062008-11-10 04:46:22 +00003221 }
Bill Wendlingfff99f02009-12-21 22:42:14 +00003222
Mon P Wang7a824742008-11-16 05:06:27 +00003223 // Calculate new mask.
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003224 SmallVector<int, 8> MappedOps;
Nate Begeman5f829d82009-04-29 05:20:52 +00003225 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00003226 int Idx = Mask[i];
Craig Topper3ef01cd2012-04-11 03:06:35 +00003227 if (Idx >= 0) {
3228 if (Idx < (int)SrcNumElts)
3229 Idx -= StartIdx[0];
3230 else
3231 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3232 }
3233 MappedOps.push_back(Idx);
Mon P Wang7a824742008-11-16 05:06:27 +00003234 }
Bill Wendlingfff99f02009-12-21 22:42:14 +00003235
Andrew Trickef9de2a2013-05-25 02:42:55 +00003236 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
Bill Wendling954cb182010-01-28 21:51:40 +00003237 &MappedOps[0]));
Mon P Wang7a824742008-11-16 05:06:27 +00003238 return;
Mon P Wang25f01062008-11-10 04:46:22 +00003239 }
3240 }
3241
Mon P Wang7a824742008-11-16 05:06:27 +00003242 // We can't use either concat vectors or extract subvectors so fall back to
3243 // replacing the shuffle with extract and build vector.
3244 // to insert and build vector.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003245 EVT EltVT = VT.getVectorElementType();
Eric Christopher58a24612014-10-08 09:50:54 +00003246 EVT IdxVT = TLI.getVectorIdxTy();
Mon P Wang25f01062008-11-10 04:46:22 +00003247 SmallVector<SDValue,8> Ops;
Nate Begeman5f829d82009-04-29 05:20:52 +00003248 for (unsigned i = 0; i != MaskNumElts; ++i) {
Craig Topper3ef01cd2012-04-11 03:06:35 +00003249 int Idx = Mask[i];
3250 SDValue Res;
3251
3252 if (Idx < 0) {
3253 Res = DAG.getUNDEF(EltVT);
Mon P Wang25f01062008-11-10 04:46:22 +00003254 } else {
Craig Topper3ef01cd2012-04-11 03:06:35 +00003255 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3256 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
Bill Wendlingfff99f02009-12-21 22:42:14 +00003257
Andrew Trickef9de2a2013-05-25 02:42:55 +00003258 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
Tom Stellardd42c5942013-08-05 22:22:01 +00003259 EltVT, Src, DAG.getConstant(Idx, IdxVT));
Mon P Wang25f01062008-11-10 04:46:22 +00003260 }
Craig Topper3ef01cd2012-04-11 03:06:35 +00003261
3262 Ops.push_back(Res);
Mon P Wang25f01062008-11-10 04:46:22 +00003263 }
Bill Wendlingfff99f02009-12-21 22:42:14 +00003264
Craig Topper48d114b2014-04-26 18:35:24 +00003265 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops));
Dan Gohman575fad32008-09-03 16:12:24 +00003266}
3267
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003268void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003269 const Value *Op0 = I.getOperand(0);
3270 const Value *Op1 = I.getOperand(1);
Chris Lattner229907c2011-07-18 04:54:35 +00003271 Type *AggTy = I.getType();
3272 Type *ValTy = Op1->getType();
Dan Gohman575fad32008-09-03 16:12:24 +00003273 bool IntoUndef = isa<UndefValue>(Op0);
3274 bool FromUndef = isa<UndefValue>(Op1);
3275
Jay Foad57aa6362011-07-13 10:26:04 +00003276 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
Dan Gohman575fad32008-09-03 16:12:24 +00003277
Eric Christopher58a24612014-10-08 09:50:54 +00003278 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Owen Anderson53aa7a92009-08-10 22:56:29 +00003279 SmallVector<EVT, 4> AggValueVTs;
Eric Christopher58a24612014-10-08 09:50:54 +00003280 ComputeValueVTs(TLI, AggTy, AggValueVTs);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003281 SmallVector<EVT, 4> ValValueVTs;
Eric Christopher58a24612014-10-08 09:50:54 +00003282 ComputeValueVTs(TLI, ValTy, ValValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00003283
3284 unsigned NumAggValues = AggValueVTs.size();
3285 unsigned NumValValues = ValValueVTs.size();
3286 SmallVector<SDValue, 4> Values(NumAggValues);
3287
Peter Collingbourne97572632014-09-20 00:10:47 +00003288 // Ignore an insertvalue that produces an empty object
3289 if (!NumAggValues) {
3290 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3291 return;
3292 }
3293
Dan Gohman575fad32008-09-03 16:12:24 +00003294 SDValue Agg = getValue(Op0);
Dan Gohman575fad32008-09-03 16:12:24 +00003295 unsigned i = 0;
3296 // Copy the beginning value(s) from the original aggregate.
3297 for (; i != LinearIndex; ++i)
Dale Johannesen84935752009-02-06 23:05:02 +00003298 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohman575fad32008-09-03 16:12:24 +00003299 SDValue(Agg.getNode(), Agg.getResNo() + i);
3300 // Copy values from the inserted value(s).
Rafael Espindolae53b7d12011-05-13 15:18:06 +00003301 if (NumValValues) {
3302 SDValue Val = getValue(Op1);
3303 for (; i != LinearIndex + NumValValues; ++i)
3304 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3305 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3306 }
Dan Gohman575fad32008-09-03 16:12:24 +00003307 // Copy remaining value(s) from the original aggregate.
3308 for (; i != NumAggValues; ++i)
Dale Johannesen84935752009-02-06 23:05:02 +00003309 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohman575fad32008-09-03 16:12:24 +00003310 SDValue(Agg.getNode(), Agg.getResNo() + i);
3311
Andrew Trickef9de2a2013-05-25 02:42:55 +00003312 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00003313 DAG.getVTList(AggValueVTs), Values));
Dan Gohman575fad32008-09-03 16:12:24 +00003314}
3315
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003316void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003317 const Value *Op0 = I.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00003318 Type *AggTy = Op0->getType();
3319 Type *ValTy = I.getType();
Dan Gohman575fad32008-09-03 16:12:24 +00003320 bool OutOfUndef = isa<UndefValue>(Op0);
3321
Jay Foad57aa6362011-07-13 10:26:04 +00003322 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
Dan Gohman575fad32008-09-03 16:12:24 +00003323
Eric Christopher58a24612014-10-08 09:50:54 +00003324 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Owen Anderson53aa7a92009-08-10 22:56:29 +00003325 SmallVector<EVT, 4> ValValueVTs;
Eric Christopher58a24612014-10-08 09:50:54 +00003326 ComputeValueVTs(TLI, ValTy, ValValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00003327
3328 unsigned NumValValues = ValValueVTs.size();
Rafael Espindolae53b7d12011-05-13 15:18:06 +00003329
3330 // Ignore a extractvalue that produces an empty object
3331 if (!NumValValues) {
3332 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3333 return;
3334 }
3335
Dan Gohman575fad32008-09-03 16:12:24 +00003336 SmallVector<SDValue, 4> Values(NumValValues);
3337
3338 SDValue Agg = getValue(Op0);
3339 // Copy out the selected value(s).
3340 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3341 Values[i - LinearIndex] =
Bill Wendling165b45d2008-11-20 07:24:30 +00003342 OutOfUndef ?
Dale Johannesen84935752009-02-06 23:05:02 +00003343 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendling165b45d2008-11-20 07:24:30 +00003344 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohman575fad32008-09-03 16:12:24 +00003345
Andrew Trickef9de2a2013-05-25 02:42:55 +00003346 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00003347 DAG.getVTList(ValValueVTs), Values));
Dan Gohman575fad32008-09-03 16:12:24 +00003348}
3349
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003350void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
Matt Arsenaultb7689122013-10-21 20:03:54 +00003351 Value *Op0 = I.getOperand(0);
Nadav Rotem1d666092012-02-28 14:13:19 +00003352 // Note that the pointer operand may be a vector of pointers. Take the scalar
3353 // element which holds a pointer.
Matt Arsenaultb7689122013-10-21 20:03:54 +00003354 Type *Ty = Op0->getType()->getScalarType();
3355 unsigned AS = Ty->getPointerAddressSpace();
3356 SDValue N = getValue(Op0);
Dan Gohman575fad32008-09-03 16:12:24 +00003357
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003358 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
Dan Gohman575fad32008-09-03 16:12:24 +00003359 OI != E; ++OI) {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003360 const Value *Idx = *OI;
Chris Lattner229907c2011-07-18 04:54:35 +00003361 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
Duncan Sandsb8d3caf2012-11-13 13:01:58 +00003362 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
Dan Gohman575fad32008-09-03 16:12:24 +00003363 if (Field) {
3364 // N = N + Offset
Rafael Espindola5f57f462014-02-21 18:34:28 +00003365 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003366 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
Duncan Sandsb8d3caf2012-11-13 13:01:58 +00003367 DAG.getConstant(Offset, N.getValueType()));
Dan Gohman575fad32008-09-03 16:12:24 +00003368 }
Bill Wendlinge79105b2009-12-21 23:10:19 +00003369
Dan Gohman575fad32008-09-03 16:12:24 +00003370 Ty = StTy->getElementType(Field);
3371 } else {
3372 Ty = cast<SequentialType>(Ty)->getElementType();
3373
3374 // If this is a constant subscript, handle it quickly.
Eric Christopher58a24612014-10-08 09:50:54 +00003375 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003376 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Dan Gohmanf1d83042010-06-18 14:22:04 +00003377 if (CI->isZero()) continue;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003378 uint64_t Offs =
Rafael Espindola5f57f462014-02-21 18:34:28 +00003379 DL->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Chengfe174df2009-02-09 21:01:06 +00003380 SDValue OffsVal;
Eric Christopher58a24612014-10-08 09:50:54 +00003381 EVT PTy = TLI.getPointerTy(AS);
Owen Andersonc30530d2009-08-10 18:56:59 +00003382 unsigned PtrBits = PTy.getSizeInBits();
Bill Wendlinge79105b2009-12-21 23:10:19 +00003383 if (PtrBits < 64)
Tom Stellardfd155822013-08-26 15:05:36 +00003384 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), PTy,
Owen Anderson9f944592009-08-11 20:47:22 +00003385 DAG.getConstant(Offs, MVT::i64));
Bill Wendlinge79105b2009-12-21 23:10:19 +00003386 else
Tom Stellardfd155822013-08-26 15:05:36 +00003387 OffsVal = DAG.getConstant(Offs, PTy);
Bill Wendlinge79105b2009-12-21 23:10:19 +00003388
Andrew Trickef9de2a2013-05-25 02:42:55 +00003389 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
Evan Cheng020588c2009-02-09 20:54:38 +00003390 OffsVal);
Dan Gohman575fad32008-09-03 16:12:24 +00003391 continue;
3392 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003393
Dan Gohman575fad32008-09-03 16:12:24 +00003394 // N = N + Idx * ElementSize;
Eric Christopher58a24612014-10-08 09:50:54 +00003395 APInt ElementSize =
3396 APInt(TLI.getPointerSizeInBits(AS), DL->getTypeAllocSize(Ty));
Dan Gohman575fad32008-09-03 16:12:24 +00003397 SDValue IdxN = getValue(Idx);
3398
3399 // If the index is smaller or larger than intptr_t, truncate or extend
3400 // it.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003401 IdxN = DAG.getSExtOrTrunc(IdxN, getCurSDLoc(), N.getValueType());
Dan Gohman575fad32008-09-03 16:12:24 +00003402
3403 // If this is a multiply by a power of two, turn it into a shl
3404 // immediately. This is a very common case.
3405 if (ElementSize != 1) {
Dan Gohman4ef112b2009-10-23 17:57:43 +00003406 if (ElementSize.isPowerOf2()) {
3407 unsigned Amt = ElementSize.logBase2();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003408 IdxN = DAG.getNode(ISD::SHL, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00003409 N.getValueType(), IdxN,
Nadav Rotem3924cb02011-12-05 06:29:09 +00003410 DAG.getConstant(Amt, IdxN.getValueType()));
Dan Gohman575fad32008-09-03 16:12:24 +00003411 } else {
Duncan Sandsb8d3caf2012-11-13 13:01:58 +00003412 SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003413 IdxN = DAG.getNode(ISD::MUL, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00003414 N.getValueType(), IdxN, Scale);
Dan Gohman575fad32008-09-03 16:12:24 +00003415 }
3416 }
3417
Andrew Trickef9de2a2013-05-25 02:42:55 +00003418 N = DAG.getNode(ISD::ADD, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00003419 N.getValueType(), N, IdxN);
Dan Gohman575fad32008-09-03 16:12:24 +00003420 }
3421 }
Bill Wendlinge79105b2009-12-21 23:10:19 +00003422
Dan Gohman575fad32008-09-03 16:12:24 +00003423 setValue(&I, N);
3424}
3425
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003426void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
Dan Gohman575fad32008-09-03 16:12:24 +00003427 // If this is a fixed sized alloca in the entry block of the function,
3428 // allocate it statically on the stack.
3429 if (FuncInfo.StaticAllocaMap.count(&I))
3430 return; // getValue will auto-populate this.
3431
Chris Lattner229907c2011-07-18 04:54:35 +00003432 Type *Ty = I.getAllocatedType();
Eric Christopher58a24612014-10-08 09:50:54 +00003433 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3434 uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
Dan Gohman575fad32008-09-03 16:12:24 +00003435 unsigned Align =
Eric Christopher58a24612014-10-08 09:50:54 +00003436 std::max((unsigned)TLI.getDataLayout()->getPrefTypeAlignment(Ty),
3437 I.getAlignment());
Dan Gohman575fad32008-09-03 16:12:24 +00003438
3439 SDValue AllocSize = getValue(I.getArraySize());
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00003440
Eric Christopher58a24612014-10-08 09:50:54 +00003441 EVT IntPtr = TLI.getPointerTy();
Dan Gohman2140a742010-05-28 01:14:11 +00003442 if (AllocSize.getValueType() != IntPtr)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003443 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurSDLoc(), IntPtr);
Dan Gohman2140a742010-05-28 01:14:11 +00003444
Andrew Trickef9de2a2013-05-25 02:42:55 +00003445 AllocSize = DAG.getNode(ISD::MUL, getCurSDLoc(), IntPtr,
Dan Gohman2140a742010-05-28 01:14:11 +00003446 AllocSize,
3447 DAG.getConstant(TySize, IntPtr));
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00003448
Dan Gohman575fad32008-09-03 16:12:24 +00003449 // Handle alignment. If the requested alignment is less than or equal to
3450 // the stack alignment, ignore it. If the size is greater than or equal to
3451 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Eric Christopherd9134482014-08-04 21:25:23 +00003452 unsigned StackAlign =
Eric Christopher85de8f92014-10-09 01:35:27 +00003453 DAG.getSubtarget().getFrameLowering()->getStackAlignment();
Dan Gohman575fad32008-09-03 16:12:24 +00003454 if (Align <= StackAlign)
3455 Align = 0;
3456
3457 // Round the size of the allocation up to the stack alignment size
3458 // by add SA-1 to the size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003459 AllocSize = DAG.getNode(ISD::ADD, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00003460 AllocSize.getValueType(), AllocSize,
Dan Gohman575fad32008-09-03 16:12:24 +00003461 DAG.getIntPtrConstant(StackAlign-1));
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003462
Dan Gohman575fad32008-09-03 16:12:24 +00003463 // Mask out the low bits for alignment purposes.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003464 AllocSize = DAG.getNode(ISD::AND, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00003465 AllocSize.getValueType(), AllocSize,
Dan Gohman575fad32008-09-03 16:12:24 +00003466 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
3467
3468 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Owen Anderson9f944592009-08-11 20:47:22 +00003469 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
Craig Topper48d114b2014-04-26 18:35:24 +00003470 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurSDLoc(), VTs, Ops);
Dan Gohman575fad32008-09-03 16:12:24 +00003471 setValue(&I, DSA);
3472 DAG.setRoot(DSA.getValue(1));
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003473
Hans Wennborgacb842d2014-03-05 02:43:26 +00003474 assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
Dan Gohman575fad32008-09-03 16:12:24 +00003475}
3476
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003477void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
Eli Friedman342e8df2011-08-24 20:50:09 +00003478 if (I.isAtomic())
3479 return visitAtomicLoad(I);
3480
Dan Gohman575fad32008-09-03 16:12:24 +00003481 const Value *SV = I.getOperand(0);
3482 SDValue Ptr = getValue(SV);
3483
Chris Lattner229907c2011-07-18 04:54:35 +00003484 Type *Ty = I.getType();
David Greene39c6d012010-02-15 17:00:31 +00003485
Dan Gohman575fad32008-09-03 16:12:24 +00003486 bool isVolatile = I.isVolatile();
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00003487 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3488 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00003489 unsigned Alignment = I.getAlignment();
Hal Finkelcc39b672014-07-24 12:16:19 +00003490
3491 AAMDNodes AAInfo;
3492 I.getAAMetadata(AAInfo);
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00003493 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
Dan Gohman575fad32008-09-03 16:12:24 +00003494
Eric Christopher58a24612014-10-08 09:50:54 +00003495 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Owen Anderson53aa7a92009-08-10 22:56:29 +00003496 SmallVector<EVT, 4> ValueVTs;
Dan Gohman575fad32008-09-03 16:12:24 +00003497 SmallVector<uint64_t, 4> Offsets;
Eric Christopher58a24612014-10-08 09:50:54 +00003498 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
Dan Gohman575fad32008-09-03 16:12:24 +00003499 unsigned NumValues = ValueVTs.size();
3500 if (NumValues == 0)
3501 return;
3502
3503 SDValue Root;
3504 bool ConstantMemory = false;
Richard Sandiford9afe6132013-12-10 10:36:34 +00003505 if (isVolatile || NumValues > MaxParallelChains)
Dan Gohman575fad32008-09-03 16:12:24 +00003506 // Serialize volatile loads with other side effects.
3507 Root = getRoot();
Dan Gohmana94cc6d2010-10-20 00:31:05 +00003508 else if (AA->pointsToConstantMemory(
Hal Finkelcc39b672014-07-24 12:16:19 +00003509 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), AAInfo))) {
Dan Gohman575fad32008-09-03 16:12:24 +00003510 // Do not serialize (non-volatile) loads of constant memory with anything.
3511 Root = DAG.getEntryNode();
3512 ConstantMemory = true;
3513 } else {
3514 // Do not serialize non-volatile loads against each other.
3515 Root = DAG.getRoot();
3516 }
Wesley Peck527da1b2010-11-23 03:31:01 +00003517
Richard Sandiford9afe6132013-12-10 10:36:34 +00003518 if (isVolatile)
Eric Christopher58a24612014-10-08 09:50:54 +00003519 Root = TLI.prepareVolatileOrAtomicLoad(Root, getCurSDLoc(), DAG);
Richard Sandiford9afe6132013-12-10 10:36:34 +00003520
Dan Gohman575fad32008-09-03 16:12:24 +00003521 SmallVector<SDValue, 4> Values(NumValues);
Andrew Trick116efac2010-11-12 17:50:46 +00003522 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3523 NumValues));
Owen Anderson53aa7a92009-08-10 22:56:29 +00003524 EVT PtrVT = Ptr.getValueType();
Andrew Trick116efac2010-11-12 17:50:46 +00003525 unsigned ChainI = 0;
3526 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3527 // Serializing loads here may result in excessive register pressure, and
3528 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3529 // could recover a bit by hoisting nodes upward in the chain by recognizing
3530 // they are side-effect free or do not alias. The optimizer should really
3531 // avoid this case by converting large object/array copies to llvm.memcpy
3532 // (MaxParallelChains should always remain as failsafe).
3533 if (ChainI == MaxParallelChains) {
3534 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
Craig Topper48d114b2014-04-26 18:35:24 +00003535 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Craig Topper2d2aa0c2014-04-30 07:17:30 +00003536 makeArrayRef(Chains.data(), ChainI));
Andrew Trick116efac2010-11-12 17:50:46 +00003537 Root = Chain;
3538 ChainI = 0;
3539 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00003540 SDValue A = DAG.getNode(ISD::ADD, getCurSDLoc(),
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003541 PtrVT, Ptr,
3542 DAG.getConstant(Offsets[i], PtrVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003543 SDValue L = DAG.getLoad(ValueVTs[i], getCurSDLoc(), Root,
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00003544 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
Hal Finkelcc39b672014-07-24 12:16:19 +00003545 isNonTemporal, isInvariant, Alignment, AAInfo,
Rafael Espindola80c540e2012-03-31 18:14:00 +00003546 Ranges);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003547
Dan Gohman575fad32008-09-03 16:12:24 +00003548 Values[i] = L;
Andrew Trick116efac2010-11-12 17:50:46 +00003549 Chains[ChainI] = L.getValue(1);
Dan Gohman575fad32008-09-03 16:12:24 +00003550 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003551
Dan Gohman575fad32008-09-03 16:12:24 +00003552 if (!ConstantMemory) {
Craig Topper48d114b2014-04-26 18:35:24 +00003553 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Craig Topper2d2aa0c2014-04-30 07:17:30 +00003554 makeArrayRef(Chains.data(), ChainI));
Dan Gohman575fad32008-09-03 16:12:24 +00003555 if (isVolatile)
3556 DAG.setRoot(Chain);
3557 else
3558 PendingLoads.push_back(Chain);
3559 }
3560
Andrew Trickef9de2a2013-05-25 02:42:55 +00003561 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00003562 DAG.getVTList(ValueVTs), Values));
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003563}
Dan Gohman575fad32008-09-03 16:12:24 +00003564
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003565void SelectionDAGBuilder::visitStore(const StoreInst &I) {
Eli Friedman342e8df2011-08-24 20:50:09 +00003566 if (I.isAtomic())
3567 return visitAtomicStore(I);
3568
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003569 const Value *SrcV = I.getOperand(0);
3570 const Value *PtrV = I.getOperand(1);
Dan Gohman575fad32008-09-03 16:12:24 +00003571
Owen Anderson53aa7a92009-08-10 22:56:29 +00003572 SmallVector<EVT, 4> ValueVTs;
Dan Gohman575fad32008-09-03 16:12:24 +00003573 SmallVector<uint64_t, 4> Offsets;
Eric Christopher58a24612014-10-08 09:50:54 +00003574 ComputeValueVTs(DAG.getTargetLoweringInfo(), SrcV->getType(),
Eric Christopherd9134482014-08-04 21:25:23 +00003575 ValueVTs, &Offsets);
Dan Gohman575fad32008-09-03 16:12:24 +00003576 unsigned NumValues = ValueVTs.size();
3577 if (NumValues == 0)
3578 return;
3579
3580 // Get the lowered operands. Note that we do this after
3581 // checking if NumResults is zero, because with zero results
3582 // the operands won't have values in the map.
3583 SDValue Src = getValue(SrcV);
3584 SDValue Ptr = getValue(PtrV);
3585
3586 SDValue Root = getRoot();
Andrew Trick116efac2010-11-12 17:50:46 +00003587 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3588 NumValues));
Owen Anderson53aa7a92009-08-10 22:56:29 +00003589 EVT PtrVT = Ptr.getValueType();
Dan Gohman575fad32008-09-03 16:12:24 +00003590 bool isVolatile = I.isVolatile();
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00003591 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00003592 unsigned Alignment = I.getAlignment();
Hal Finkelcc39b672014-07-24 12:16:19 +00003593
3594 AAMDNodes AAInfo;
3595 I.getAAMetadata(AAInfo);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003596
Andrew Trick116efac2010-11-12 17:50:46 +00003597 unsigned ChainI = 0;
3598 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3599 // See visitLoad comments.
3600 if (ChainI == MaxParallelChains) {
Craig Topper48d114b2014-04-26 18:35:24 +00003601 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Craig Topper2d2aa0c2014-04-30 07:17:30 +00003602 makeArrayRef(Chains.data(), ChainI));
Andrew Trick116efac2010-11-12 17:50:46 +00003603 Root = Chain;
3604 ChainI = 0;
3605 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00003606 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, Ptr,
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003607 DAG.getConstant(Offsets[i], PtrVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003608 SDValue St = DAG.getStore(Root, getCurSDLoc(),
Andrew Trick116efac2010-11-12 17:50:46 +00003609 SDValue(Src.getNode(), Src.getResNo() + i),
3610 Add, MachinePointerInfo(PtrV, Offsets[i]),
Hal Finkelcc39b672014-07-24 12:16:19 +00003611 isVolatile, isNonTemporal, Alignment, AAInfo);
Andrew Trick116efac2010-11-12 17:50:46 +00003612 Chains[ChainI] = St;
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003613 }
3614
Craig Topper48d114b2014-04-26 18:35:24 +00003615 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
Craig Topper2d2aa0c2014-04-30 07:17:30 +00003616 makeArrayRef(Chains.data(), ChainI));
Devang Patel05561e82010-10-26 22:14:52 +00003617 DAG.setRoot(StoreNode);
Dan Gohman575fad32008-09-03 16:12:24 +00003618}
3619
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00003620void SelectionDAGBuilder::visitMaskedStore(const CallInst &I) {
3621 SDLoc sdl = getCurSDLoc();
3622
3623 Value *PtrOperand = I.getArgOperand(0);
3624 SDValue Ptr = getValue(PtrOperand);
3625 SDValue Src0 = getValue(I.getArgOperand(1));
3626 SDValue Mask = getValue(I.getArgOperand(3));
3627 EVT VT = Src0.getValueType();
3628 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3629 if (!Alignment)
3630 Alignment = DAG.getEVTAlignment(VT);
3631
3632 AAMDNodes AAInfo;
3633 I.getAAMetadata(AAInfo);
3634
3635 MachineMemOperand *MMO =
3636 DAG.getMachineFunction().
3637 getMachineMemOperand(MachinePointerInfo(PtrOperand),
3638 MachineMemOperand::MOStore, VT.getStoreSize(),
3639 Alignment, AAInfo);
3640 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, MMO);
3641 DAG.setRoot(StoreNode);
3642 setValue(&I, StoreNode);
3643}
3644
3645void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I) {
3646 SDLoc sdl = getCurSDLoc();
3647
3648 Value *PtrOperand = I.getArgOperand(0);
3649 SDValue Ptr = getValue(PtrOperand);
3650 SDValue Src0 = getValue(I.getArgOperand(1));
3651 SDValue Mask = getValue(I.getArgOperand(3));
3652
3653 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3654 EVT VT = TLI.getValueType(I.getType());
3655 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3656 if (!Alignment)
3657 Alignment = DAG.getEVTAlignment(VT);
3658
3659 AAMDNodes AAInfo;
3660 I.getAAMetadata(AAInfo);
3661 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3662
3663 SDValue InChain = DAG.getRoot();
3664 if (AA->pointsToConstantMemory(
3665 AliasAnalysis::Location(PtrOperand,
3666 AA->getTypeStoreSize(I.getType()),
3667 AAInfo))) {
3668 // Do not serialize (non-volatile) loads of constant memory with anything.
3669 InChain = DAG.getEntryNode();
3670 }
3671
3672 MachineMemOperand *MMO =
3673 DAG.getMachineFunction().
3674 getMachineMemOperand(MachinePointerInfo(PtrOperand),
3675 MachineMemOperand::MOLoad, VT.getStoreSize(),
3676 Alignment, AAInfo, Ranges);
3677
3678 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, MMO);
3679 SDValue OutChain = Load.getValue(1);
3680 DAG.setRoot(OutChain);
3681 setValue(&I, Load);
3682}
3683
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003684void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003685 SDLoc dl = getCurSDLoc();
Tim Northovere94a5182014-03-11 10:48:52 +00003686 AtomicOrdering SuccessOrder = I.getSuccessOrdering();
3687 AtomicOrdering FailureOrder = I.getFailureOrdering();
Eli Friedman342e8df2011-08-24 20:50:09 +00003688 SynchronizationScope Scope = I.getSynchScope();
Eli Friedman30a49e92011-08-03 21:06:02 +00003689
3690 SDValue InChain = getRoot();
3691
Tim Northover420a2162014-06-13 14:24:07 +00003692 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
3693 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
3694 SDValue L = DAG.getAtomicCmpSwap(
3695 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
3696 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
3697 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
Robin Morissete2de06b2014-10-16 20:34:57 +00003698 /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope);
Eli Friedman30a49e92011-08-03 21:06:02 +00003699
Tim Northover420a2162014-06-13 14:24:07 +00003700 SDValue OutChain = L.getValue(2);
Eli Friedman30a49e92011-08-03 21:06:02 +00003701
Eli Friedmanadec5872011-07-29 03:05:32 +00003702 setValue(&I, L);
Eli Friedman30a49e92011-08-03 21:06:02 +00003703 DAG.setRoot(OutChain);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003704}
3705
3706void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003707 SDLoc dl = getCurSDLoc();
Eli Friedmanadec5872011-07-29 03:05:32 +00003708 ISD::NodeType NT;
3709 switch (I.getOperation()) {
David Blaikie46a9f012012-01-20 21:51:11 +00003710 default: llvm_unreachable("Unknown atomicrmw operation");
Eli Friedmanadec5872011-07-29 03:05:32 +00003711 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3712 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
3713 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
3714 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
3715 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3716 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
3717 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
3718 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
3719 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
3720 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3721 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3722 }
Eli Friedman30a49e92011-08-03 21:06:02 +00003723 AtomicOrdering Order = I.getOrdering();
Eli Friedman342e8df2011-08-24 20:50:09 +00003724 SynchronizationScope Scope = I.getSynchScope();
Eli Friedman30a49e92011-08-03 21:06:02 +00003725
3726 SDValue InChain = getRoot();
3727
Robin Morissete2de06b2014-10-16 20:34:57 +00003728 SDValue L =
3729 DAG.getAtomic(NT, dl,
3730 getValue(I.getValOperand()).getSimpleValueType(),
3731 InChain,
3732 getValue(I.getPointerOperand()),
3733 getValue(I.getValOperand()),
3734 I.getPointerOperand(),
3735 /* Alignment=*/ 0, Order, Scope);
Eli Friedman30a49e92011-08-03 21:06:02 +00003736
3737 SDValue OutChain = L.getValue(1);
3738
Eli Friedmanadec5872011-07-29 03:05:32 +00003739 setValue(&I, L);
Eli Friedman30a49e92011-08-03 21:06:02 +00003740 DAG.setRoot(OutChain);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003741}
3742
Eli Friedmanfee02c62011-07-25 23:16:38 +00003743void SelectionDAGBuilder::visitFence(const FenceInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003744 SDLoc dl = getCurSDLoc();
Eric Christopher58a24612014-10-08 09:50:54 +00003745 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Eli Friedman26a48482011-07-27 22:21:52 +00003746 SDValue Ops[3];
3747 Ops[0] = getRoot();
Eric Christopher58a24612014-10-08 09:50:54 +00003748 Ops[1] = DAG.getConstant(I.getOrdering(), TLI.getPointerTy());
3749 Ops[2] = DAG.getConstant(I.getSynchScope(), TLI.getPointerTy());
Craig Topper48d114b2014-04-26 18:35:24 +00003750 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
Eli Friedmanfee02c62011-07-25 23:16:38 +00003751}
3752
Eli Friedman342e8df2011-08-24 20:50:09 +00003753void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003754 SDLoc dl = getCurSDLoc();
Eli Friedman342e8df2011-08-24 20:50:09 +00003755 AtomicOrdering Order = I.getOrdering();
3756 SynchronizationScope Scope = I.getSynchScope();
3757
3758 SDValue InChain = getRoot();
3759
Eric Christopher58a24612014-10-08 09:50:54 +00003760 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3761 EVT VT = TLI.getValueType(I.getType());
Eli Friedman342e8df2011-08-24 20:50:09 +00003762
Evan Chenga72b9702013-02-06 02:06:33 +00003763 if (I.getAlignment() < VT.getSizeInBits() / 8)
Eli Friedmanf1518212011-09-13 20:50:54 +00003764 report_fatal_error("Cannot generate unaligned atomic load");
3765
Nick Lewyckyaad475b2014-04-15 07:22:52 +00003766 MachineMemOperand *MMO =
3767 DAG.getMachineFunction().
3768 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
3769 MachineMemOperand::MOVolatile |
3770 MachineMemOperand::MOLoad,
3771 VT.getStoreSize(),
3772 I.getAlignment() ? I.getAlignment() :
3773 DAG.getEVTAlignment(VT));
3774
Eric Christopher58a24612014-10-08 09:50:54 +00003775 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
Robin Morissete2de06b2014-10-16 20:34:57 +00003776 SDValue L =
3777 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3778 getValue(I.getPointerOperand()), MMO,
3779 Order, Scope);
Eli Friedman342e8df2011-08-24 20:50:09 +00003780
3781 SDValue OutChain = L.getValue(1);
3782
Eli Friedman342e8df2011-08-24 20:50:09 +00003783 setValue(&I, L);
3784 DAG.setRoot(OutChain);
3785}
3786
3787void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003788 SDLoc dl = getCurSDLoc();
Eli Friedman342e8df2011-08-24 20:50:09 +00003789
3790 AtomicOrdering Order = I.getOrdering();
3791 SynchronizationScope Scope = I.getSynchScope();
3792
3793 SDValue InChain = getRoot();
3794
Eric Christopher58a24612014-10-08 09:50:54 +00003795 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3796 EVT VT = TLI.getValueType(I.getValueOperand()->getType());
Eli Friedmanf1518212011-09-13 20:50:54 +00003797
Evan Chenga72b9702013-02-06 02:06:33 +00003798 if (I.getAlignment() < VT.getSizeInBits() / 8)
Eli Friedmanf1518212011-09-13 20:50:54 +00003799 report_fatal_error("Cannot generate unaligned atomic store");
3800
Robin Morissete2de06b2014-10-16 20:34:57 +00003801 SDValue OutChain =
3802 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
3803 InChain,
3804 getValue(I.getPointerOperand()),
3805 getValue(I.getValueOperand()),
3806 I.getPointerOperand(), I.getAlignment(),
3807 Order, Scope);
Eli Friedman342e8df2011-08-24 20:50:09 +00003808
3809 DAG.setRoot(OutChain);
3810}
3811
Dan Gohman575fad32008-09-03 16:12:24 +00003812/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3813/// node.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00003814void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
Dan Gohman1a6c47f2009-11-23 18:04:58 +00003815 unsigned Intrinsic) {
Dan Gohman575fad32008-09-03 16:12:24 +00003816 bool HasChain = !I.doesNotAccessMemory();
3817 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3818
3819 // Build the operand list.
3820 SmallVector<SDValue, 8> Ops;
3821 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3822 if (OnlyLoad) {
3823 // We don't need to serialize loads against other loads.
3824 Ops.push_back(DAG.getRoot());
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003825 } else {
Dan Gohman575fad32008-09-03 16:12:24 +00003826 Ops.push_back(getRoot());
3827 }
3828 }
Mon P Wang769134b2008-11-01 20:24:53 +00003829
3830 // Info is set by getTgtMemInstrinsic
3831 TargetLowering::IntrinsicInfo Info;
Eric Christopher58a24612014-10-08 09:50:54 +00003832 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3833 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
Mon P Wang769134b2008-11-01 20:24:53 +00003834
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003835 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Bob Wilson5549d492010-09-21 17:56:22 +00003836 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3837 Info.opc == ISD::INTRINSIC_W_CHAIN)
Eric Christopher58a24612014-10-08 09:50:54 +00003838 Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohman575fad32008-09-03 16:12:24 +00003839
3840 // Add all operands of the call to the operand list.
Gabor Greifeba0be72010-06-25 09:38:13 +00003841 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3842 SDValue Op = getValue(I.getArgOperand(i));
Dan Gohman575fad32008-09-03 16:12:24 +00003843 Ops.push_back(Op);
3844 }
3845
Owen Anderson53aa7a92009-08-10 22:56:29 +00003846 SmallVector<EVT, 4> ValueVTs;
Eric Christopher58a24612014-10-08 09:50:54 +00003847 ComputeValueVTs(TLI, I.getType(), ValueVTs);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003848
Dan Gohman575fad32008-09-03 16:12:24 +00003849 if (HasChain)
Owen Anderson9f944592009-08-11 20:47:22 +00003850 ValueVTs.push_back(MVT::Other);
Dan Gohman575fad32008-09-03 16:12:24 +00003851
Craig Topperabb4ac72014-04-16 06:10:51 +00003852 SDVTList VTs = DAG.getVTList(ValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00003853
3854 // Create the node.
3855 SDValue Result;
Mon P Wang769134b2008-11-01 20:24:53 +00003856 if (IsTgtIntrinsic) {
3857 // This is target intrinsic that touches memory
Andrew Trickef9de2a2013-05-25 02:42:55 +00003858 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
Craig Topper206fcd42014-04-26 19:29:41 +00003859 VTs, Ops, Info.memVT,
Chris Lattnerd2d58ad2010-09-21 04:57:15 +00003860 MachinePointerInfo(Info.ptrVal, Info.offset),
Mon P Wang769134b2008-11-01 20:24:53 +00003861 Info.align, Info.vol,
Hal Finkel46ef7ce2014-08-13 01:15:40 +00003862 Info.readMem, Info.writeMem, Info.size);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003863 } else if (!HasChain) {
Craig Topper48d114b2014-04-26 18:35:24 +00003864 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00003865 } else if (!I.getType()->isVoidTy()) {
Craig Topper48d114b2014-04-26 18:35:24 +00003866 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003867 } else {
Craig Topper48d114b2014-04-26 18:35:24 +00003868 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003869 }
3870
Dan Gohman575fad32008-09-03 16:12:24 +00003871 if (HasChain) {
3872 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3873 if (OnlyLoad)
3874 PendingLoads.push_back(Chain);
3875 else
3876 DAG.setRoot(Chain);
3877 }
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003878
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00003879 if (!I.getType()->isVoidTy()) {
Chris Lattner229907c2011-07-18 04:54:35 +00003880 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Eric Christopher58a24612014-10-08 09:50:54 +00003881 EVT VT = TLI.getValueType(PTy);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003882 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00003883 }
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003884
Dan Gohman575fad32008-09-03 16:12:24 +00003885 setValue(&I, Result);
3886 }
3887}
3888
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003889/// GetSignificand - Get the significand and build it into a floating-point
3890/// number with exponent of 1:
3891///
3892/// Op = (Op & 0x007fffff) | 0x3f800000;
3893///
Matt Beaumont-Gay0e760da2013-02-25 18:11:18 +00003894/// where Op is the hexadecimal representation of floating point value.
Bill Wendlinged3bb782008-09-09 20:39:27 +00003895static SDValue
Andrew Trickef9de2a2013-05-25 02:42:55 +00003896GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
Owen Anderson9f944592009-08-11 20:47:22 +00003897 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3898 DAG.getConstant(0x007fffff, MVT::i32));
3899 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3900 DAG.getConstant(0x3f800000, MVT::i32));
Wesley Peck527da1b2010-11-23 03:31:01 +00003901 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
Bill Wendlinged3bb782008-09-09 20:39:27 +00003902}
3903
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003904/// GetExponent - Get the exponent:
3905///
Bill Wendling23959162009-01-20 21:17:57 +00003906/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003907///
Matt Beaumont-Gay0e760da2013-02-25 18:11:18 +00003908/// where Op is the hexadecimal representation of floating point value.
Bill Wendlinged3bb782008-09-09 20:39:27 +00003909static SDValue
Dale Johannesendb7c5f62009-01-31 02:22:37 +00003910GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
Andrew Trickef9de2a2013-05-25 02:42:55 +00003911 SDLoc dl) {
Owen Anderson9f944592009-08-11 20:47:22 +00003912 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3913 DAG.getConstant(0x7f800000, MVT::i32));
3914 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands41826032009-01-31 15:50:11 +00003915 DAG.getConstant(23, TLI.getPointerTy()));
Owen Anderson9f944592009-08-11 20:47:22 +00003916 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3917 DAG.getConstant(127, MVT::i32));
Bill Wendling954cb182010-01-28 21:51:40 +00003918 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendlinged3bb782008-09-09 20:39:27 +00003919}
3920
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003921/// getF32Constant - Get 32-bit floating point constant.
3922static SDValue
3923getF32Constant(SelectionDAG &DAG, unsigned Flt) {
Tim Northover29178a32013-01-22 09:46:31 +00003924 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)),
3925 MVT::f32);
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003926}
3927
Craig Topperd2638c12012-11-24 18:52:06 +00003928/// expandExp - Lower an exp intrinsic. Handles the special sequences for
Bill Wendling48217d82008-09-09 22:13:54 +00003929/// limited-precision mode.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003930static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topperd2638c12012-11-24 18:52:06 +00003931 const TargetLowering &TLI) {
3932 if (Op.getValueType() == MVT::f32 &&
Bill Wendling48217d82008-09-09 22:13:54 +00003933 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Bill Wendling48217d82008-09-09 22:13:54 +00003934
3935 // Put the exponent in the right bit position for later addition to the
3936 // final result:
3937 //
3938 // #define LOG2OFe 1.4426950f
3939 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Owen Anderson9f944592009-08-11 20:47:22 +00003940 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003941 getF32Constant(DAG, 0x3fb8aa3b));
Owen Anderson9f944592009-08-11 20:47:22 +00003942 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendling48217d82008-09-09 22:13:54 +00003943
3944 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Owen Anderson9f944592009-08-11 20:47:22 +00003945 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3946 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendling48217d82008-09-09 22:13:54 +00003947
3948 // IntegerPartOfX <<= 23;
Owen Anderson9f944592009-08-11 20:47:22 +00003949 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands41826032009-01-31 15:50:11 +00003950 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingea3e73e2009-12-22 00:12:37 +00003951
Craig Topper4a981752012-11-24 08:22:37 +00003952 SDValue TwoToFracPartOfX;
Bill Wendling48217d82008-09-09 22:13:54 +00003953 if (LimitFloatPrecision <= 6) {
3954 // For floating-point precision of 6:
3955 //
3956 // TwoToFractionalPartOfX =
3957 // 0.997535578f +
3958 // (0.735607626f + 0.252464424f * x) * x;
3959 //
3960 // error 0.0144103317, which is 6 bits
Owen Anderson9f944592009-08-11 20:47:22 +00003961 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003962 getF32Constant(DAG, 0x3e814304));
Owen Anderson9f944592009-08-11 20:47:22 +00003963 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003964 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson9f944592009-08-11 20:47:22 +00003965 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topper4a981752012-11-24 08:22:37 +00003966 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3967 getF32Constant(DAG, 0x3f7f5e7e));
Craig Toppered756c52012-11-16 20:01:39 +00003968 } else if (LimitFloatPrecision <= 12) {
Bill Wendling48217d82008-09-09 22:13:54 +00003969 // For floating-point precision of 12:
3970 //
3971 // TwoToFractionalPartOfX =
3972 // 0.999892986f +
3973 // (0.696457318f +
3974 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3975 //
3976 // 0.000107046256 error, which is 13 to 14 bits
Owen Anderson9f944592009-08-11 20:47:22 +00003977 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003978 getF32Constant(DAG, 0x3da235e3));
Owen Anderson9f944592009-08-11 20:47:22 +00003979 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003980 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson9f944592009-08-11 20:47:22 +00003981 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3982 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00003983 getF32Constant(DAG, 0x3f324b07));
Owen Anderson9f944592009-08-11 20:47:22 +00003984 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topper4a981752012-11-24 08:22:37 +00003985 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3986 getF32Constant(DAG, 0x3f7ff8fd));
Craig Toppered756c52012-11-16 20:01:39 +00003987 } else { // LimitFloatPrecision <= 18
Bill Wendling48217d82008-09-09 22:13:54 +00003988 // For floating-point precision of 18:
3989 //
3990 // TwoToFractionalPartOfX =
3991 // 0.999999982f +
3992 // (0.693148872f +
3993 // (0.240227044f +
3994 // (0.554906021e-1f +
3995 // (0.961591928e-2f +
3996 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3997 //
3998 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00003999 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004000 getF32Constant(DAG, 0x3924b03e));
Owen Anderson9f944592009-08-11 20:47:22 +00004001 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004002 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson9f944592009-08-11 20:47:22 +00004003 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4004 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004005 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson9f944592009-08-11 20:47:22 +00004006 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4007 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004008 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson9f944592009-08-11 20:47:22 +00004009 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4010 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004011 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson9f944592009-08-11 20:47:22 +00004012 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4013 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004014 getF32Constant(DAG, 0x3f317234));
Owen Anderson9f944592009-08-11 20:47:22 +00004015 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
Craig Topper4a981752012-11-24 08:22:37 +00004016 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4017 getF32Constant(DAG, 0x3f800000));
Bill Wendling48217d82008-09-09 22:13:54 +00004018 }
Craig Topper4a981752012-11-24 08:22:37 +00004019
4020 // Add the exponent into the result in integer domain.
4021 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFracPartOfX);
Craig Topperd2638c12012-11-24 18:52:06 +00004022 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4023 DAG.getNode(ISD::ADD, dl, MVT::i32,
4024 t13, IntegerPartOfX));
Bill Wendling48217d82008-09-09 22:13:54 +00004025 }
4026
Craig Topperd2638c12012-11-24 18:52:06 +00004027 // No special expansion.
4028 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
Dale Johannesen520143e2008-09-05 18:38:42 +00004029}
4030
Craig Topperbef254a2012-11-23 18:38:31 +00004031/// expandLog - Lower a log intrinsic. Handles the special sequences for
Bill Wendlinged3bb782008-09-09 20:39:27 +00004032/// limited-precision mode.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004033static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topperbef254a2012-11-23 18:38:31 +00004034 const TargetLowering &TLI) {
4035 if (Op.getValueType() == MVT::f32 &&
Bill Wendlinged3bb782008-09-09 20:39:27 +00004036 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Wesley Peck527da1b2010-11-23 03:31:01 +00004037 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendlinged3bb782008-09-09 20:39:27 +00004038
4039 // Scale the exponent by log(2) [0.69314718f].
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004040 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson9f944592009-08-11 20:47:22 +00004041 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004042 getF32Constant(DAG, 0x3f317218));
Bill Wendlinged3bb782008-09-09 20:39:27 +00004043
4044 // Get the significand and build it into a floating-point number with
4045 // exponent of 1.
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004046 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendlinged3bb782008-09-09 20:39:27 +00004047
Craig Topper3669de42012-11-16 19:08:44 +00004048 SDValue LogOfMantissa;
Bill Wendlinged3bb782008-09-09 20:39:27 +00004049 if (LimitFloatPrecision <= 6) {
4050 // For floating-point precision of 6:
4051 //
4052 // LogofMantissa =
4053 // -1.1609546f +
4054 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004055 //
Bill Wendlinged3bb782008-09-09 20:39:27 +00004056 // error 0.0034276066, which is better than 8 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004057 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004058 getF32Constant(DAG, 0xbe74c456));
Owen Anderson9f944592009-08-11 20:47:22 +00004059 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004060 getF32Constant(DAG, 0x3fb3a2b1));
Owen Anderson9f944592009-08-11 20:47:22 +00004061 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topper3669de42012-11-16 19:08:44 +00004062 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4063 getF32Constant(DAG, 0x3f949a29));
Craig Toppered756c52012-11-16 20:01:39 +00004064 } else if (LimitFloatPrecision <= 12) {
Bill Wendlinged3bb782008-09-09 20:39:27 +00004065 // For floating-point precision of 12:
4066 //
4067 // LogOfMantissa =
4068 // -1.7417939f +
4069 // (2.8212026f +
4070 // (-1.4699568f +
4071 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4072 //
4073 // error 0.000061011436, which is 14 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004074 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004075 getF32Constant(DAG, 0xbd67b6d6));
Owen Anderson9f944592009-08-11 20:47:22 +00004076 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004077 getF32Constant(DAG, 0x3ee4f4b8));
Owen Anderson9f944592009-08-11 20:47:22 +00004078 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4079 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004080 getF32Constant(DAG, 0x3fbc278b));
Owen Anderson9f944592009-08-11 20:47:22 +00004081 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4082 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004083 getF32Constant(DAG, 0x40348e95));
Owen Anderson9f944592009-08-11 20:47:22 +00004084 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topper3669de42012-11-16 19:08:44 +00004085 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4086 getF32Constant(DAG, 0x3fdef31a));
Craig Toppered756c52012-11-16 20:01:39 +00004087 } else { // LimitFloatPrecision <= 18
Bill Wendlinged3bb782008-09-09 20:39:27 +00004088 // For floating-point precision of 18:
4089 //
4090 // LogOfMantissa =
4091 // -2.1072184f +
4092 // (4.2372794f +
4093 // (-3.7029485f +
4094 // (2.2781945f +
4095 // (-0.87823314f +
4096 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4097 //
4098 // error 0.0000023660568, which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004099 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004100 getF32Constant(DAG, 0xbc91e5ac));
Owen Anderson9f944592009-08-11 20:47:22 +00004101 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004102 getF32Constant(DAG, 0x3e4350aa));
Owen Anderson9f944592009-08-11 20:47:22 +00004103 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4104 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004105 getF32Constant(DAG, 0x3f60d3e3));
Owen Anderson9f944592009-08-11 20:47:22 +00004106 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4107 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004108 getF32Constant(DAG, 0x4011cdf0));
Owen Anderson9f944592009-08-11 20:47:22 +00004109 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4110 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004111 getF32Constant(DAG, 0x406cfd1c));
Owen Anderson9f944592009-08-11 20:47:22 +00004112 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4113 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004114 getF32Constant(DAG, 0x408797cb));
Owen Anderson9f944592009-08-11 20:47:22 +00004115 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
Craig Topper3669de42012-11-16 19:08:44 +00004116 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4117 getF32Constant(DAG, 0x4006dcab));
Bill Wendlinged3bb782008-09-09 20:39:27 +00004118 }
Craig Topper3669de42012-11-16 19:08:44 +00004119
Craig Topperbef254a2012-11-23 18:38:31 +00004120 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendlinged3bb782008-09-09 20:39:27 +00004121 }
4122
Craig Topperbef254a2012-11-23 18:38:31 +00004123 // No special expansion.
4124 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
Dale Johannesen520143e2008-09-05 18:38:42 +00004125}
4126
Craig Topperbef254a2012-11-23 18:38:31 +00004127/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
Bill Wendling48416782008-09-09 00:28:24 +00004128/// limited-precision mode.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004129static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topperbef254a2012-11-23 18:38:31 +00004130 const TargetLowering &TLI) {
4131 if (Op.getValueType() == MVT::f32 &&
Bill Wendling48416782008-09-09 00:28:24 +00004132 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Wesley Peck527da1b2010-11-23 03:31:01 +00004133 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendling48416782008-09-09 00:28:24 +00004134
Bill Wendlinged3bb782008-09-09 20:39:27 +00004135 // Get the exponent.
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004136 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
Bill Wendlingea3e73e2009-12-22 00:12:37 +00004137
Bill Wendling48416782008-09-09 00:28:24 +00004138 // Get the significand and build it into a floating-point number with
Bill Wendlinged3bb782008-09-09 20:39:27 +00004139 // exponent of 1.
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004140 SDValue X = GetSignificand(DAG, Op1, dl);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004141
Bill Wendling48416782008-09-09 00:28:24 +00004142 // Different possible minimax approximations of significand in
4143 // floating-point for various degrees of accuracy over [1,2].
Craig Topper3669de42012-11-16 19:08:44 +00004144 SDValue Log2ofMantissa;
Bill Wendling48416782008-09-09 00:28:24 +00004145 if (LimitFloatPrecision <= 6) {
4146 // For floating-point precision of 6:
4147 //
4148 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4149 //
4150 // error 0.0049451742, which is more than 7 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004151 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004152 getF32Constant(DAG, 0xbeb08fe0));
Owen Anderson9f944592009-08-11 20:47:22 +00004153 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004154 getF32Constant(DAG, 0x40019463));
Owen Anderson9f944592009-08-11 20:47:22 +00004155 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topper3669de42012-11-16 19:08:44 +00004156 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4157 getF32Constant(DAG, 0x3fd6633d));
Craig Toppered756c52012-11-16 20:01:39 +00004158 } else if (LimitFloatPrecision <= 12) {
Bill Wendling48416782008-09-09 00:28:24 +00004159 // For floating-point precision of 12:
4160 //
4161 // Log2ofMantissa =
4162 // -2.51285454f +
4163 // (4.07009056f +
4164 // (-2.12067489f +
4165 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004166 //
Bill Wendling48416782008-09-09 00:28:24 +00004167 // error 0.0000876136000, which is better than 13 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004168 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004169 getF32Constant(DAG, 0xbda7262e));
Owen Anderson9f944592009-08-11 20:47:22 +00004170 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004171 getF32Constant(DAG, 0x3f25280b));
Owen Anderson9f944592009-08-11 20:47:22 +00004172 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4173 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004174 getF32Constant(DAG, 0x4007b923));
Owen Anderson9f944592009-08-11 20:47:22 +00004175 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4176 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004177 getF32Constant(DAG, 0x40823e2f));
Owen Anderson9f944592009-08-11 20:47:22 +00004178 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topper3669de42012-11-16 19:08:44 +00004179 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4180 getF32Constant(DAG, 0x4020d29c));
Craig Toppered756c52012-11-16 20:01:39 +00004181 } else { // LimitFloatPrecision <= 18
Bill Wendling48416782008-09-09 00:28:24 +00004182 // For floating-point precision of 18:
4183 //
4184 // Log2ofMantissa =
4185 // -3.0400495f +
4186 // (6.1129976f +
4187 // (-5.3420409f +
4188 // (3.2865683f +
4189 // (-1.2669343f +
4190 // (0.27515199f -
4191 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4192 //
4193 // error 0.0000018516, which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004194 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004195 getF32Constant(DAG, 0xbcd2769e));
Owen Anderson9f944592009-08-11 20:47:22 +00004196 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004197 getF32Constant(DAG, 0x3e8ce0b9));
Owen Anderson9f944592009-08-11 20:47:22 +00004198 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4199 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004200 getF32Constant(DAG, 0x3fa22ae7));
Owen Anderson9f944592009-08-11 20:47:22 +00004201 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4202 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004203 getF32Constant(DAG, 0x40525723));
Owen Anderson9f944592009-08-11 20:47:22 +00004204 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4205 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004206 getF32Constant(DAG, 0x40aaf200));
Owen Anderson9f944592009-08-11 20:47:22 +00004207 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4208 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004209 getF32Constant(DAG, 0x40c39dad));
Owen Anderson9f944592009-08-11 20:47:22 +00004210 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
Craig Topper3669de42012-11-16 19:08:44 +00004211 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4212 getF32Constant(DAG, 0x4042902c));
Bill Wendling48416782008-09-09 00:28:24 +00004213 }
Craig Topper3669de42012-11-16 19:08:44 +00004214
Craig Topperbef254a2012-11-23 18:38:31 +00004215 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
Dale Johannesen36d532a2008-09-05 23:49:37 +00004216 }
Bill Wendling48416782008-09-09 00:28:24 +00004217
Craig Topperbef254a2012-11-23 18:38:31 +00004218 // No special expansion.
4219 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
Dale Johannesen520143e2008-09-05 18:38:42 +00004220}
4221
Craig Topperbef254a2012-11-23 18:38:31 +00004222/// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
Bill Wendling48416782008-09-09 00:28:24 +00004223/// limited-precision mode.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004224static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topperbef254a2012-11-23 18:38:31 +00004225 const TargetLowering &TLI) {
4226 if (Op.getValueType() == MVT::f32 &&
Bill Wendling48416782008-09-09 00:28:24 +00004227 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Wesley Peck527da1b2010-11-23 03:31:01 +00004228 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendling48416782008-09-09 00:28:24 +00004229
Bill Wendlinged3bb782008-09-09 20:39:27 +00004230 // Scale the exponent by log10(2) [0.30102999f].
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004231 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson9f944592009-08-11 20:47:22 +00004232 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004233 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling48416782008-09-09 00:28:24 +00004234
4235 // Get the significand and build it into a floating-point number with
Bill Wendlinged3bb782008-09-09 20:39:27 +00004236 // exponent of 1.
Bill Wendling78c5b7a2010-03-02 01:55:18 +00004237 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling48416782008-09-09 00:28:24 +00004238
Craig Topper3669de42012-11-16 19:08:44 +00004239 SDValue Log10ofMantissa;
Bill Wendling48416782008-09-09 00:28:24 +00004240 if (LimitFloatPrecision <= 6) {
Bill Wendlingfaeb4b62008-09-09 18:42:23 +00004241 // For floating-point precision of 6:
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004242 //
Bill Wendlingfaeb4b62008-09-09 18:42:23 +00004243 // Log10ofMantissa =
4244 // -0.50419619f +
4245 // (0.60948995f - 0.10380950f * x) * x;
4246 //
4247 // error 0.0014886165, which is 6 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004248 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004249 getF32Constant(DAG, 0xbdd49a13));
Owen Anderson9f944592009-08-11 20:47:22 +00004250 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004251 getF32Constant(DAG, 0x3f1c0789));
Owen Anderson9f944592009-08-11 20:47:22 +00004252 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topper3669de42012-11-16 19:08:44 +00004253 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4254 getF32Constant(DAG, 0x3f011300));
Craig Toppered756c52012-11-16 20:01:39 +00004255 } else if (LimitFloatPrecision <= 12) {
Bill Wendling48416782008-09-09 00:28:24 +00004256 // For floating-point precision of 12:
4257 //
4258 // Log10ofMantissa =
4259 // -0.64831180f +
4260 // (0.91751397f +
4261 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4262 //
4263 // error 0.00019228036, which is better than 12 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004264 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004265 getF32Constant(DAG, 0x3d431f31));
Owen Anderson9f944592009-08-11 20:47:22 +00004266 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004267 getF32Constant(DAG, 0x3ea21fb2));
Owen Anderson9f944592009-08-11 20:47:22 +00004268 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4269 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004270 getF32Constant(DAG, 0x3f6ae232));
Owen Anderson9f944592009-08-11 20:47:22 +00004271 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topper3669de42012-11-16 19:08:44 +00004272 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4273 getF32Constant(DAG, 0x3f25f7c3));
Craig Toppered756c52012-11-16 20:01:39 +00004274 } else { // LimitFloatPrecision <= 18
Bill Wendlingfaeb4b62008-09-09 18:42:23 +00004275 // For floating-point precision of 18:
4276 //
4277 // Log10ofMantissa =
4278 // -0.84299375f +
4279 // (1.5327582f +
4280 // (-1.0688956f +
4281 // (0.49102474f +
4282 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4283 //
4284 // error 0.0000037995730, which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004285 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004286 getF32Constant(DAG, 0x3c5d51ce));
Owen Anderson9f944592009-08-11 20:47:22 +00004287 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004288 getF32Constant(DAG, 0x3e00685a));
Owen Anderson9f944592009-08-11 20:47:22 +00004289 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4290 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004291 getF32Constant(DAG, 0x3efb6798));
Owen Anderson9f944592009-08-11 20:47:22 +00004292 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4293 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004294 getF32Constant(DAG, 0x3f88d192));
Owen Anderson9f944592009-08-11 20:47:22 +00004295 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4296 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004297 getF32Constant(DAG, 0x3fc4316c));
Owen Anderson9f944592009-08-11 20:47:22 +00004298 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
Craig Topper3669de42012-11-16 19:08:44 +00004299 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4300 getF32Constant(DAG, 0x3f57ce70));
Bill Wendling48416782008-09-09 00:28:24 +00004301 }
Craig Topper3669de42012-11-16 19:08:44 +00004302
Craig Topperbef254a2012-11-23 18:38:31 +00004303 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
Dale Johannesend4dac0e2008-09-05 21:27:19 +00004304 }
Bill Wendling48416782008-09-09 00:28:24 +00004305
Craig Topperbef254a2012-11-23 18:38:31 +00004306 // No special expansion.
4307 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
Dale Johannesen520143e2008-09-05 18:38:42 +00004308}
4309
Craig Topperd2638c12012-11-24 18:52:06 +00004310/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
Bill Wendlingab6676a2008-09-09 22:39:21 +00004311/// limited-precision mode.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004312static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
Craig Topperd2638c12012-11-24 18:52:06 +00004313 const TargetLowering &TLI) {
4314 if (Op.getValueType() == MVT::f32 &&
Bill Wendlingab6676a2008-09-09 22:39:21 +00004315 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Owen Anderson9f944592009-08-11 20:47:22 +00004316 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlingab6676a2008-09-09 22:39:21 +00004317
4318 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson9f944592009-08-11 20:47:22 +00004319 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4320 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlingab6676a2008-09-09 22:39:21 +00004321
4322 // IntegerPartOfX <<= 23;
Owen Anderson9f944592009-08-11 20:47:22 +00004323 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands41826032009-01-31 15:50:11 +00004324 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingab6676a2008-09-09 22:39:21 +00004325
Craig Topper4a981752012-11-24 08:22:37 +00004326 SDValue TwoToFractionalPartOfX;
Bill Wendlingab6676a2008-09-09 22:39:21 +00004327 if (LimitFloatPrecision <= 6) {
4328 // For floating-point precision of 6:
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004329 //
Bill Wendlingab6676a2008-09-09 22:39:21 +00004330 // TwoToFractionalPartOfX =
4331 // 0.997535578f +
4332 // (0.735607626f + 0.252464424f * x) * x;
4333 //
4334 // error 0.0144103317, which is 6 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004335 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004336 getF32Constant(DAG, 0x3e814304));
Owen Anderson9f944592009-08-11 20:47:22 +00004337 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004338 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson9f944592009-08-11 20:47:22 +00004339 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topper4a981752012-11-24 08:22:37 +00004340 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4341 getF32Constant(DAG, 0x3f7f5e7e));
Craig Toppered756c52012-11-16 20:01:39 +00004342 } else if (LimitFloatPrecision <= 12) {
Bill Wendlingab6676a2008-09-09 22:39:21 +00004343 // For floating-point precision of 12:
4344 //
4345 // TwoToFractionalPartOfX =
4346 // 0.999892986f +
4347 // (0.696457318f +
4348 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4349 //
4350 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004351 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004352 getF32Constant(DAG, 0x3da235e3));
Owen Anderson9f944592009-08-11 20:47:22 +00004353 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004354 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson9f944592009-08-11 20:47:22 +00004355 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4356 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004357 getF32Constant(DAG, 0x3f324b07));
Owen Anderson9f944592009-08-11 20:47:22 +00004358 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topper4a981752012-11-24 08:22:37 +00004359 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4360 getF32Constant(DAG, 0x3f7ff8fd));
Craig Toppered756c52012-11-16 20:01:39 +00004361 } else { // LimitFloatPrecision <= 18
Bill Wendlingab6676a2008-09-09 22:39:21 +00004362 // For floating-point precision of 18:
4363 //
4364 // TwoToFractionalPartOfX =
4365 // 0.999999982f +
4366 // (0.693148872f +
4367 // (0.240227044f +
4368 // (0.554906021e-1f +
4369 // (0.961591928e-2f +
4370 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4371 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004372 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004373 getF32Constant(DAG, 0x3924b03e));
Owen Anderson9f944592009-08-11 20:47:22 +00004374 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004375 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson9f944592009-08-11 20:47:22 +00004376 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4377 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004378 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson9f944592009-08-11 20:47:22 +00004379 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4380 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004381 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson9f944592009-08-11 20:47:22 +00004382 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4383 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004384 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson9f944592009-08-11 20:47:22 +00004385 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4386 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004387 getF32Constant(DAG, 0x3f317234));
Owen Anderson9f944592009-08-11 20:47:22 +00004388 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
Craig Topper4a981752012-11-24 08:22:37 +00004389 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4390 getF32Constant(DAG, 0x3f800000));
Bill Wendlingab6676a2008-09-09 22:39:21 +00004391 }
Craig Topper4a981752012-11-24 08:22:37 +00004392
4393 // Add the exponent into the result in integer domain.
4394 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4395 TwoToFractionalPartOfX);
Craig Topperd2638c12012-11-24 18:52:06 +00004396 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4397 DAG.getNode(ISD::ADD, dl, MVT::i32,
4398 t13, IntegerPartOfX));
Dale Johannesenf2a52bb2008-09-05 01:48:15 +00004399 }
Bill Wendlingab6676a2008-09-09 22:39:21 +00004400
Craig Topperd2638c12012-11-24 18:52:06 +00004401 // No special expansion.
4402 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
Dale Johannesenf2a52bb2008-09-05 01:48:15 +00004403}
4404
Bill Wendling648930b2008-09-10 00:20:20 +00004405/// visitPow - Lower a pow intrinsic. Handles the special sequences for
4406/// limited-precision mode with x == 10.0f.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004407static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
Craig Topper79bd2052012-11-25 08:08:58 +00004408 SelectionDAG &DAG, const TargetLowering &TLI) {
Bill Wendling648930b2008-09-10 00:20:20 +00004409 bool IsExp10 = false;
Benjamin Kramer671a5962013-12-11 16:36:09 +00004410 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
Bill Wendling648930b2008-09-10 00:20:20 +00004411 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Craig Topper79bd2052012-11-25 08:08:58 +00004412 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4413 APFloat Ten(10.0f);
4414 IsExp10 = LHSC->isExactlyValue(Ten);
Bill Wendling648930b2008-09-10 00:20:20 +00004415 }
4416 }
4417
Craig Topper268b6222012-11-25 00:48:58 +00004418 if (IsExp10) {
Bill Wendling648930b2008-09-10 00:20:20 +00004419 // Put the exponent in the right bit position for later addition to the
4420 // final result:
4421 //
4422 // #define LOG2OF10 3.3219281f
4423 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Craig Topper79bd2052012-11-25 08:08:58 +00004424 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004425 getF32Constant(DAG, 0x40549a78));
Owen Anderson9f944592009-08-11 20:47:22 +00004426 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendling648930b2008-09-10 00:20:20 +00004427
4428 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson9f944592009-08-11 20:47:22 +00004429 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4430 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendling648930b2008-09-10 00:20:20 +00004431
4432 // IntegerPartOfX <<= 23;
Owen Anderson9f944592009-08-11 20:47:22 +00004433 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands41826032009-01-31 15:50:11 +00004434 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendling648930b2008-09-10 00:20:20 +00004435
Craig Topper85719442012-11-25 00:15:07 +00004436 SDValue TwoToFractionalPartOfX;
Bill Wendling648930b2008-09-10 00:20:20 +00004437 if (LimitFloatPrecision <= 6) {
4438 // For floating-point precision of 6:
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004439 //
Bill Wendling648930b2008-09-10 00:20:20 +00004440 // twoToFractionalPartOfX =
4441 // 0.997535578f +
4442 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00004443 //
Bill Wendling648930b2008-09-10 00:20:20 +00004444 // error 0.0144103317, which is 6 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004445 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004446 getF32Constant(DAG, 0x3e814304));
Owen Anderson9f944592009-08-11 20:47:22 +00004447 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004448 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson9f944592009-08-11 20:47:22 +00004449 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topper85719442012-11-25 00:15:07 +00004450 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4451 getF32Constant(DAG, 0x3f7f5e7e));
Craig Toppered756c52012-11-16 20:01:39 +00004452 } else if (LimitFloatPrecision <= 12) {
Bill Wendling648930b2008-09-10 00:20:20 +00004453 // For floating-point precision of 12:
4454 //
4455 // TwoToFractionalPartOfX =
4456 // 0.999892986f +
4457 // (0.696457318f +
4458 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4459 //
4460 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004461 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004462 getF32Constant(DAG, 0x3da235e3));
Owen Anderson9f944592009-08-11 20:47:22 +00004463 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004464 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson9f944592009-08-11 20:47:22 +00004465 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4466 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004467 getF32Constant(DAG, 0x3f324b07));
Owen Anderson9f944592009-08-11 20:47:22 +00004468 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topper85719442012-11-25 00:15:07 +00004469 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4470 getF32Constant(DAG, 0x3f7ff8fd));
Craig Toppered756c52012-11-16 20:01:39 +00004471 } else { // LimitFloatPrecision <= 18
Bill Wendling648930b2008-09-10 00:20:20 +00004472 // For floating-point precision of 18:
4473 //
4474 // TwoToFractionalPartOfX =
4475 // 0.999999982f +
4476 // (0.693148872f +
4477 // (0.240227044f +
4478 // (0.554906021e-1f +
4479 // (0.961591928e-2f +
4480 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4481 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson9f944592009-08-11 20:47:22 +00004482 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004483 getF32Constant(DAG, 0x3924b03e));
Owen Anderson9f944592009-08-11 20:47:22 +00004484 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004485 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson9f944592009-08-11 20:47:22 +00004486 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4487 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004488 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson9f944592009-08-11 20:47:22 +00004489 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4490 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004491 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson9f944592009-08-11 20:47:22 +00004492 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4493 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004494 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson9f944592009-08-11 20:47:22 +00004495 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4496 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendling91ef8fc2008-09-22 00:44:35 +00004497 getF32Constant(DAG, 0x3f317234));
Owen Anderson9f944592009-08-11 20:47:22 +00004498 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
Craig Topper85719442012-11-25 00:15:07 +00004499 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4500 getF32Constant(DAG, 0x3f800000));
Bill Wendling648930b2008-09-10 00:20:20 +00004501 }
Craig Topper85719442012-11-25 00:15:07 +00004502
4503 SDValue t13 = DAG.getNode(ISD::BITCAST, dl,MVT::i32,TwoToFractionalPartOfX);
Craig Topper79bd2052012-11-25 08:08:58 +00004504 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4505 DAG.getNode(ISD::ADD, dl, MVT::i32,
4506 t13, IntegerPartOfX));
Bill Wendling648930b2008-09-10 00:20:20 +00004507 }
4508
Craig Topper79bd2052012-11-25 08:08:58 +00004509 // No special expansion.
4510 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
Bill Wendling648930b2008-09-10 00:20:20 +00004511}
4512
Chris Lattner39f18e52010-01-01 03:32:16 +00004513
4514/// ExpandPowI - Expand a llvm.powi intrinsic.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004515static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
Chris Lattner39f18e52010-01-01 03:32:16 +00004516 SelectionDAG &DAG) {
4517 // If RHS is a constant, we can expand this out to a multiplication tree,
4518 // otherwise we end up lowering to a call to __powidf2 (for example). When
4519 // optimizing for size, we only want to do this if the expansion would produce
4520 // a small number of multiplies, otherwise we do the full expansion.
4521 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4522 // Get the exponent as a positive value.
4523 unsigned Val = RHSC->getSExtValue();
4524 if ((int)Val < 0) Val = -Val;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00004525
Chris Lattner39f18e52010-01-01 03:32:16 +00004526 // powi(x, 0) -> 1.0
4527 if (Val == 0)
4528 return DAG.getConstantFP(1.0, LHS.getValueType());
4529
Dan Gohman913c9982010-04-15 04:33:49 +00004530 const Function *F = DAG.getMachineFunction().getFunction();
Bill Wendling698e84f2012-12-30 10:32:01 +00004531 if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
4532 Attribute::OptimizeForSize) ||
Chris Lattner39f18e52010-01-01 03:32:16 +00004533 // If optimizing for size, don't insert too many multiplies. This
4534 // inserts up to 5 multiplies.
4535 CountPopulation_32(Val)+Log2_32(Val) < 7) {
4536 // We use the simple binary decomposition method to generate the multiply
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00004537 // sequence. There are more optimal ways to do this (for example,
Chris Lattner39f18e52010-01-01 03:32:16 +00004538 // powi(x,15) generates one more multiply than it should), but this has
4539 // the benefit of being both really simple and much better than a libcall.
4540 SDValue Res; // Logically starts equal to 1.0
4541 SDValue CurSquare = LHS;
4542 while (Val) {
Mikhail Glushenkov5c35d2f2010-01-01 04:41:36 +00004543 if (Val & 1) {
Chris Lattner39f18e52010-01-01 03:32:16 +00004544 if (Res.getNode())
4545 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4546 else
4547 Res = CurSquare; // 1.0*CurSquare.
Mikhail Glushenkov5c35d2f2010-01-01 04:41:36 +00004548 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00004549
Chris Lattner39f18e52010-01-01 03:32:16 +00004550 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4551 CurSquare, CurSquare);
4552 Val >>= 1;
4553 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00004554
Chris Lattner39f18e52010-01-01 03:32:16 +00004555 // If the original was negative, invert the result, producing 1/(x*x*x).
4556 if (RHSC->getSExtValue() < 0)
4557 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4558 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4559 return Res;
4560 }
4561 }
4562
4563 // Otherwise, expand to a libcall.
4564 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4565}
4566
Devang Patel8e60ff12011-05-16 21:24:05 +00004567// getTruncatedArgReg - Find underlying register used for an truncated
4568// argument.
4569static unsigned getTruncatedArgReg(const SDValue &N) {
4570 if (N.getOpcode() != ISD::TRUNCATE)
4571 return 0;
4572
4573 const SDValue &Ext = N.getOperand(0);
Stephen Lin6d715e82013-07-06 21:44:25 +00004574 if (Ext.getOpcode() == ISD::AssertZext ||
4575 Ext.getOpcode() == ISD::AssertSext) {
Devang Patel8e60ff12011-05-16 21:24:05 +00004576 const SDValue &CFR = Ext.getOperand(0);
4577 if (CFR.getOpcode() == ISD::CopyFromReg)
4578 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
Craig Topper692d5842012-04-11 04:55:51 +00004579 if (CFR.getOpcode() == ISD::TRUNCATE)
4580 return getTruncatedArgReg(CFR);
Devang Patel8e60ff12011-05-16 21:24:05 +00004581 }
4582 return 0;
4583}
4584
Evan Cheng6e822452010-04-28 23:08:54 +00004585/// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4586/// argument, create the corresponding DBG_VALUE machine instruction for it now.
4587/// At the end of instruction selection, they will be inserted to the entry BB.
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004588bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V,
4589 MDNode *Variable,
4590 MDNode *Expr, int64_t Offset,
4591 bool IsIndirect,
4592 const SDValue &N) {
Devang Patel86ec8b32010-08-31 22:22:42 +00004593 const Argument *Arg = dyn_cast<Argument>(V);
4594 if (!Arg)
Evan Cheng5fb45a22010-04-29 01:40:30 +00004595 return false;
Evan Cheng6e822452010-04-28 23:08:54 +00004596
Devang Patel03955532010-04-29 20:40:36 +00004597 MachineFunction &MF = DAG.getMachineFunction();
Eric Christopherfc6de422014-08-05 02:39:49 +00004598 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
Devang Patel94f2a252010-11-02 17:01:30 +00004599
Devang Patela46953d2010-04-29 18:50:36 +00004600 // Ignore inlined function arguments here.
4601 DIVariable DV(Variable);
Devang Patel03955532010-04-29 20:40:36 +00004602 if (DV.isInlinedFnArgument(MF.getFunction()))
Devang Patela46953d2010-04-29 18:50:36 +00004603 return false;
4604
David Blaikie0252265b2013-06-16 20:34:15 +00004605 Optional<MachineOperand> Op;
Devang Patel9d904e12011-09-08 22:59:09 +00004606 // Some arguments' frame index is recorded during argument lowering.
David Blaikie0252265b2013-06-16 20:34:15 +00004607 if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
4608 Op = MachineOperand::CreateFI(FI);
Devang Patel86ec8b32010-08-31 22:22:42 +00004609
David Blaikie0252265b2013-06-16 20:34:15 +00004610 if (!Op && N.getNode()) {
4611 unsigned Reg;
Devang Patel8e60ff12011-05-16 21:24:05 +00004612 if (N.getOpcode() == ISD::CopyFromReg)
4613 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4614 else
4615 Reg = getTruncatedArgReg(N);
4616 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
Evan Cheng6e822452010-04-28 23:08:54 +00004617 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4618 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4619 if (PR)
4620 Reg = PR;
4621 }
David Blaikie0252265b2013-06-16 20:34:15 +00004622 if (Reg)
4623 Op = MachineOperand::CreateReg(Reg, false);
Evan Cheng6e822452010-04-28 23:08:54 +00004624 }
4625
David Blaikie0252265b2013-06-16 20:34:15 +00004626 if (!Op) {
Devang Patel94f2a252010-11-02 17:01:30 +00004627 // Check if ValueMap has reg number.
Evan Cheng923679f2010-04-29 06:33:38 +00004628 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
Devang Patelbc741402010-11-02 17:19:03 +00004629 if (VMI != FuncInfo.ValueMap.end())
David Blaikie0252265b2013-06-16 20:34:15 +00004630 Op = MachineOperand::CreateReg(VMI->second, false);
Evan Cheng923679f2010-04-29 06:33:38 +00004631 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004632
David Blaikie0252265b2013-06-16 20:34:15 +00004633 if (!Op && N.getNode())
Devang Patel94f2a252010-11-02 17:01:30 +00004634 // Check if frame index is available.
4635 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
Wesley Peck527da1b2010-11-23 03:31:01 +00004636 if (FrameIndexSDNode *FINode =
David Blaikie0252265b2013-06-16 20:34:15 +00004637 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4638 Op = MachineOperand::CreateFI(FINode->getIndex());
Devang Patelbc741402010-11-02 17:19:03 +00004639
David Blaikie0252265b2013-06-16 20:34:15 +00004640 if (!Op)
Devang Patelbc741402010-11-02 17:19:03 +00004641 return false;
Devang Patel94f2a252010-11-02 17:01:30 +00004642
David Blaikie0252265b2013-06-16 20:34:15 +00004643 if (Op->isReg())
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004644 FuncInfo.ArgDbgValues.push_back(
4645 BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE),
4646 IsIndirect, Op->getReg(), Offset, Variable, Expr));
Adrian Prantl418d1d12013-07-09 20:28:37 +00004647 else
4648 FuncInfo.ArgDbgValues.push_back(
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004649 BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE))
4650 .addOperand(*Op)
4651 .addImm(Offset)
4652 .addMetadata(Variable)
4653 .addMetadata(Expr));
Adrian Prantl418d1d12013-07-09 20:28:37 +00004654
Evan Cheng5fb45a22010-04-29 01:40:30 +00004655 return true;
Evan Cheng6e822452010-04-28 23:08:54 +00004656}
Chris Lattner39f18e52010-01-01 03:32:16 +00004657
Douglas Gregor6739a892010-05-11 06:17:44 +00004658// VisualStudio defines setjmp as _setjmp
Michael J. Spencerded5f662010-09-24 19:48:47 +00004659#if defined(_MSC_VER) && defined(setjmp) && \
4660 !defined(setjmp_undefined_for_msvc)
4661# pragma push_macro("setjmp")
4662# undef setjmp
4663# define setjmp_undefined_for_msvc
Douglas Gregor6739a892010-05-11 06:17:44 +00004664#endif
4665
Dan Gohman575fad32008-09-03 16:12:24 +00004666/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4667/// we want to emit this as a call to a named external function, return the name
4668/// otherwise lower it and return null.
4669const char *
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004670SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
Eric Christopher58a24612014-10-08 09:50:54 +00004671 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004672 SDLoc sdl = getCurSDLoc();
Dale Johannesendb7c5f62009-01-31 02:22:37 +00004673 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb99b2692009-12-22 00:40:51 +00004674 SDValue Res;
4675
Dan Gohman575fad32008-09-03 16:12:24 +00004676 switch (Intrinsic) {
4677 default:
4678 // By default, turn this into a target intrinsic node.
4679 visitTargetIntrinsic(I, Intrinsic);
Craig Topperc0196b12014-04-14 00:51:57 +00004680 return nullptr;
4681 case Intrinsic::vastart: visitVAStart(I); return nullptr;
4682 case Intrinsic::vaend: visitVAEnd(I); return nullptr;
4683 case Intrinsic::vacopy: visitVACopy(I); return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00004684 case Intrinsic::returnaddress:
Eric Christopher58a24612014-10-08 09:50:54 +00004685 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI.getPointerTy(),
Gabor Greifeba0be72010-06-25 09:38:13 +00004686 getValue(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00004687 return nullptr;
Bill Wendlingc966a732008-09-26 22:10:44 +00004688 case Intrinsic::frameaddress:
Eric Christopher58a24612014-10-08 09:50:54 +00004689 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI.getPointerTy(),
Gabor Greifeba0be72010-06-25 09:38:13 +00004690 getValue(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00004691 return nullptr;
Renato Golinc7aea402014-05-06 16:51:25 +00004692 case Intrinsic::read_register: {
4693 Value *Reg = I.getArgOperand(0);
4694 SDValue RegName = DAG.getMDNode(cast<MDNode>(Reg));
Eric Christopher58a24612014-10-08 09:50:54 +00004695 EVT VT = TLI.getValueType(I.getType());
Renato Golinc7aea402014-05-06 16:51:25 +00004696 setValue(&I, DAG.getNode(ISD::READ_REGISTER, sdl, VT, RegName));
4697 return nullptr;
4698 }
4699 case Intrinsic::write_register: {
4700 Value *Reg = I.getArgOperand(0);
4701 Value *RegValue = I.getArgOperand(1);
4702 SDValue Chain = getValue(RegValue).getOperand(0);
4703 SDValue RegName = DAG.getMDNode(cast<MDNode>(Reg));
4704 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
4705 RegName, getValue(RegValue)));
4706 return nullptr;
4707 }
Dan Gohman575fad32008-09-03 16:12:24 +00004708 case Intrinsic::setjmp:
Eric Christopher58a24612014-10-08 09:50:54 +00004709 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
Dan Gohman575fad32008-09-03 16:12:24 +00004710 case Intrinsic::longjmp:
Eric Christopher58a24612014-10-08 09:50:54 +00004711 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
Chris Lattnerdd708342008-11-21 16:42:48 +00004712 case Intrinsic::memcpy: {
Mon P Wangc576ee92010-04-04 03:10:48 +00004713 // Assert for address < 256 since we support only user defined address
4714 // spaces.
Gabor Greifeba0be72010-06-25 09:38:13 +00004715 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wangc576ee92010-04-04 03:10:48 +00004716 < 256 &&
Gabor Greifeba0be72010-06-25 09:38:13 +00004717 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
Mon P Wangc576ee92010-04-04 03:10:48 +00004718 < 256 &&
4719 "Unknown address space");
Gabor Greifeba0be72010-06-25 09:38:13 +00004720 SDValue Op1 = getValue(I.getArgOperand(0));
4721 SDValue Op2 = getValue(I.getArgOperand(1));
4722 SDValue Op3 = getValue(I.getArgOperand(2));
4723 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
Chandler Carruth05920b182013-02-25 14:20:21 +00004724 if (!Align)
4725 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
Gabor Greifeba0be72010-06-25 09:38:13 +00004726 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004727 DAG.setRoot(DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, false,
Chris Lattner2510de22010-09-21 05:40:29 +00004728 MachinePointerInfo(I.getArgOperand(0)),
4729 MachinePointerInfo(I.getArgOperand(1))));
Craig Topperc0196b12014-04-14 00:51:57 +00004730 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00004731 }
Chris Lattnerdd708342008-11-21 16:42:48 +00004732 case Intrinsic::memset: {
Mon P Wangc576ee92010-04-04 03:10:48 +00004733 // Assert for address < 256 since we support only user defined address
4734 // spaces.
Gabor Greifeba0be72010-06-25 09:38:13 +00004735 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wangc576ee92010-04-04 03:10:48 +00004736 < 256 &&
4737 "Unknown address space");
Gabor Greifeba0be72010-06-25 09:38:13 +00004738 SDValue Op1 = getValue(I.getArgOperand(0));
4739 SDValue Op2 = getValue(I.getArgOperand(1));
4740 SDValue Op3 = getValue(I.getArgOperand(2));
4741 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
Chandler Carruth05920b182013-02-25 14:20:21 +00004742 if (!Align)
4743 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
Gabor Greifeba0be72010-06-25 09:38:13 +00004744 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004745 DAG.setRoot(DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
Chris Lattner2510de22010-09-21 05:40:29 +00004746 MachinePointerInfo(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00004747 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00004748 }
Chris Lattnerdd708342008-11-21 16:42:48 +00004749 case Intrinsic::memmove: {
Mon P Wangc576ee92010-04-04 03:10:48 +00004750 // Assert for address < 256 since we support only user defined address
4751 // spaces.
Gabor Greifeba0be72010-06-25 09:38:13 +00004752 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wangc576ee92010-04-04 03:10:48 +00004753 < 256 &&
Gabor Greifeba0be72010-06-25 09:38:13 +00004754 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
Mon P Wangc576ee92010-04-04 03:10:48 +00004755 < 256 &&
4756 "Unknown address space");
Gabor Greifeba0be72010-06-25 09:38:13 +00004757 SDValue Op1 = getValue(I.getArgOperand(0));
4758 SDValue Op2 = getValue(I.getArgOperand(1));
4759 SDValue Op3 = getValue(I.getArgOperand(2));
4760 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
Chandler Carruth05920b182013-02-25 14:20:21 +00004761 if (!Align)
4762 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
Gabor Greifeba0be72010-06-25 09:38:13 +00004763 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004764 DAG.setRoot(DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
Chris Lattner2510de22010-09-21 05:40:29 +00004765 MachinePointerInfo(I.getArgOperand(0)),
4766 MachinePointerInfo(I.getArgOperand(1))));
Craig Topperc0196b12014-04-14 00:51:57 +00004767 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00004768 }
Bill Wendling65c0fd42009-02-13 02:16:35 +00004769 case Intrinsic::dbg_declare: {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004770 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Devang Pateldf45c7f2009-10-09 22:42:28 +00004771 MDNode *Variable = DI.getVariable();
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004772 MDNode *Expression = DI.getExpression();
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004773 const Value *Address = DI.getAddress();
Manman Ren983a16c2013-06-28 05:43:10 +00004774 DIVariable DIVar(Variable);
4775 assert((!DIVar || DIVar.isVariable()) &&
4776 "Variable in DbgDeclareInst should be either null or a DIVariable.");
4777 if (!Address || !DIVar) {
Eric Christopherbe7a1012012-03-15 21:33:41 +00004778 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00004779 return nullptr;
Eric Christopherbe7a1012012-03-15 21:33:41 +00004780 }
Dale Johannesene0983522010-04-26 20:06:49 +00004781
Devang Patel3bffd522010-09-02 21:29:42 +00004782 // Check if address has undef value.
4783 if (isa<UndefValue>(Address) ||
4784 (Address->use_empty() && !isa<Argument>(Address))) {
Eric Christopher5c452052012-02-23 03:39:39 +00004785 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00004786 return nullptr;
Devang Patel3bffd522010-09-02 21:29:42 +00004787 }
4788
Dale Johannesene0983522010-04-26 20:06:49 +00004789 SDValue &N = NodeMap[Address];
Devang Patel86ec8b32010-08-31 22:22:42 +00004790 if (!N.getNode() && isa<Argument>(Address))
4791 // Check unused arguments map.
4792 N = UnusedArgNodeMap[Address];
Dale Johannesene0983522010-04-26 20:06:49 +00004793 SDDbgValue *SDV;
4794 if (N.getNode()) {
Devang Patel98d3edf2010-09-02 21:02:27 +00004795 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4796 Address = BCI->getOperand(0);
Eric Christopherda970542012-02-24 01:59:08 +00004797 // Parameters are handled specially.
4798 bool isParameter =
4799 (DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable ||
4800 isa<Argument>(Address));
4801
Devang Patel98d3edf2010-09-02 21:02:27 +00004802 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4803
Dale Johannesene0983522010-04-26 20:06:49 +00004804 if (isParameter && !AI) {
4805 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4806 if (FINode)
4807 // Byval parameter. We have a frame index at this point.
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004808 SDV = DAG.getFrameIndexDbgValue(
4809 Variable, Expression, FINode->getIndex(), 0, dl, SDNodeOrder);
Devang Patelc24048a2010-12-06 22:39:26 +00004810 else {
Devang Patel8e60ff12011-05-16 21:24:05 +00004811 // Address is an argument, so try to emit its dbg value using
4812 // virtual register info from the FuncInfo.ValueMap.
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004813 EmitFuncArgumentDbgValue(Address, Variable, Expression, 0, false, N);
Craig Topperc0196b12014-04-14 00:51:57 +00004814 return nullptr;
Devang Patelc24048a2010-12-06 22:39:26 +00004815 }
Dale Johannesene0983522010-04-26 20:06:49 +00004816 } else if (AI)
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004817 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
Adrian Prantl32da8892014-04-25 20:49:25 +00004818 true, 0, dl, SDNodeOrder);
Devang Patelc24048a2010-12-06 22:39:26 +00004819 else {
Dale Johannesene0983522010-04-26 20:06:49 +00004820 // Can't do anything with other non-AI cases yet.
Eric Christopher5c452052012-02-23 03:39:39 +00004821 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Eric Christopherda970542012-02-24 01:59:08 +00004822 DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
4823 DEBUG(Address->dump());
Craig Topperc0196b12014-04-14 00:51:57 +00004824 return nullptr;
Devang Patelc24048a2010-12-06 22:39:26 +00004825 }
Dale Johannesene0983522010-04-26 20:06:49 +00004826 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4827 } else {
Gabor Greif47a3b8c2010-10-01 10:32:19 +00004828 // If Address is an argument then try to emit its dbg value using
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00004829 // virtual register info from the FuncInfo.ValueMap.
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004830 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, 0, false,
4831 N)) {
Devang Patelda25de82010-09-15 14:48:53 +00004832 // If variable is pinned by a alloca in dominating bb then
4833 // use StaticAllocaMap.
4834 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
Devang Patel46b96c42010-09-15 18:13:55 +00004835 if (AI->getParent() != DI.getParent()) {
4836 DenseMap<const AllocaInst*, int>::iterator SI =
4837 FuncInfo.StaticAllocaMap.find(AI);
4838 if (SI != FuncInfo.StaticAllocaMap.end()) {
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004839 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second,
Adrian Prantl32da8892014-04-25 20:49:25 +00004840 0, dl, SDNodeOrder);
Craig Topperc0196b12014-04-14 00:51:57 +00004841 DAG.AddDbgValue(SDV, nullptr, false);
4842 return nullptr;
Devang Patel46b96c42010-09-15 18:13:55 +00004843 }
Devang Patelda25de82010-09-15 14:48:53 +00004844 }
4845 }
Eric Christopher18c6be72012-02-23 03:39:43 +00004846 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Devang Patelea134f52010-08-26 22:53:27 +00004847 }
Dale Johannesene0983522010-04-26 20:06:49 +00004848 }
Craig Topperc0196b12014-04-14 00:51:57 +00004849 return nullptr;
Bill Wendling65c0fd42009-02-13 02:16:35 +00004850 }
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004851 case Intrinsic::dbg_value: {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004852 const DbgValueInst &DI = cast<DbgValueInst>(I);
Manman Ren983a16c2013-06-28 05:43:10 +00004853 DIVariable DIVar(DI.getVariable());
4854 assert((!DIVar || DIVar.isVariable()) &&
4855 "Variable in DbgValueInst should be either null or a DIVariable.");
4856 if (!DIVar)
Craig Topperc0196b12014-04-14 00:51:57 +00004857 return nullptr;
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004858
4859 MDNode *Variable = DI.getVariable();
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004860 MDNode *Expression = DI.getExpression();
Devang Patelf2bce7c2010-03-15 19:15:44 +00004861 uint64_t Offset = DI.getOffset();
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004862 const Value *V = DI.getValue();
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004863 if (!V)
Craig Topperc0196b12014-04-14 00:51:57 +00004864 return nullptr;
Devang Patelf2bce7c2010-03-15 19:15:44 +00004865
Dale Johannesene0983522010-04-26 20:06:49 +00004866 SDDbgValue *SDV;
Devang Patelaab841c2011-08-03 23:13:55 +00004867 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004868 SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl,
4869 SDNodeOrder);
Craig Topperc0196b12014-04-14 00:51:57 +00004870 DAG.AddDbgValue(SDV, nullptr, false);
Devang Patelf2bce7c2010-03-15 19:15:44 +00004871 } else {
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00004872 // Do not use getValue() in here; we don't want to generate code at
4873 // this point if it hasn't been done yet.
Devang Patelb0c76392010-06-01 19:59:01 +00004874 SDValue N = NodeMap[V];
4875 if (!N.getNode() && isa<Argument>(V))
4876 // Check unused arguments map.
4877 N = UnusedArgNodeMap[V];
Dale Johannesene0983522010-04-26 20:06:49 +00004878 if (N.getNode()) {
Adrian Prantl32da8892014-04-25 20:49:25 +00004879 // A dbg.value for an alloca is always indirect.
4880 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
Adrian Prantl87b7eb92014-10-01 18:55:02 +00004881 if (!EmitFuncArgumentDbgValue(V, Variable, Expression, Offset,
4882 IsIndirect, N)) {
4883 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4884 IsIndirect, Offset, dl, SDNodeOrder);
Evan Cheng5fb45a22010-04-29 01:40:30 +00004885 DAG.AddDbgValue(SDV, N.getNode(), false);
4886 }
Devang Patelb7ae3cc2011-02-18 22:43:42 +00004887 } else if (!V->use_empty() ) {
Dale Johannesenbfd4fd72010-07-16 00:02:08 +00004888 // Do not call getValue(V) yet, as we don't want to generate code.
4889 // Remember it for later.
4890 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4891 DanglingDebugInfoMap[V] = DDI;
Devang Patelf2855b12010-08-27 22:25:51 +00004892 } else {
Devang Patelf2bce7c2010-03-15 19:15:44 +00004893 // We may expand this to cover more cases. One case where we have no
Devang Patelc24048a2010-12-06 22:39:26 +00004894 // data available is an unreferenced parameter.
Eric Christopher18c6be72012-02-23 03:39:43 +00004895 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Dale Johannesene0983522010-04-26 20:06:49 +00004896 }
Devang Patelf2bce7c2010-03-15 19:15:44 +00004897 }
4898
4899 // Build a debug info table entry.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004900 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004901 V = BCI->getOperand(0);
Dan Gohmanbcaf6812010-04-15 01:51:59 +00004902 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004903 // Don't handle byval struct arguments or VLAs, for example.
Eric Christopherc1e2dcd2012-03-26 06:10:32 +00004904 if (!AI) {
Eric Christopher24a62982012-03-28 07:34:36 +00004905 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
4906 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00004907 return nullptr;
Eric Christopherc1e2dcd2012-03-26 06:10:32 +00004908 }
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004909 DenseMap<const AllocaInst*, int>::iterator SI =
4910 FuncInfo.StaticAllocaMap.find(AI);
4911 if (SI == FuncInfo.StaticAllocaMap.end())
Craig Topperc0196b12014-04-14 00:51:57 +00004912 return nullptr; // VLAs.
Craig Topperc0196b12014-04-14 00:51:57 +00004913 return nullptr;
Dale Johannesen0b30cfc2010-02-01 19:54:53 +00004914 }
Dan Gohman575fad32008-09-03 16:12:24 +00004915
Duncan Sands8e6ccb62009-10-14 16:11:37 +00004916 case Intrinsic::eh_typeid_for: {
Chris Lattnerfb964e52010-04-05 06:19:28 +00004917 // Find the type id for the given typeinfo.
Reid Kleckner283bc2e2014-11-14 00:35:50 +00004918 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
Chris Lattnerfb964e52010-04-05 06:19:28 +00004919 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4920 Res = DAG.getConstant(TypeID, MVT::i32);
Bill Wendlingb99b2692009-12-22 00:40:51 +00004921 setValue(&I, Res);
Craig Topperc0196b12014-04-14 00:51:57 +00004922 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00004923 }
4924
Anton Korobeynikov45165ed2008-09-08 21:13:56 +00004925 case Intrinsic::eh_return_i32:
4926 case Intrinsic::eh_return_i64:
Chris Lattnerfb964e52010-04-05 06:19:28 +00004927 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004928 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
Chris Lattnerfb964e52010-04-05 06:19:28 +00004929 MVT::Other,
4930 getControlRoot(),
Gabor Greifeba0be72010-06-25 09:38:13 +00004931 getValue(I.getArgOperand(0)),
4932 getValue(I.getArgOperand(1))));
Craig Topperc0196b12014-04-14 00:51:57 +00004933 return nullptr;
Anton Korobeynikov45165ed2008-09-08 21:13:56 +00004934 case Intrinsic::eh_unwind_init:
Chris Lattnerfb964e52010-04-05 06:19:28 +00004935 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
Craig Topperc0196b12014-04-14 00:51:57 +00004936 return nullptr;
Anton Korobeynikov45165ed2008-09-08 21:13:56 +00004937 case Intrinsic::eh_dwarf_cfa: {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004938 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
Eric Christopher58a24612014-10-08 09:50:54 +00004939 TLI.getPointerTy());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004940 SDValue Offset = DAG.getNode(ISD::ADD, sdl,
Tom Stellard838e2342013-08-26 15:06:10 +00004941 CfaArg.getValueType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004942 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
Tom Stellard838e2342013-08-26 15:06:10 +00004943 CfaArg.getValueType()),
Anton Korobeynikov45165ed2008-09-08 21:13:56 +00004944 CfaArg);
Eric Christopher58a24612014-10-08 09:50:54 +00004945 SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl, TLI.getPointerTy(),
4946 DAG.getConstant(0, TLI.getPointerTy()));
Tom Stellard838e2342013-08-26 15:06:10 +00004947 setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
Bill Wendling954cb182010-01-28 21:51:40 +00004948 FA, Offset));
Craig Topperc0196b12014-04-14 00:51:57 +00004949 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00004950 }
Jim Grosbach54c05302010-01-28 01:45:32 +00004951 case Intrinsic::eh_sjlj_callsite: {
Chris Lattnerfb964e52010-04-05 06:19:28 +00004952 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Gabor Greifeba0be72010-06-25 09:38:13 +00004953 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
Jim Grosbach54c05302010-01-28 01:45:32 +00004954 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
Chris Lattnerfb964e52010-04-05 06:19:28 +00004955 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
Jim Grosbach54c05302010-01-28 01:45:32 +00004956
Chris Lattnerfb964e52010-04-05 06:19:28 +00004957 MMI.setCurrentCallSite(CI->getZExtValue());
Craig Topperc0196b12014-04-14 00:51:57 +00004958 return nullptr;
Jim Grosbach54c05302010-01-28 01:45:32 +00004959 }
Bill Wendling66b110f2011-09-28 03:36:43 +00004960 case Intrinsic::eh_sjlj_functioncontext: {
4961 // Get and store the index of the function context.
4962 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
Bill Wendlingbaf39412011-09-28 03:52:41 +00004963 AllocaInst *FnCtx =
4964 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
Bill Wendling66b110f2011-09-28 03:36:43 +00004965 int FI = FuncInfo.StaticAllocaMap[FnCtx];
4966 MFI->setFunctionContextIndex(FI);
Craig Topperc0196b12014-04-14 00:51:57 +00004967 return nullptr;
Bill Wendling66b110f2011-09-28 03:36:43 +00004968 }
Jim Grosbachc98892f2010-05-26 20:22:18 +00004969 case Intrinsic::eh_sjlj_setjmp: {
Bill Wendling7ecfbd92011-10-07 21:25:38 +00004970 SDValue Ops[2];
4971 Ops[0] = getRoot();
4972 Ops[1] = getValue(I.getArgOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004973 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
Craig Topper48d114b2014-04-26 18:35:24 +00004974 DAG.getVTList(MVT::i32, MVT::Other), Ops);
Bill Wendling7ecfbd92011-10-07 21:25:38 +00004975 setValue(&I, Op.getValue(0));
4976 DAG.setRoot(Op.getValue(1));
Craig Topperc0196b12014-04-14 00:51:57 +00004977 return nullptr;
Jim Grosbachc98892f2010-05-26 20:22:18 +00004978 }
Jim Grosbachbd9485d2010-05-22 01:06:18 +00004979 case Intrinsic::eh_sjlj_longjmp: {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004980 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
Jim Grosbachbbdc5d22010-10-19 23:27:08 +00004981 getRoot(), getValue(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00004982 return nullptr;
Jim Grosbachbbdc5d22010-10-19 23:27:08 +00004983 }
Jim Grosbach54c05302010-01-28 01:45:32 +00004984
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00004985 case Intrinsic::masked_load:
4986 visitMaskedLoad(I);
4987 return nullptr;
4988 case Intrinsic::masked_store:
4989 visitMaskedStore(I);
4990 return nullptr;
Dale Johannesendd224d22010-09-30 23:57:10 +00004991 case Intrinsic::x86_mmx_pslli_w:
4992 case Intrinsic::x86_mmx_pslli_d:
4993 case Intrinsic::x86_mmx_pslli_q:
4994 case Intrinsic::x86_mmx_psrli_w:
4995 case Intrinsic::x86_mmx_psrli_d:
4996 case Intrinsic::x86_mmx_psrli_q:
4997 case Intrinsic::x86_mmx_psrai_w:
4998 case Intrinsic::x86_mmx_psrai_d: {
4999 SDValue ShAmt = getValue(I.getArgOperand(1));
5000 if (isa<ConstantSDNode>(ShAmt)) {
5001 visitTargetIntrinsic(I, Intrinsic);
Craig Topperc0196b12014-04-14 00:51:57 +00005002 return nullptr;
Dale Johannesendd224d22010-09-30 23:57:10 +00005003 }
5004 unsigned NewIntrinsic = 0;
5005 EVT ShAmtVT = MVT::v2i32;
5006 switch (Intrinsic) {
5007 case Intrinsic::x86_mmx_pslli_w:
5008 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5009 break;
5010 case Intrinsic::x86_mmx_pslli_d:
5011 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5012 break;
5013 case Intrinsic::x86_mmx_pslli_q:
5014 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5015 break;
5016 case Intrinsic::x86_mmx_psrli_w:
5017 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5018 break;
5019 case Intrinsic::x86_mmx_psrli_d:
5020 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5021 break;
5022 case Intrinsic::x86_mmx_psrli_q:
5023 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5024 break;
5025 case Intrinsic::x86_mmx_psrai_w:
5026 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5027 break;
5028 case Intrinsic::x86_mmx_psrai_d:
5029 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5030 break;
5031 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5032 }
5033
5034 // The vector shift intrinsics with scalars uses 32b shift amounts but
5035 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5036 // to be zero.
5037 // We must do this early because v2i32 is not a legal type.
Dale Johannesendd224d22010-09-30 23:57:10 +00005038 SDValue ShOps[2];
5039 ShOps[0] = ShAmt;
5040 ShOps[1] = DAG.getConstant(0, MVT::i32);
Craig Topper48d114b2014-04-26 18:35:24 +00005041 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps);
Eric Christopher58a24612014-10-08 09:50:54 +00005042 EVT DestVT = TLI.getValueType(I.getType());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005043 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5044 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
Dale Johannesendd224d22010-09-30 23:57:10 +00005045 DAG.getConstant(NewIntrinsic, MVT::i32),
5046 getValue(I.getArgOperand(0)), ShAmt);
5047 setValue(&I, Res);
Craig Topperc0196b12014-04-14 00:51:57 +00005048 return nullptr;
Dale Johannesendd224d22010-09-30 23:57:10 +00005049 }
Pete Cooper682c76b2012-02-24 03:51:49 +00005050 case Intrinsic::x86_avx_vinsertf128_pd_256:
5051 case Intrinsic::x86_avx_vinsertf128_ps_256:
Craig Topperd024cef2012-04-07 22:32:29 +00005052 case Intrinsic::x86_avx_vinsertf128_si_256:
5053 case Intrinsic::x86_avx2_vinserti128: {
Eric Christopher58a24612014-10-08 09:50:54 +00005054 EVT DestVT = TLI.getValueType(I.getType());
5055 EVT ElVT = TLI.getValueType(I.getArgOperand(1)->getType());
Pete Cooper682c76b2012-02-24 03:51:49 +00005056 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue() & 1) *
5057 ElVT.getVectorNumElements();
Eric Christopher58a24612014-10-08 09:50:54 +00005058 Res =
5059 DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, DestVT,
5060 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
5061 DAG.getConstant(Idx, TLI.getVectorIdxTy()));
Craig Topper2db23532012-09-05 05:48:09 +00005062 setValue(&I, Res);
Craig Topperc0196b12014-04-14 00:51:57 +00005063 return nullptr;
Craig Topper2db23532012-09-05 05:48:09 +00005064 }
5065 case Intrinsic::x86_avx_vextractf128_pd_256:
5066 case Intrinsic::x86_avx_vextractf128_ps_256:
5067 case Intrinsic::x86_avx_vextractf128_si_256:
5068 case Intrinsic::x86_avx2_vextracti128: {
Eric Christopher58a24612014-10-08 09:50:54 +00005069 EVT DestVT = TLI.getValueType(I.getType());
Craig Topper2db23532012-09-05 05:48:09 +00005070 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(1))->getZExtValue() & 1) *
5071 DestVT.getVectorNumElements();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005072 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, DestVT,
Craig Topper2db23532012-09-05 05:48:09 +00005073 getValue(I.getArgOperand(0)),
Eric Christopher58a24612014-10-08 09:50:54 +00005074 DAG.getConstant(Idx, TLI.getVectorIdxTy()));
Pete Cooper682c76b2012-02-24 03:51:49 +00005075 setValue(&I, Res);
Craig Topperc0196b12014-04-14 00:51:57 +00005076 return nullptr;
Pete Cooper682c76b2012-02-24 03:51:49 +00005077 }
Mon P Wang58fb9132008-11-10 20:54:11 +00005078 case Intrinsic::convertff:
5079 case Intrinsic::convertfsi:
5080 case Intrinsic::convertfui:
5081 case Intrinsic::convertsif:
5082 case Intrinsic::convertuif:
5083 case Intrinsic::convertss:
5084 case Intrinsic::convertsu:
5085 case Intrinsic::convertus:
5086 case Intrinsic::convertuu: {
5087 ISD::CvtCode Code = ISD::CVT_INVALID;
5088 switch (Intrinsic) {
Craig Topperbc680062012-04-11 04:34:11 +00005089 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
Mon P Wang58fb9132008-11-10 20:54:11 +00005090 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
5091 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
5092 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
5093 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
5094 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
5095 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
5096 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
5097 case Intrinsic::convertus: Code = ISD::CVT_US; break;
5098 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
5099 }
Eric Christopher58a24612014-10-08 09:50:54 +00005100 EVT DestVT = TLI.getValueType(I.getType());
Gabor Greifeba0be72010-06-25 09:38:13 +00005101 const Value *Op1 = I.getArgOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005102 Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
Bill Wendlingb99b2692009-12-22 00:40:51 +00005103 DAG.getValueType(DestVT),
5104 DAG.getValueType(getValue(Op1).getValueType()),
Gabor Greifeba0be72010-06-25 09:38:13 +00005105 getValue(I.getArgOperand(1)),
5106 getValue(I.getArgOperand(2)),
Bill Wendlingb99b2692009-12-22 00:40:51 +00005107 Code);
5108 setValue(&I, Res);
Craig Topperc0196b12014-04-14 00:51:57 +00005109 return nullptr;
Mon P Wang58fb9132008-11-10 20:54:11 +00005110 }
Dan Gohman575fad32008-09-03 16:12:24 +00005111 case Intrinsic::powi:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005112 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
Gabor Greifeba0be72010-06-25 09:38:13 +00005113 getValue(I.getArgOperand(1)), DAG));
Craig Topperc0196b12014-04-14 00:51:57 +00005114 return nullptr;
Dale Johannesenda2d8062008-09-04 00:47:13 +00005115 case Intrinsic::log:
Eric Christopher58a24612014-10-08 09:50:54 +00005116 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
Craig Topperc0196b12014-04-14 00:51:57 +00005117 return nullptr;
Dale Johannesenda2d8062008-09-04 00:47:13 +00005118 case Intrinsic::log2:
Eric Christopher58a24612014-10-08 09:50:54 +00005119 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
Craig Topperc0196b12014-04-14 00:51:57 +00005120 return nullptr;
Dale Johannesenda2d8062008-09-04 00:47:13 +00005121 case Intrinsic::log10:
Eric Christopher58a24612014-10-08 09:50:54 +00005122 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
Craig Topperc0196b12014-04-14 00:51:57 +00005123 return nullptr;
Dale Johannesenda2d8062008-09-04 00:47:13 +00005124 case Intrinsic::exp:
Eric Christopher58a24612014-10-08 09:50:54 +00005125 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
Craig Topperc0196b12014-04-14 00:51:57 +00005126 return nullptr;
Dale Johannesenda2d8062008-09-04 00:47:13 +00005127 case Intrinsic::exp2:
Eric Christopher58a24612014-10-08 09:50:54 +00005128 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
Craig Topperc0196b12014-04-14 00:51:57 +00005129 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005130 case Intrinsic::pow:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005131 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
Eric Christopher58a24612014-10-08 09:50:54 +00005132 getValue(I.getArgOperand(1)), DAG, TLI));
Craig Topperc0196b12014-04-14 00:51:57 +00005133 return nullptr;
Craig Topperae894262012-11-16 07:48:23 +00005134 case Intrinsic::sqrt:
Peter Collingbourne913869b2012-05-28 21:48:37 +00005135 case Intrinsic::fabs:
Craig Topperae894262012-11-16 07:48:23 +00005136 case Intrinsic::sin:
5137 case Intrinsic::cos:
Dan Gohman0b3d7822012-07-26 17:43:27 +00005138 case Intrinsic::floor:
Craig Topper61d04572012-11-15 06:51:10 +00005139 case Intrinsic::ceil:
Craig Topper61d04572012-11-15 06:51:10 +00005140 case Intrinsic::trunc:
Craig Topper61d04572012-11-15 06:51:10 +00005141 case Intrinsic::rint:
Hal Finkel171817e2013-08-07 22:49:12 +00005142 case Intrinsic::nearbyint:
5143 case Intrinsic::round: {
Craig Topperae894262012-11-16 07:48:23 +00005144 unsigned Opcode;
5145 switch (Intrinsic) {
5146 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5147 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
5148 case Intrinsic::fabs: Opcode = ISD::FABS; break;
5149 case Intrinsic::sin: Opcode = ISD::FSIN; break;
5150 case Intrinsic::cos: Opcode = ISD::FCOS; break;
5151 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
5152 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
5153 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
5154 case Intrinsic::rint: Opcode = ISD::FRINT; break;
5155 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
Hal Finkel171817e2013-08-07 22:49:12 +00005156 case Intrinsic::round: Opcode = ISD::FROUND; break;
Craig Topperae894262012-11-16 07:48:23 +00005157 }
5158
Andrew Trickef9de2a2013-05-25 02:42:55 +00005159 setValue(&I, DAG.getNode(Opcode, sdl,
Craig Topper61d04572012-11-15 06:51:10 +00005160 getValue(I.getArgOperand(0)).getValueType(),
5161 getValue(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00005162 return nullptr;
Craig Topperae894262012-11-16 07:48:23 +00005163 }
Matt Arsenault7c936902014-10-21 23:01:01 +00005164 case Intrinsic::minnum:
5165 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
5166 getValue(I.getArgOperand(0)).getValueType(),
5167 getValue(I.getArgOperand(0)),
5168 getValue(I.getArgOperand(1))));
5169 return nullptr;
5170 case Intrinsic::maxnum:
5171 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
5172 getValue(I.getArgOperand(0)).getValueType(),
5173 getValue(I.getArgOperand(0)),
5174 getValue(I.getArgOperand(1))));
5175 return nullptr;
Hal Finkel0c5c01aa2013-08-19 23:35:46 +00005176 case Intrinsic::copysign:
5177 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5178 getValue(I.getArgOperand(0)).getValueType(),
5179 getValue(I.getArgOperand(0)),
5180 getValue(I.getArgOperand(1))));
Craig Topperc0196b12014-04-14 00:51:57 +00005181 return nullptr;
Cameron Zwarichf03fa182011-07-08 21:39:21 +00005182 case Intrinsic::fma:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005183 setValue(&I, DAG.getNode(ISD::FMA, sdl,
Cameron Zwarichf03fa182011-07-08 21:39:21 +00005184 getValue(I.getArgOperand(0)).getValueType(),
5185 getValue(I.getArgOperand(0)),
5186 getValue(I.getArgOperand(1)),
5187 getValue(I.getArgOperand(2))));
Craig Topperc0196b12014-04-14 00:51:57 +00005188 return nullptr;
Lang Hamesa59100c2012-06-05 19:07:46 +00005189 case Intrinsic::fmuladd: {
Eric Christopher58a24612014-10-08 09:50:54 +00005190 EVT VT = TLI.getValueType(I.getType());
Lang Hamesb8650f12012-06-22 01:09:09 +00005191 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
Eric Christopher58a24612014-10-08 09:50:54 +00005192 TLI.isFMAFasterThanFMulAndFAdd(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005193 setValue(&I, DAG.getNode(ISD::FMA, sdl,
Lang Hamesa59100c2012-06-05 19:07:46 +00005194 getValue(I.getArgOperand(0)).getValueType(),
5195 getValue(I.getArgOperand(0)),
5196 getValue(I.getArgOperand(1)),
5197 getValue(I.getArgOperand(2))));
5198 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005199 SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
Lang Hamesa59100c2012-06-05 19:07:46 +00005200 getValue(I.getArgOperand(0)).getValueType(),
5201 getValue(I.getArgOperand(0)),
5202 getValue(I.getArgOperand(1)));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005203 SDValue Add = DAG.getNode(ISD::FADD, sdl,
Lang Hamesa59100c2012-06-05 19:07:46 +00005204 getValue(I.getArgOperand(0)).getValueType(),
5205 Mul,
5206 getValue(I.getArgOperand(2)));
5207 setValue(&I, Add);
5208 }
Craig Topperc0196b12014-04-14 00:51:57 +00005209 return nullptr;
Lang Hamesa59100c2012-06-05 19:07:46 +00005210 }
Anton Korobeynikov39ed49d2010-03-14 18:42:15 +00005211 case Intrinsic::convert_to_fp16:
Tim Northoverf7a02c12014-07-21 09:13:56 +00005212 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5213 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5214 getValue(I.getArgOperand(0)),
5215 DAG.getTargetConstant(0, MVT::i32))));
Craig Topperc0196b12014-04-14 00:51:57 +00005216 return nullptr;
Anton Korobeynikov39ed49d2010-03-14 18:42:15 +00005217 case Intrinsic::convert_from_fp16:
Tim Northoverfd7e4242014-07-17 10:51:23 +00005218 setValue(&I,
Eric Christopher58a24612014-10-08 09:50:54 +00005219 DAG.getNode(ISD::FP_EXTEND, sdl, TLI.getValueType(I.getType()),
Tim Northoverf7a02c12014-07-21 09:13:56 +00005220 DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5221 getValue(I.getArgOperand(0)))));
Craig Topperc0196b12014-04-14 00:51:57 +00005222 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005223 case Intrinsic::pcmarker: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005224 SDValue Tmp = getValue(I.getArgOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005225 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
Craig Topperc0196b12014-04-14 00:51:57 +00005226 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005227 }
5228 case Intrinsic::readcyclecounter: {
5229 SDValue Op = getRoot();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005230 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
Craig Topper48d114b2014-04-26 18:35:24 +00005231 DAG.getVTList(MVT::i64, MVT::Other), Op);
Bill Wendlingb99b2692009-12-22 00:40:51 +00005232 setValue(&I, Res);
5233 DAG.setRoot(Res.getValue(1));
Craig Topperc0196b12014-04-14 00:51:57 +00005234 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005235 }
Dan Gohman575fad32008-09-03 16:12:24 +00005236 case Intrinsic::bswap:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005237 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
Gabor Greifeba0be72010-06-25 09:38:13 +00005238 getValue(I.getArgOperand(0)).getValueType(),
5239 getValue(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00005240 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005241 case Intrinsic::cttz: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005242 SDValue Arg = getValue(I.getArgOperand(0));
Chandler Carruth637cc6a2011-12-13 01:56:10 +00005243 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
Owen Anderson53aa7a92009-08-10 22:56:29 +00005244 EVT Ty = Arg.getValueType();
Chandler Carruth637cc6a2011-12-13 01:56:10 +00005245 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005246 sdl, Ty, Arg));
Craig Topperc0196b12014-04-14 00:51:57 +00005247 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005248 }
5249 case Intrinsic::ctlz: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005250 SDValue Arg = getValue(I.getArgOperand(0));
Chandler Carruth637cc6a2011-12-13 01:56:10 +00005251 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
Owen Anderson53aa7a92009-08-10 22:56:29 +00005252 EVT Ty = Arg.getValueType();
Chandler Carruth637cc6a2011-12-13 01:56:10 +00005253 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005254 sdl, Ty, Arg));
Craig Topperc0196b12014-04-14 00:51:57 +00005255 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005256 }
5257 case Intrinsic::ctpop: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005258 SDValue Arg = getValue(I.getArgOperand(0));
Owen Anderson53aa7a92009-08-10 22:56:29 +00005259 EVT Ty = Arg.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005260 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
Craig Topperc0196b12014-04-14 00:51:57 +00005261 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005262 }
5263 case Intrinsic::stacksave: {
5264 SDValue Op = getRoot();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005265 Res = DAG.getNode(ISD::STACKSAVE, sdl,
Eric Christopher58a24612014-10-08 09:50:54 +00005266 DAG.getVTList(TLI.getPointerTy(), MVT::Other), Op);
Bill Wendlingb99b2692009-12-22 00:40:51 +00005267 setValue(&I, Res);
5268 DAG.setRoot(Res.getValue(1));
Craig Topperc0196b12014-04-14 00:51:57 +00005269 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005270 }
5271 case Intrinsic::stackrestore: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005272 Res = getValue(I.getArgOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005273 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
Craig Topperc0196b12014-04-14 00:51:57 +00005274 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005275 }
Bill Wendling13020d22008-11-18 11:01:33 +00005276 case Intrinsic::stackprotector: {
Bill Wendlingd970ea32008-11-06 02:29:10 +00005277 // Emit code into the DAG to store the stack guard onto the stack.
5278 MachineFunction &MF = DAG.getMachineFunction();
5279 MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopher58a24612014-10-08 09:50:54 +00005280 EVT PtrTy = TLI.getPointerTy();
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00005281 SDValue Src, Chain = getRoot();
Akira Hatanaka5acc58f2014-08-07 23:08:24 +00005282 const Value *Ptr = cast<LoadInst>(I.getArgOperand(0))->getPointerOperand();
5283 const GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr);
Bill Wendlingd970ea32008-11-06 02:29:10 +00005284
Akira Hatanaka5acc58f2014-08-07 23:08:24 +00005285 // See if Ptr is a bitcast. If it is, look through it and see if we can get
5286 // global variable __stack_chk_guard.
5287 if (!GV)
5288 if (const Operator *BC = dyn_cast<Operator>(Ptr))
5289 if (BC->getOpcode() == Instruction::BitCast)
5290 GV = dyn_cast<GlobalVariable>(BC->getOperand(0));
5291
Eric Christopher58a24612014-10-08 09:50:54 +00005292 if (GV && TLI.useLoadStackGuardNode()) {
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00005293 // Emit a LOAD_STACK_GUARD node.
5294 MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD,
5295 sdl, PtrTy, Chain);
Akira Hatanaka5acc58f2014-08-07 23:08:24 +00005296 MachinePointerInfo MPInfo(GV);
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00005297 MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
5298 unsigned Flags = MachineMemOperand::MOLoad |
5299 MachineMemOperand::MOInvariant;
5300 *MemRefs = MF.getMachineMemOperand(MPInfo, Flags,
5301 PtrTy.getSizeInBits() / 8,
5302 DAG.getEVTAlignment(PtrTy));
5303 Node->setMemRefs(MemRefs, MemRefs + 1);
5304
5305 // Copy the guard value to a virtual register so that it can be
5306 // retrieved in the epilogue.
5307 Src = SDValue(Node, 0);
5308 const TargetRegisterClass *RC =
Eric Christopher58a24612014-10-08 09:50:54 +00005309 TLI.getRegClassFor(Src.getSimpleValueType());
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00005310 unsigned Reg = MF.getRegInfo().createVirtualRegister(RC);
5311
5312 SPDescriptor.setGuardReg(Reg);
5313 Chain = DAG.getCopyToReg(Chain, sdl, Reg, Src);
5314 } else {
5315 Src = getValue(I.getArgOperand(0)); // The guard's value.
5316 }
5317
Gabor Greifeba0be72010-06-25 09:38:13 +00005318 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
Bill Wendlingd970ea32008-11-06 02:29:10 +00005319
Bill Wendlingeb4268d2008-11-07 01:23:58 +00005320 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingd970ea32008-11-06 02:29:10 +00005321 MFI->setStackProtectorIndex(FI);
5322
5323 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5324
5325 // Store the stack protector onto the stack.
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00005326 Res = DAG.getStore(Chain, sdl, Src, FIN,
Chris Lattnera4f19972010-09-21 18:58:22 +00005327 MachinePointerInfo::getFixedStack(FI),
5328 true, false, 0);
Bill Wendlingb99b2692009-12-22 00:40:51 +00005329 setValue(&I, Res);
5330 DAG.setRoot(Res);
Craig Topperc0196b12014-04-14 00:51:57 +00005331 return nullptr;
Bill Wendlingd970ea32008-11-06 02:29:10 +00005332 }
Eric Christopher7a50b282009-10-27 00:52:25 +00005333 case Intrinsic::objectsize: {
5334 // If we don't know by now, we're never going to know.
Gabor Greifeba0be72010-06-25 09:38:13 +00005335 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
Eric Christopher7a50b282009-10-27 00:52:25 +00005336
5337 assert(CI && "Non-constant type in __builtin_object_size?");
5338
Gabor Greifeba0be72010-06-25 09:38:13 +00005339 SDValue Arg = getValue(I.getCalledValue());
Eric Christopher1fd4c572009-10-28 21:32:16 +00005340 EVT Ty = Arg.getValueType();
5341
Dan Gohmanf1d83042010-06-18 14:22:04 +00005342 if (CI->isZero())
Bill Wendlingb99b2692009-12-22 00:40:51 +00005343 Res = DAG.getConstant(-1ULL, Ty);
Eric Christopher7a50b282009-10-27 00:52:25 +00005344 else
Bill Wendlingb99b2692009-12-22 00:40:51 +00005345 Res = DAG.getConstant(0, Ty);
5346
5347 setValue(&I, Res);
Craig Topperc0196b12014-04-14 00:51:57 +00005348 return nullptr;
Eric Christopher7a50b282009-10-27 00:52:25 +00005349 }
Justin Holewinskifff1f5f2013-05-21 14:37:16 +00005350 case Intrinsic::annotation:
5351 case Intrinsic::ptr_annotation:
5352 // Drop the intrinsic, but forward the value
5353 setValue(&I, getValue(I.getOperand(0)));
Craig Topperc0196b12014-04-14 00:51:57 +00005354 return nullptr;
Hal Finkel93046912014-07-25 21:13:35 +00005355 case Intrinsic::assume:
Dan Gohman575fad32008-09-03 16:12:24 +00005356 case Intrinsic::var_annotation:
Hal Finkel93046912014-07-25 21:13:35 +00005357 // Discard annotate attributes and assumptions
Craig Topperc0196b12014-04-14 00:51:57 +00005358 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005359
5360 case Intrinsic::init_trampoline: {
Gabor Greifeba0be72010-06-25 09:38:13 +00005361 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
Dan Gohman575fad32008-09-03 16:12:24 +00005362
5363 SDValue Ops[6];
5364 Ops[0] = getRoot();
Gabor Greifeba0be72010-06-25 09:38:13 +00005365 Ops[1] = getValue(I.getArgOperand(0));
5366 Ops[2] = getValue(I.getArgOperand(1));
5367 Ops[3] = getValue(I.getArgOperand(2));
5368 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
Dan Gohman575fad32008-09-03 16:12:24 +00005369 Ops[5] = DAG.getSrcValue(F);
5370
Craig Topper48d114b2014-04-26 18:35:24 +00005371 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
Dan Gohman575fad32008-09-03 16:12:24 +00005372
Duncan Sandsa0984362011-09-06 13:37:06 +00005373 DAG.setRoot(Res);
Craig Topperc0196b12014-04-14 00:51:57 +00005374 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00005375 }
5376 case Intrinsic::adjust_trampoline: {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005377 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
Eric Christopher58a24612014-10-08 09:50:54 +00005378 TLI.getPointerTy(),
Duncan Sandsa0984362011-09-06 13:37:06 +00005379 getValue(I.getArgOperand(0))));
Craig Topperc0196b12014-04-14 00:51:57 +00005380 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005381 }
Dan Gohman575fad32008-09-03 16:12:24 +00005382 case Intrinsic::gcroot:
5383 if (GFI) {
Bill Wendlingb6b50c62012-05-01 22:50:45 +00005384 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
Gabor Greifeba0be72010-06-25 09:38:13 +00005385 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00005386
Dan Gohman575fad32008-09-03 16:12:24 +00005387 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5388 GFI->addStackRoot(FI->getIndex(), TypeMap);
5389 }
Craig Topperc0196b12014-04-14 00:51:57 +00005390 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005391 case Intrinsic::gcread:
5392 case Intrinsic::gcwrite:
Torok Edwinfbcc6632009-07-14 16:55:14 +00005393 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
Bill Wendlingb99b2692009-12-22 00:40:51 +00005394 case Intrinsic::flt_rounds:
Andrew Trickef9de2a2013-05-25 02:42:55 +00005395 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
Craig Topperc0196b12014-04-14 00:51:57 +00005396 return nullptr;
Jakub Staszak3f158fd2011-07-06 18:22:43 +00005397
5398 case Intrinsic::expect: {
5399 // Just replace __builtin_expect(exp, c) with EXP.
5400 setValue(&I, getValue(I.getArgOperand(0)));
Craig Topperc0196b12014-04-14 00:51:57 +00005401 return nullptr;
Jakub Staszak3f158fd2011-07-06 18:22:43 +00005402 }
5403
Shuxin Yangcdde0592012-10-19 20:11:16 +00005404 case Intrinsic::debugtrap:
Evan Cheng74d92c12011-04-08 21:37:21 +00005405 case Intrinsic::trap: {
Nick Lewycky50f02cb2011-12-02 22:16:29 +00005406 StringRef TrapFuncName = TM.Options.getTrapFunctionName();
Evan Cheng74d92c12011-04-08 21:37:21 +00005407 if (TrapFuncName.empty()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00005408 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
Shuxin Yangcdde0592012-10-19 20:11:16 +00005409 ISD::TRAP : ISD::DEBUGTRAP;
Andrew Trickef9de2a2013-05-25 02:42:55 +00005410 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
Craig Topperc0196b12014-04-14 00:51:57 +00005411 return nullptr;
Evan Cheng74d92c12011-04-08 21:37:21 +00005412 }
5413 TargetLowering::ArgListTy Args;
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +00005414
5415 TargetLowering::CallLoweringInfo CLI(DAG);
5416 CLI.setDebugLoc(sdl).setChain(getRoot())
5417 .setCallee(CallingConv::C, I.getType(),
Eric Christopher58a24612014-10-08 09:50:54 +00005418 DAG.getExternalSymbol(TrapFuncName.data(), TLI.getPointerTy()),
Juergen Ributzka3bd03c72014-07-01 22:01:54 +00005419 std::move(Args), 0);
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +00005420
Eric Christopher58a24612014-10-08 09:50:54 +00005421 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
Evan Cheng74d92c12011-04-08 21:37:21 +00005422 DAG.setRoot(Result.second);
Craig Topperc0196b12014-04-14 00:51:57 +00005423 return nullptr;
Evan Cheng74d92c12011-04-08 21:37:21 +00005424 }
Shuxin Yangcdde0592012-10-19 20:11:16 +00005425
Bill Wendling5eee7442008-11-21 02:38:44 +00005426 case Intrinsic::uadd_with_overflow:
Bill Wendlingdb8ec2d2008-12-09 22:08:41 +00005427 case Intrinsic::sadd_with_overflow:
Bill Wendlingdb8ec2d2008-12-09 22:08:41 +00005428 case Intrinsic::usub_with_overflow:
Bill Wendlingdb8ec2d2008-12-09 22:08:41 +00005429 case Intrinsic::ssub_with_overflow:
Bill Wendlingdb8ec2d2008-12-09 22:08:41 +00005430 case Intrinsic::umul_with_overflow:
Craig Topperbc680062012-04-11 04:34:11 +00005431 case Intrinsic::smul_with_overflow: {
5432 ISD::NodeType Op;
5433 switch (Intrinsic) {
5434 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5435 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5436 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5437 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5438 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5439 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5440 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5441 }
5442 SDValue Op1 = getValue(I.getArgOperand(0));
5443 SDValue Op2 = getValue(I.getArgOperand(1));
Bill Wendling74296c62008-11-21 02:03:52 +00005444
Craig Topperbc680062012-04-11 04:34:11 +00005445 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005446 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
Craig Topperc0196b12014-04-14 00:51:57 +00005447 return nullptr;
Craig Topperbc680062012-04-11 04:34:11 +00005448 }
Dan Gohman575fad32008-09-03 16:12:24 +00005449 case Intrinsic::prefetch: {
Bruno Cardoso Lopesdc9ff3a2011-06-14 04:58:37 +00005450 SDValue Ops[5];
Dale Johannesene660f4d2010-10-26 23:11:10 +00005451 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
Dan Gohman575fad32008-09-03 16:12:24 +00005452 Ops[0] = getRoot();
Gabor Greifeba0be72010-06-25 09:38:13 +00005453 Ops[1] = getValue(I.getArgOperand(0));
5454 Ops[2] = getValue(I.getArgOperand(1));
5455 Ops[3] = getValue(I.getArgOperand(2));
Bruno Cardoso Lopesdc9ff3a2011-06-14 04:58:37 +00005456 Ops[4] = getValue(I.getArgOperand(3));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005457 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
Craig Topper206fcd42014-04-26 19:29:41 +00005458 DAG.getVTList(MVT::Other), Ops,
Dale Johannesene660f4d2010-10-26 23:11:10 +00005459 EVT::getIntegerVT(*Context, 8),
5460 MachinePointerInfo(I.getArgOperand(0)),
5461 0, /* align */
5462 false, /* volatile */
5463 rw==0, /* read */
5464 rw==1)); /* write */
Craig Topperc0196b12014-04-14 00:51:57 +00005465 return nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005466 }
Duncan Sandsdca0c282009-11-10 09:08:09 +00005467 case Intrinsic::lifetime_start:
Nadav Rotem7c277da2012-09-06 09:17:37 +00005468 case Intrinsic::lifetime_end: {
Nadav Rotem7c277da2012-09-06 09:17:37 +00005469 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
Nadav Rotemd753a952012-09-10 08:43:23 +00005470 // Stack coloring is not enabled in O0, discard region information.
5471 if (TM.getOptLevel() == CodeGenOpt::None)
Craig Topperc0196b12014-04-14 00:51:57 +00005472 return nullptr;
Nadav Rotem7c277da2012-09-06 09:17:37 +00005473
Nadav Rotemd753a952012-09-10 08:43:23 +00005474 SmallVector<Value *, 4> Allocas;
Rafael Espindola5f57f462014-02-21 18:34:28 +00005475 GetUnderlyingObjects(I.getArgOperand(1), Allocas, DL);
Nadav Rotemd753a952012-09-10 08:43:23 +00005476
Craig Toppere1c1d362013-07-03 05:11:49 +00005477 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5478 E = Allocas.end(); Object != E; ++Object) {
Nadav Rotemd753a952012-09-10 08:43:23 +00005479 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5480
5481 // Could not find an Alloca.
5482 if (!LifetimeObject)
5483 continue;
5484
Pete Cooper230332f2014-10-17 22:59:33 +00005485 // First check that the Alloca is static, otherwise it won't have a
5486 // valid frame index.
5487 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
5488 if (SI == FuncInfo.StaticAllocaMap.end())
5489 return nullptr;
5490
5491 int FI = SI->second;
Nadav Rotemd753a952012-09-10 08:43:23 +00005492
5493 SDValue Ops[2];
5494 Ops[0] = getRoot();
Eric Christopher58a24612014-10-08 09:50:54 +00005495 Ops[1] = DAG.getFrameIndex(FI, TLI.getPointerTy(), true);
Nadav Rotemd753a952012-09-10 08:43:23 +00005496 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5497
Craig Topper48d114b2014-04-26 18:35:24 +00005498 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
Nadav Rotemd753a952012-09-10 08:43:23 +00005499 DAG.setRoot(Res);
5500 }
Craig Topperc0196b12014-04-14 00:51:57 +00005501 return nullptr;
Nadav Rotem7c277da2012-09-06 09:17:37 +00005502 }
5503 case Intrinsic::invariant_start:
Duncan Sandsdca0c282009-11-10 09:08:09 +00005504 // Discard region information.
Eric Christopher58a24612014-10-08 09:50:54 +00005505 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
Craig Topperc0196b12014-04-14 00:51:57 +00005506 return nullptr;
Duncan Sandsdca0c282009-11-10 09:08:09 +00005507 case Intrinsic::invariant_end:
Duncan Sandsdca0c282009-11-10 09:08:09 +00005508 // Discard region information.
Craig Topperc0196b12014-04-14 00:51:57 +00005509 return nullptr;
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00005510 case Intrinsic::stackprotectorcheck: {
5511 // Do not actually emit anything for this basic block. Instead we initialize
5512 // the stack protector descriptor and export the guard variable so we can
5513 // access it in FinishBasicBlock.
5514 const BasicBlock *BB = I.getParent();
5515 SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
5516 ExportFromCurrentBlock(SPDescriptor.getGuard());
5517
5518 // Flush our exports since we are going to process a terminator.
5519 (void)getControlRoot();
Craig Topperc0196b12014-04-14 00:51:57 +00005520 return nullptr;
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00005521 }
Renato Golinc0a3c1d2014-03-26 12:52:28 +00005522 case Intrinsic::clear_cache:
Eric Christopher58a24612014-10-08 09:50:54 +00005523 return TLI.getClearCacheBuiltinName();
Nuno Lopesec9653b2012-06-28 22:30:12 +00005524 case Intrinsic::donothing:
5525 // ignore
Craig Topperc0196b12014-04-14 00:51:57 +00005526 return nullptr;
Andrew Trick74f4c742013-10-31 17:18:24 +00005527 case Intrinsic::experimental_stackmap: {
5528 visitStackmap(I);
Craig Topperc0196b12014-04-14 00:51:57 +00005529 return nullptr;
Andrew Trick74f4c742013-10-31 17:18:24 +00005530 }
5531 case Intrinsic::experimental_patchpoint_void:
5532 case Intrinsic::experimental_patchpoint_i64: {
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00005533 visitPatchpoint(&I);
Craig Topperc0196b12014-04-14 00:51:57 +00005534 return nullptr;
Andrew Trick74f4c742013-10-31 17:18:24 +00005535 }
Philip Reames1a1bdb22014-12-02 18:50:36 +00005536 case Intrinsic::experimental_gc_statepoint: {
5537 visitStatepoint(I);
5538 return nullptr;
5539 }
5540 case Intrinsic::experimental_gc_result_int:
5541 case Intrinsic::experimental_gc_result_float:
5542 case Intrinsic::experimental_gc_result_ptr: {
5543 visitGCResult(I);
5544 return nullptr;
5545 }
5546 case Intrinsic::experimental_gc_relocate: {
5547 visitGCRelocate(I);
5548 return nullptr;
5549 }
Dan Gohman575fad32008-09-03 16:12:24 +00005550 }
5551}
5552
Juergen Ributzkafd4633e2014-10-16 21:26:35 +00005553std::pair<SDValue, SDValue>
5554SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
5555 MachineBasicBlock *LandingPad) {
Chris Lattnerfb964e52010-04-05 06:19:28 +00005556 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Craig Topperc0196b12014-04-14 00:51:57 +00005557 MCSymbol *BeginLabel = nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00005558
Chris Lattnerfb964e52010-04-05 06:19:28 +00005559 if (LandingPad) {
Dan Gohman575fad32008-09-03 16:12:24 +00005560 // Insert a label before the invoke call to mark the try range. This can be
5561 // used to detect deletion of the invoke via the MachineModuleInfo.
Chris Lattnerfb964e52010-04-05 06:19:28 +00005562 BeginLabel = MMI.getContext().CreateTempSymbol();
Jim Grosbach693e36a2009-08-11 00:09:57 +00005563
Jim Grosbach54c05302010-01-28 01:45:32 +00005564 // For SjLj, keep track of which landing pads go with which invokes
5565 // so as to maintain the ordering of pads in the LSDA.
Chris Lattnerfb964e52010-04-05 06:19:28 +00005566 unsigned CallSiteIndex = MMI.getCurrentCallSite();
Jim Grosbach54c05302010-01-28 01:45:32 +00005567 if (CallSiteIndex) {
Chris Lattnerfb964e52010-04-05 06:19:28 +00005568 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
Bill Wendling267f3232011-10-05 22:24:35 +00005569 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
Bill Wendling3d11aa72011-10-04 22:00:35 +00005570
Jim Grosbach54c05302010-01-28 01:45:32 +00005571 // Now that the call site is handled, stop tracking it.
Chris Lattnerfb964e52010-04-05 06:19:28 +00005572 MMI.setCurrentCallSite(0);
Jim Grosbach54c05302010-01-28 01:45:32 +00005573 }
5574
Dan Gohman575fad32008-09-03 16:12:24 +00005575 // Both PendingLoads and PendingExports must be flushed here;
5576 // this call might not return.
5577 (void)getRoot();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005578 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
Juergen Ributzkafd4633e2014-10-16 21:26:35 +00005579
5580 CLI.setChain(getRoot());
Dan Gohman575fad32008-09-03 16:12:24 +00005581 }
5582
Juergen Ributzkafd4633e2014-10-16 21:26:35 +00005583 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
5584 std::pair<SDValue, SDValue> Result = TLI->LowerCallTo(CLI);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00005585
Juergen Ributzkafd4633e2014-10-16 21:26:35 +00005586 assert((CLI.IsTailCall || Result.second.getNode()) &&
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00005587 "Non-null chain expected with non-tail call!");
5588 assert((Result.second.getNode() || !Result.first.getNode()) &&
5589 "Null value expected with tail call!");
Bill Wendlinga4d7df72009-12-22 00:50:32 +00005590
Evan Cheng8d68ebd2011-04-01 19:42:22 +00005591 if (!Result.second.getNode()) {
Andrew Trick74f4c742013-10-31 17:18:24 +00005592 // As a special case, a null chain means that a tail call has been emitted
5593 // and the DAG root is already updated.
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00005594 HasTailCall = true;
Tim Northoverdab4db52013-07-06 12:58:45 +00005595
5596 // Since there's no actual continuation from this block, nothing can be
5597 // relying on us setting vregs for them.
5598 PendingExports.clear();
Evan Cheng8d68ebd2011-04-01 19:42:22 +00005599 } else {
5600 DAG.setRoot(Result.second);
Evan Cheng8d68ebd2011-04-01 19:42:22 +00005601 }
Dan Gohman575fad32008-09-03 16:12:24 +00005602
Chris Lattnerfb964e52010-04-05 06:19:28 +00005603 if (LandingPad) {
Dan Gohman575fad32008-09-03 16:12:24 +00005604 // Insert a label at the end of the invoke call to mark the try range. This
5605 // can be used to detect deletion of the invoke via the MachineModuleInfo.
Chris Lattnerfb964e52010-04-05 06:19:28 +00005606 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005607 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
Dan Gohman575fad32008-09-03 16:12:24 +00005608
5609 // Inform MachineModuleInfo of range.
Chris Lattnerfb964e52010-04-05 06:19:28 +00005610 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
Dan Gohman575fad32008-09-03 16:12:24 +00005611 }
Juergen Ributzkafd4633e2014-10-16 21:26:35 +00005612
5613 return Result;
5614}
5615
5616void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
5617 bool isTailCall,
5618 MachineBasicBlock *LandingPad) {
5619 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
5620 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
5621 Type *RetTy = FTy->getReturnType();
5622
5623 TargetLowering::ArgListTy Args;
5624 TargetLowering::ArgListEntry Entry;
5625 Args.reserve(CS.arg_size());
5626
5627 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
5628 i != e; ++i) {
5629 const Value *V = *i;
5630
5631 // Skip empty types
5632 if (V->getType()->isEmptyTy())
5633 continue;
5634
5635 SDValue ArgNode = getValue(V);
5636 Entry.Node = ArgNode; Entry.Ty = V->getType();
5637
5638 // Skip the first return-type Attribute to get to params.
5639 Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
5640 Args.push_back(Entry);
5641 }
5642
5643 // Check if target-independent constraints permit a tail call here.
5644 // Target-dependent constraints are checked within TLI->LowerCallTo.
5645 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
5646 isTailCall = false;
5647
5648 TargetLowering::CallLoweringInfo CLI(DAG);
5649 CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
5650 .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
5651 .setTailCall(isTailCall);
5652 std::pair<SDValue,SDValue> Result = lowerInvokable(CLI, LandingPad);
5653
5654 if (Result.first.getNode())
5655 setValue(CS.getInstruction(), Result.first);
Dan Gohman575fad32008-09-03 16:12:24 +00005656}
5657
Chris Lattner1a32ede2009-12-24 00:37:38 +00005658/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5659/// value is equal or not-equal to zero.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005660static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00005661 for (const User *U : V->users()) {
5662 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
Chris Lattner1a32ede2009-12-24 00:37:38 +00005663 if (IC->isEquality())
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005664 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
Chris Lattner1a32ede2009-12-24 00:37:38 +00005665 if (C->isNullValue())
5666 continue;
5667 // Unknown instruction.
5668 return false;
5669 }
5670 return true;
5671}
5672
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005673static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
Chris Lattner229907c2011-07-18 04:54:35 +00005674 Type *LoadTy,
Chris Lattner1a32ede2009-12-24 00:37:38 +00005675 SelectionDAGBuilder &Builder) {
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005676
Chris Lattner1a32ede2009-12-24 00:37:38 +00005677 // Check to see if this load can be trivially constant folded, e.g. if the
5678 // input is from a string literal.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005679 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
Chris Lattner1a32ede2009-12-24 00:37:38 +00005680 // Cast pointer to the type we really want to load.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005681 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
Chris Lattner1a32ede2009-12-24 00:37:38 +00005682 PointerType::getUnqual(LoadTy));
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005683
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005684 if (const Constant *LoadCst =
5685 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
Rafael Espindola5f57f462014-02-21 18:34:28 +00005686 Builder.DL))
Chris Lattner1a32ede2009-12-24 00:37:38 +00005687 return Builder.getValue(LoadCst);
5688 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005689
Chris Lattner1a32ede2009-12-24 00:37:38 +00005690 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5691 // still constant memory, the input chain can be the entry node.
5692 SDValue Root;
5693 bool ConstantMemory = false;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005694
Chris Lattner1a32ede2009-12-24 00:37:38 +00005695 // Do not serialize (non-volatile) loads of constant memory with anything.
5696 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5697 Root = Builder.DAG.getEntryNode();
5698 ConstantMemory = true;
5699 } else {
5700 // Do not serialize non-volatile loads against each other.
5701 Root = Builder.DAG.getRoot();
5702 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005703
Chris Lattner1a32ede2009-12-24 00:37:38 +00005704 SDValue Ptr = Builder.getValue(PtrVal);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005705 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
Chris Lattner1ffcf522010-09-21 16:36:31 +00005706 Ptr, MachinePointerInfo(PtrVal),
David Greene39c6d012010-02-15 17:00:31 +00005707 false /*volatile*/,
Stephen Lincfe7f352013-07-08 00:37:03 +00005708 false /*nontemporal*/,
Pete Cooper82cd9e82011-11-08 18:42:53 +00005709 false /*isinvariant*/, 1 /* align=1 */);
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005710
Chris Lattner1a32ede2009-12-24 00:37:38 +00005711 if (!ConstantMemory)
5712 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5713 return LoadVal;
5714}
5715
Richard Sandiforde3827752013-08-16 10:55:47 +00005716/// processIntegerCallValue - Record the value for an instruction that
5717/// produces an integer result, converting the type where necessary.
5718void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
5719 SDValue Value,
5720 bool IsSigned) {
Eric Christopher58a24612014-10-08 09:50:54 +00005721 EVT VT = DAG.getTargetLoweringInfo().getValueType(I.getType(), true);
Richard Sandiforde3827752013-08-16 10:55:47 +00005722 if (IsSigned)
5723 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
5724 else
5725 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
5726 setValue(&I, Value);
5727}
Chris Lattner1a32ede2009-12-24 00:37:38 +00005728
5729/// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5730/// If so, return true and lower it, otherwise return false and it will be
5731/// lowered like a normal call.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00005732bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
Chris Lattner1a32ede2009-12-24 00:37:38 +00005733 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
Gabor Greiff69acfe2010-06-30 12:55:46 +00005734 if (I.getNumArgOperands() != 3)
Chris Lattner1a32ede2009-12-24 00:37:38 +00005735 return false;
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005736
Gabor Greifeba0be72010-06-25 09:38:13 +00005737 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
Duncan Sands19d0b472010-02-16 11:11:14 +00005738 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
Gabor Greifeba0be72010-06-25 09:38:13 +00005739 !I.getArgOperand(2)->getType()->isIntegerTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +00005740 !I.getType()->isIntegerTy())
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005741 return false;
5742
Richard Sandiforde3827752013-08-16 10:55:47 +00005743 const Value *Size = I.getArgOperand(2);
5744 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
5745 if (CSize && CSize->getZExtValue() == 0) {
Eric Christopher58a24612014-10-08 09:50:54 +00005746 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(I.getType(), true);
Richard Sandiford564681c2013-08-12 10:28:10 +00005747 setValue(&I, DAG.getConstant(0, CallVT));
5748 return true;
5749 }
5750
Richard Sandiford564681c2013-08-12 10:28:10 +00005751 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5752 std::pair<SDValue, SDValue> Res =
5753 TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
Richard Sandiforde3827752013-08-16 10:55:47 +00005754 getValue(LHS), getValue(RHS), getValue(Size),
5755 MachinePointerInfo(LHS),
5756 MachinePointerInfo(RHS));
Richard Sandiford564681c2013-08-12 10:28:10 +00005757 if (Res.first.getNode()) {
Richard Sandiforde3827752013-08-16 10:55:47 +00005758 processIntegerCallValue(I, Res.first, true);
5759 PendingLoads.push_back(Res.second);
Richard Sandiford564681c2013-08-12 10:28:10 +00005760 return true;
5761 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005762
Chris Lattner1a32ede2009-12-24 00:37:38 +00005763 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5764 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
Richard Sandiforde3827752013-08-16 10:55:47 +00005765 if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005766 bool ActuallyDoIt = true;
5767 MVT LoadVT;
Chris Lattner229907c2011-07-18 04:54:35 +00005768 Type *LoadTy;
Richard Sandiforde3827752013-08-16 10:55:47 +00005769 switch (CSize->getZExtValue()) {
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005770 default:
5771 LoadVT = MVT::Other;
Craig Topperc0196b12014-04-14 00:51:57 +00005772 LoadTy = nullptr;
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005773 ActuallyDoIt = false;
5774 break;
5775 case 2:
5776 LoadVT = MVT::i16;
Richard Sandiforde3827752013-08-16 10:55:47 +00005777 LoadTy = Type::getInt16Ty(CSize->getContext());
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005778 break;
5779 case 4:
5780 LoadVT = MVT::i32;
Richard Sandiforde3827752013-08-16 10:55:47 +00005781 LoadTy = Type::getInt32Ty(CSize->getContext());
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005782 break;
5783 case 8:
5784 LoadVT = MVT::i64;
Richard Sandiforde3827752013-08-16 10:55:47 +00005785 LoadTy = Type::getInt64Ty(CSize->getContext());
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005786 break;
5787 /*
5788 case 16:
5789 LoadVT = MVT::v4i32;
Richard Sandiforde3827752013-08-16 10:55:47 +00005790 LoadTy = Type::getInt32Ty(CSize->getContext());
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005791 LoadTy = VectorType::get(LoadTy, 4);
5792 break;
5793 */
5794 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005795
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005796 // This turns into unaligned loads. We only do this if the target natively
5797 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5798 // we'll only produce a small number of byte loads.
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005799
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005800 // Require that we can find a legal MVT, and only do this if the target
5801 // supports unaligned loads of that type. Expanding into byte loads would
5802 // bloat the code.
Eric Christopher58a24612014-10-08 09:50:54 +00005803 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Richard Sandiforde3827752013-08-16 10:55:47 +00005804 if (ActuallyDoIt && CSize->getZExtValue() > 4) {
Matt Arsenault1b55dd92014-02-05 23:16:05 +00005805 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
5806 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005807 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5808 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
Matt Arsenault6f2a5262014-07-27 17:46:40 +00005809 // TODO: Check alignment of src and dest ptrs.
Eric Christopher58a24612014-10-08 09:50:54 +00005810 if (!TLI.isTypeLegal(LoadVT) ||
5811 !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) ||
5812 !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS))
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005813 ActuallyDoIt = false;
5814 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005815
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005816 if (ActuallyDoIt) {
5817 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5818 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005819
Andrew Trickef9de2a2013-05-25 02:42:55 +00005820 SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005821 ISD::SETNE);
Richard Sandiforde3827752013-08-16 10:55:47 +00005822 processIntegerCallValue(I, Res, false);
Chris Lattnerf5e3ed62009-12-24 01:07:17 +00005823 return true;
5824 }
Chris Lattner1a32ede2009-12-24 00:37:38 +00005825 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00005826
5827
Chris Lattner1a32ede2009-12-24 00:37:38 +00005828 return false;
5829}
5830
Richard Sandiford6f6d5512013-08-20 09:38:48 +00005831/// visitMemChrCall -- See if we can lower a memchr call into an optimized
5832/// form. If so, return true and lower it, otherwise return false and it
5833/// will be lowered like a normal call.
5834bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
5835 // Verify that the prototype makes sense. void *memchr(void *, int, size_t)
5836 if (I.getNumArgOperands() != 3)
5837 return false;
5838
5839 const Value *Src = I.getArgOperand(0);
5840 const Value *Char = I.getArgOperand(1);
5841 const Value *Length = I.getArgOperand(2);
5842 if (!Src->getType()->isPointerTy() ||
5843 !Char->getType()->isIntegerTy() ||
5844 !Length->getType()->isIntegerTy() ||
5845 !I.getType()->isPointerTy())
5846 return false;
5847
5848 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5849 std::pair<SDValue, SDValue> Res =
5850 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
5851 getValue(Src), getValue(Char), getValue(Length),
5852 MachinePointerInfo(Src));
5853 if (Res.first.getNode()) {
5854 setValue(&I, Res.first);
5855 PendingLoads.push_back(Res.second);
5856 return true;
5857 }
5858
5859 return false;
5860}
5861
Richard Sandifordbb83a502013-08-16 11:29:37 +00005862/// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
5863/// optimized form. If so, return true and lower it, otherwise return false
5864/// and it will be lowered like a normal call.
5865bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
5866 // Verify that the prototype makes sense. char *strcpy(char *, char *)
5867 if (I.getNumArgOperands() != 2)
5868 return false;
5869
5870 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5871 if (!Arg0->getType()->isPointerTy() ||
5872 !Arg1->getType()->isPointerTy() ||
5873 !I.getType()->isPointerTy())
5874 return false;
5875
5876 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5877 std::pair<SDValue, SDValue> Res =
5878 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
5879 getValue(Arg0), getValue(Arg1),
5880 MachinePointerInfo(Arg0),
5881 MachinePointerInfo(Arg1), isStpcpy);
5882 if (Res.first.getNode()) {
5883 setValue(&I, Res.first);
5884 DAG.setRoot(Res.second);
5885 return true;
5886 }
5887
5888 return false;
5889}
5890
Richard Sandifordca232712013-08-16 11:21:54 +00005891/// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
5892/// If so, return true and lower it, otherwise return false and it will be
5893/// lowered like a normal call.
5894bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
5895 // Verify that the prototype makes sense. int strcmp(void*,void*)
5896 if (I.getNumArgOperands() != 2)
5897 return false;
5898
5899 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5900 if (!Arg0->getType()->isPointerTy() ||
5901 !Arg1->getType()->isPointerTy() ||
5902 !I.getType()->isIntegerTy())
5903 return false;
5904
5905 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5906 std::pair<SDValue, SDValue> Res =
5907 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5908 getValue(Arg0), getValue(Arg1),
5909 MachinePointerInfo(Arg0),
5910 MachinePointerInfo(Arg1));
5911 if (Res.first.getNode()) {
5912 processIntegerCallValue(I, Res.first, true);
5913 PendingLoads.push_back(Res.second);
5914 return true;
5915 }
5916
5917 return false;
5918}
5919
Richard Sandiford0dec06a2013-08-16 11:41:43 +00005920/// visitStrLenCall -- See if we can lower a strlen call into an optimized
5921/// form. If so, return true and lower it, otherwise return false and it
5922/// will be lowered like a normal call.
5923bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
5924 // Verify that the prototype makes sense. size_t strlen(char *)
5925 if (I.getNumArgOperands() != 1)
5926 return false;
5927
5928 const Value *Arg0 = I.getArgOperand(0);
5929 if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
5930 return false;
5931
5932 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5933 std::pair<SDValue, SDValue> Res =
5934 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
5935 getValue(Arg0), MachinePointerInfo(Arg0));
5936 if (Res.first.getNode()) {
5937 processIntegerCallValue(I, Res.first, false);
5938 PendingLoads.push_back(Res.second);
5939 return true;
5940 }
5941
5942 return false;
5943}
5944
5945/// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
5946/// form. If so, return true and lower it, otherwise return false and it
5947/// will be lowered like a normal call.
5948bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
5949 // Verify that the prototype makes sense. size_t strnlen(char *, size_t)
5950 if (I.getNumArgOperands() != 2)
5951 return false;
5952
5953 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5954 if (!Arg0->getType()->isPointerTy() ||
5955 !Arg1->getType()->isIntegerTy() ||
5956 !I.getType()->isIntegerTy())
5957 return false;
5958
5959 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5960 std::pair<SDValue, SDValue> Res =
5961 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
5962 getValue(Arg0), getValue(Arg1),
5963 MachinePointerInfo(Arg0));
5964 if (Res.first.getNode()) {
5965 processIntegerCallValue(I, Res.first, false);
5966 PendingLoads.push_back(Res.second);
5967 return true;
5968 }
5969
5970 return false;
5971}
5972
Bob Wilson874886c2012-08-03 23:29:17 +00005973/// visitUnaryFloatCall - If a call instruction is a unary floating-point
5974/// operation (as expected), translate it to an SDNode with the specified opcode
5975/// and return true.
5976bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
5977 unsigned Opcode) {
5978 // Sanity check that it really is a unary floating-point call.
5979 if (I.getNumArgOperands() != 1 ||
5980 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5981 I.getType() != I.getArgOperand(0)->getType() ||
5982 !I.onlyReadsMemory())
5983 return false;
5984
5985 SDValue Tmp = getValue(I.getArgOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005986 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
Bob Wilson874886c2012-08-03 23:29:17 +00005987 return true;
5988}
Chris Lattner1a32ede2009-12-24 00:37:38 +00005989
Matt Arsenault4b7bd2d2014-10-24 18:13:10 +00005990/// visitBinaryFloatCall - If a call instruction is a binary floating-point
Matt Arsenault7c936902014-10-21 23:01:01 +00005991/// operation (as expected), translate it to an SDNode with the specified opcode
5992/// and return true.
5993bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
5994 unsigned Opcode) {
Matt Arsenault4b7bd2d2014-10-24 18:13:10 +00005995 // Sanity check that it really is a binary floating-point call.
Matt Arsenault7c936902014-10-21 23:01:01 +00005996 if (I.getNumArgOperands() != 2 ||
5997 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5998 I.getType() != I.getArgOperand(0)->getType() ||
5999 I.getType() != I.getArgOperand(1)->getType() ||
6000 !I.onlyReadsMemory())
6001 return false;
6002
6003 SDValue Tmp0 = getValue(I.getArgOperand(0));
6004 SDValue Tmp1 = getValue(I.getArgOperand(1));
6005 EVT VT = Tmp0.getValueType();
6006 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
6007 return true;
6008}
6009
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006010void SelectionDAGBuilder::visitCall(const CallInst &I) {
Chris Lattner2c0315a2010-07-05 05:36:21 +00006011 // Handle inline assembly differently.
6012 if (isa<InlineAsm>(I.getCalledValue())) {
6013 visitInlineAsm(&I);
6014 return;
6015 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006016
Michael J. Spencer0e36e032010-10-21 20:49:23 +00006017 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Michael J. Spencer8b98bf22012-02-22 19:06:13 +00006018 ComputeUsesVAFloatArgument(I, &MMI);
Michael J. Spencer0e36e032010-10-21 20:49:23 +00006019
Craig Topperc0196b12014-04-14 00:51:57 +00006020 const char *RenameFn = nullptr;
Dan Gohman575fad32008-09-03 16:12:24 +00006021 if (Function *F = I.getCalledFunction()) {
6022 if (F->isDeclaration()) {
Chris Lattner2c0315a2010-07-05 05:36:21 +00006023 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
Dale Johannesenb842d522009-02-05 01:49:45 +00006024 if (unsigned IID = II->getIntrinsicID(F)) {
6025 RenameFn = visitIntrinsicCall(I, IID);
6026 if (!RenameFn)
6027 return;
6028 }
6029 }
Dan Gohman575fad32008-09-03 16:12:24 +00006030 if (unsigned IID = F->getIntrinsicID()) {
6031 RenameFn = visitIntrinsicCall(I, IID);
6032 if (!RenameFn)
6033 return;
6034 }
6035 }
6036
6037 // Check for well-known libc/libm calls. If the function is internal, it
6038 // can't be a library call.
Bob Wilson871701c2012-08-03 21:26:24 +00006039 LibFunc::Func Func;
6040 if (!F->hasLocalLinkage() && F->hasName() &&
6041 LibInfo->getLibFunc(F->getName(), Func) &&
6042 LibInfo->hasOptimizedCodeGen(Func)) {
6043 switch (Func) {
6044 default: break;
6045 case LibFunc::copysign:
6046 case LibFunc::copysignf:
6047 case LibFunc::copysignl:
Gabor Greiff69acfe2010-06-30 12:55:46 +00006048 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
Gabor Greifeba0be72010-06-25 09:38:13 +00006049 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
6050 I.getType() == I.getArgOperand(0)->getType() &&
Bob Wilson874886c2012-08-03 23:29:17 +00006051 I.getType() == I.getArgOperand(1)->getType() &&
6052 I.onlyReadsMemory()) {
Gabor Greifeba0be72010-06-25 09:38:13 +00006053 SDValue LHS = getValue(I.getArgOperand(0));
6054 SDValue RHS = getValue(I.getArgOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006055 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
Bill Wendling0602f392009-12-23 01:28:19 +00006056 LHS.getValueType(), LHS, RHS));
Dan Gohman575fad32008-09-03 16:12:24 +00006057 return;
6058 }
Bob Wilson871701c2012-08-03 21:26:24 +00006059 break;
6060 case LibFunc::fabs:
6061 case LibFunc::fabsf:
6062 case LibFunc::fabsl:
Bob Wilson874886c2012-08-03 23:29:17 +00006063 if (visitUnaryFloatCall(I, ISD::FABS))
Dan Gohman575fad32008-09-03 16:12:24 +00006064 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006065 break;
Matt Arsenault7c936902014-10-21 23:01:01 +00006066 case LibFunc::fmin:
6067 case LibFunc::fminf:
6068 case LibFunc::fminl:
6069 if (visitBinaryFloatCall(I, ISD::FMINNUM))
6070 return;
6071 break;
6072 case LibFunc::fmax:
6073 case LibFunc::fmaxf:
6074 case LibFunc::fmaxl:
6075 if (visitBinaryFloatCall(I, ISD::FMAXNUM))
6076 return;
6077 break;
Bob Wilson871701c2012-08-03 21:26:24 +00006078 case LibFunc::sin:
6079 case LibFunc::sinf:
6080 case LibFunc::sinl:
Bob Wilson874886c2012-08-03 23:29:17 +00006081 if (visitUnaryFloatCall(I, ISD::FSIN))
Dan Gohman575fad32008-09-03 16:12:24 +00006082 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006083 break;
6084 case LibFunc::cos:
6085 case LibFunc::cosf:
6086 case LibFunc::cosl:
Bob Wilson874886c2012-08-03 23:29:17 +00006087 if (visitUnaryFloatCall(I, ISD::FCOS))
Dan Gohman575fad32008-09-03 16:12:24 +00006088 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006089 break;
6090 case LibFunc::sqrt:
6091 case LibFunc::sqrtf:
6092 case LibFunc::sqrtl:
Preston Gurd048f99d2013-05-27 15:44:35 +00006093 case LibFunc::sqrt_finite:
6094 case LibFunc::sqrtf_finite:
6095 case LibFunc::sqrtl_finite:
Bob Wilson874886c2012-08-03 23:29:17 +00006096 if (visitUnaryFloatCall(I, ISD::FSQRT))
Dale Johannesenc7213422009-09-25 17:23:22 +00006097 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006098 break;
6099 case LibFunc::floor:
6100 case LibFunc::floorf:
6101 case LibFunc::floorl:
Bob Wilson874886c2012-08-03 23:29:17 +00006102 if (visitUnaryFloatCall(I, ISD::FFLOOR))
Owen Anderson0b9b9da2011-12-08 19:32:14 +00006103 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006104 break;
6105 case LibFunc::nearbyint:
6106 case LibFunc::nearbyintf:
6107 case LibFunc::nearbyintl:
Bob Wilson874886c2012-08-03 23:29:17 +00006108 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
Owen Anderson0b9b9da2011-12-08 19:32:14 +00006109 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006110 break;
6111 case LibFunc::ceil:
6112 case LibFunc::ceilf:
6113 case LibFunc::ceill:
Bob Wilson874886c2012-08-03 23:29:17 +00006114 if (visitUnaryFloatCall(I, ISD::FCEIL))
Owen Anderson0b9b9da2011-12-08 19:32:14 +00006115 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006116 break;
6117 case LibFunc::rint:
6118 case LibFunc::rintf:
6119 case LibFunc::rintl:
Bob Wilson874886c2012-08-03 23:29:17 +00006120 if (visitUnaryFloatCall(I, ISD::FRINT))
Owen Anderson0b9b9da2011-12-08 19:32:14 +00006121 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006122 break;
Hal Finkel171817e2013-08-07 22:49:12 +00006123 case LibFunc::round:
6124 case LibFunc::roundf:
6125 case LibFunc::roundl:
6126 if (visitUnaryFloatCall(I, ISD::FROUND))
6127 return;
6128 break;
Bob Wilson871701c2012-08-03 21:26:24 +00006129 case LibFunc::trunc:
6130 case LibFunc::truncf:
6131 case LibFunc::truncl:
Bob Wilson874886c2012-08-03 23:29:17 +00006132 if (visitUnaryFloatCall(I, ISD::FTRUNC))
Owen Anderson0b9b9da2011-12-08 19:32:14 +00006133 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006134 break;
6135 case LibFunc::log2:
6136 case LibFunc::log2f:
6137 case LibFunc::log2l:
Bob Wilson874886c2012-08-03 23:29:17 +00006138 if (visitUnaryFloatCall(I, ISD::FLOG2))
Owen Andersone7f329f2011-12-15 00:54:12 +00006139 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006140 break;
6141 case LibFunc::exp2:
6142 case LibFunc::exp2f:
6143 case LibFunc::exp2l:
Bob Wilson874886c2012-08-03 23:29:17 +00006144 if (visitUnaryFloatCall(I, ISD::FEXP2))
Owen Andersone7f329f2011-12-15 00:54:12 +00006145 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006146 break;
6147 case LibFunc::memcmp:
Chris Lattner1a32ede2009-12-24 00:37:38 +00006148 if (visitMemCmpCall(I))
6149 return;
Bob Wilson871701c2012-08-03 21:26:24 +00006150 break;
Richard Sandiford6f6d5512013-08-20 09:38:48 +00006151 case LibFunc::memchr:
6152 if (visitMemChrCall(I))
6153 return;
6154 break;
Richard Sandifordbb83a502013-08-16 11:29:37 +00006155 case LibFunc::strcpy:
6156 if (visitStrCpyCall(I, false))
6157 return;
6158 break;
6159 case LibFunc::stpcpy:
6160 if (visitStrCpyCall(I, true))
6161 return;
6162 break;
Richard Sandifordca232712013-08-16 11:21:54 +00006163 case LibFunc::strcmp:
6164 if (visitStrCmpCall(I))
6165 return;
6166 break;
Richard Sandiford0dec06a2013-08-16 11:41:43 +00006167 case LibFunc::strlen:
6168 if (visitStrLenCall(I))
6169 return;
6170 break;
6171 case LibFunc::strnlen:
6172 if (visitStrNLenCall(I))
6173 return;
6174 break;
Dan Gohman575fad32008-09-03 16:12:24 +00006175 }
6176 }
Dan Gohman575fad32008-09-03 16:12:24 +00006177 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006178
Dan Gohman575fad32008-09-03 16:12:24 +00006179 SDValue Callee;
6180 if (!RenameFn)
Gabor Greifeba0be72010-06-25 09:38:13 +00006181 Callee = getValue(I.getCalledValue());
Dan Gohman575fad32008-09-03 16:12:24 +00006182 else
Eric Christopher58a24612014-10-08 09:50:54 +00006183 Callee = DAG.getExternalSymbol(RenameFn,
6184 DAG.getTargetLoweringInfo().getPointerTy());
Dan Gohman575fad32008-09-03 16:12:24 +00006185
Bill Wendling0602f392009-12-23 01:28:19 +00006186 // Check if we can potentially perform a tail call. More detailed checking is
6187 // be done within LowerCallTo, after more information about the call is known.
Evan Chengc35b5a12010-01-26 23:13:04 +00006188 LowerCallTo(&I, Callee, I.isTailCall());
Dan Gohman575fad32008-09-03 16:12:24 +00006189}
6190
Benjamin Kramer355ce072011-03-26 16:35:10 +00006191namespace {
Dan Gohman4db93c92010-05-29 17:53:24 +00006192
Dan Gohman575fad32008-09-03 16:12:24 +00006193/// AsmOperandInfo - This contains information for each constraint that we are
6194/// lowering.
Benjamin Kramer355ce072011-03-26 16:35:10 +00006195class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
Cedric Venetd1e179d2009-02-14 16:06:42 +00006196public:
Dan Gohman575fad32008-09-03 16:12:24 +00006197 /// CallOperand - If this is the result output operand or a clobber
6198 /// this is null, otherwise it is the incoming operand to the CallInst.
6199 /// This gets modified as the asm is processed.
6200 SDValue CallOperand;
6201
6202 /// AssignedRegs - If this is a register or register class operand, this
6203 /// contains the set of register corresponding to the operand.
6204 RegsForValue AssignedRegs;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006205
John Thompson1094c802010-09-13 18:15:37 +00006206 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
Craig Topperc0196b12014-04-14 00:51:57 +00006207 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
Dan Gohman575fad32008-09-03 16:12:24 +00006208 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006209
Owen Anderson53aa7a92009-08-10 22:56:29 +00006210 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
Chris Lattner3b1833c2008-10-17 17:05:25 +00006211 /// corresponds to. If there is no Value* for this operand, it returns
Owen Anderson9f944592009-08-11 20:47:22 +00006212 /// MVT::Other.
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00006213 EVT getCallOperandValEVT(LLVMContext &Context,
Owen Anderson55f1c092009-08-13 21:58:54 +00006214 const TargetLowering &TLI,
Rafael Espindola5f57f462014-02-21 18:34:28 +00006215 const DataLayout *DL) const {
Craig Topperc0196b12014-04-14 00:51:57 +00006216 if (!CallOperandVal) return MVT::Other;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006217
Chris Lattner3b1833c2008-10-17 17:05:25 +00006218 if (isa<BasicBlock>(CallOperandVal))
6219 return TLI.getPointerTy();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006220
Chris Lattner229907c2011-07-18 04:54:35 +00006221 llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006222
Eric Christopher44804282011-05-09 20:04:43 +00006223 // FIXME: code duplicated from TargetLowering::ParseConstraints().
Chris Lattner3b1833c2008-10-17 17:05:25 +00006224 // If this is an indirect operand, the operand is a pointer to the
6225 // accessed type.
Bob Wilsonbac37ab2009-12-22 18:34:19 +00006226 if (isIndirect) {
Chris Lattner229907c2011-07-18 04:54:35 +00006227 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
Bob Wilsonbac37ab2009-12-22 18:34:19 +00006228 if (!PtrTy)
Chris Lattner2104b8d2010-04-07 22:58:41 +00006229 report_fatal_error("Indirect operand for inline asm not a pointer!");
Bob Wilsonbac37ab2009-12-22 18:34:19 +00006230 OpTy = PtrTy->getElementType();
6231 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006232
Eric Christopher44804282011-05-09 20:04:43 +00006233 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
Chris Lattner229907c2011-07-18 04:54:35 +00006234 if (StructType *STy = dyn_cast<StructType>(OpTy))
Eric Christopher44804282011-05-09 20:04:43 +00006235 if (STy->getNumElements() == 1)
6236 OpTy = STy->getElementType(0);
6237
Chris Lattner3b1833c2008-10-17 17:05:25 +00006238 // If OpTy is not a single value, it may be a struct/union that we
6239 // can tile with integers.
6240 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
Rafael Espindola5f57f462014-02-21 18:34:28 +00006241 unsigned BitSize = DL->getTypeSizeInBits(OpTy);
Chris Lattner3b1833c2008-10-17 17:05:25 +00006242 switch (BitSize) {
6243 default: break;
6244 case 1:
6245 case 8:
6246 case 16:
6247 case 32:
6248 case 64:
Chris Lattneraadf7412008-10-17 19:59:51 +00006249 case 128:
Owen Anderson55f1c092009-08-13 21:58:54 +00006250 OpTy = IntegerType::get(Context, BitSize);
Chris Lattner3b1833c2008-10-17 17:05:25 +00006251 break;
6252 }
6253 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006254
Chris Lattner3b1833c2008-10-17 17:05:25 +00006255 return TLI.getValueType(OpTy, true);
6256 }
Dan Gohman575fad32008-09-03 16:12:24 +00006257};
Dan Gohman4db93c92010-05-29 17:53:24 +00006258
John Thompsone8360b72010-10-29 17:29:13 +00006259typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
6260
Benjamin Kramer355ce072011-03-26 16:35:10 +00006261} // end anonymous namespace
Dan Gohman575fad32008-09-03 16:12:24 +00006262
Dan Gohman575fad32008-09-03 16:12:24 +00006263/// GetRegistersForValue - Assign registers (virtual or physical) for the
6264/// specified operand. We prefer to assign virtual registers, to allow the
Bob Wilson1c00b692009-12-17 05:07:36 +00006265/// register allocator to handle the assignment process. However, if the asm
6266/// uses features that we can't model on machineinstrs, we have SDISel do the
Dan Gohman575fad32008-09-03 16:12:24 +00006267/// allocation. This produces generally horrible, but correct, code.
6268///
6269/// OpInfo describes the operand.
Dan Gohman575fad32008-09-03 16:12:24 +00006270///
Benjamin Kramer355ce072011-03-26 16:35:10 +00006271static void GetRegistersForValue(SelectionDAG &DAG,
6272 const TargetLowering &TLI,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006273 SDLoc DL,
Benjamin Kramer6fe3e3d2012-02-24 14:01:17 +00006274 SDISelAsmOperandInfo &OpInfo) {
Benjamin Kramer355ce072011-03-26 16:35:10 +00006275 LLVMContext &Context = *DAG.getContext();
Owen Anderson117c9e82009-08-12 00:36:31 +00006276
Dan Gohman575fad32008-09-03 16:12:24 +00006277 MachineFunction &MF = DAG.getMachineFunction();
6278 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006279
Dan Gohman575fad32008-09-03 16:12:24 +00006280 // If this is a constraint for a single physreg, or a constraint for a
6281 // register class, find it.
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006282 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohman575fad32008-09-03 16:12:24 +00006283 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6284 OpInfo.ConstraintVT);
6285
6286 unsigned NumRegs = 1;
Owen Anderson9f944592009-08-11 20:47:22 +00006287 if (OpInfo.ConstraintVT != MVT::Other) {
Chris Lattner4396e0d2008-10-21 00:45:36 +00006288 // If this is a FP input in an integer register (or visa versa) insert a bit
6289 // cast of the input value. More generally, handle any case where the input
6290 // value disagrees with the register class we plan to stick this in.
6291 if (OpInfo.Type == InlineAsm::isInput &&
6292 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006293 // Try to convert to the first EVT that the reg class contains. If the
Chris Lattner4396e0d2008-10-21 00:45:36 +00006294 // types are identical size, use a bitcast to convert (e.g. two differing
6295 // vector types).
Patrik Hagglund4e0f8282012-12-19 12:23:01 +00006296 MVT RegVT = *PhysReg.second->vt_begin();
Kevin Qin275ce912014-03-21 02:14:50 +00006297 if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
Benjamin Kramer355ce072011-03-26 16:35:10 +00006298 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
Dale Johannesened255b32009-01-30 01:34:22 +00006299 RegVT, OpInfo.CallOperand);
Chris Lattner4396e0d2008-10-21 00:45:36 +00006300 OpInfo.ConstraintVT = RegVT;
6301 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
6302 // If the input is a FP value and we want it in FP registers, do a
6303 // bitcast to the corresponding integer type. This turns an f64 value
6304 // into i64, which can be passed with two i32 values on a 32-bit
6305 // machine.
Patrik Hagglund4e0f8282012-12-19 12:23:01 +00006306 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
Benjamin Kramer355ce072011-03-26 16:35:10 +00006307 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
Dale Johannesened255b32009-01-30 01:34:22 +00006308 RegVT, OpInfo.CallOperand);
Chris Lattner4396e0d2008-10-21 00:45:36 +00006309 OpInfo.ConstraintVT = RegVT;
6310 }
6311 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006312
Owen Anderson117c9e82009-08-12 00:36:31 +00006313 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
Chris Lattner4396e0d2008-10-21 00:45:36 +00006314 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006315
Patrik Hagglund4e0f8282012-12-19 12:23:01 +00006316 MVT RegVT;
Owen Anderson53aa7a92009-08-10 22:56:29 +00006317 EVT ValueVT = OpInfo.ConstraintVT;
Dan Gohman575fad32008-09-03 16:12:24 +00006318
6319 // If this is a constraint for a specific physical register, like {r17},
6320 // assign it now.
Chris Lattnerc35847e2009-03-24 15:27:37 +00006321 if (unsigned AssignedReg = PhysReg.first) {
6322 const TargetRegisterClass *RC = PhysReg.second;
Owen Anderson9f944592009-08-11 20:47:22 +00006323 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnerc35847e2009-03-24 15:27:37 +00006324 ValueVT = *RC->vt_begin();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006325
Dan Gohman575fad32008-09-03 16:12:24 +00006326 // Get the actual register value type. This is important, because the user
6327 // may have asked for (e.g.) the AX register in i32 type. We need to
6328 // remember that AX is actually i16 to get the right extension.
Chris Lattnerc35847e2009-03-24 15:27:37 +00006329 RegVT = *RC->vt_begin();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006330
Dan Gohman575fad32008-09-03 16:12:24 +00006331 // This is a explicit reference to a physical register.
Chris Lattnerc35847e2009-03-24 15:27:37 +00006332 Regs.push_back(AssignedReg);
Dan Gohman575fad32008-09-03 16:12:24 +00006333
6334 // If this is an expanded reference, add the rest of the regs to Regs.
6335 if (NumRegs != 1) {
Chris Lattnerc35847e2009-03-24 15:27:37 +00006336 TargetRegisterClass::iterator I = RC->begin();
6337 for (; *I != AssignedReg; ++I)
6338 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006339
Dan Gohman575fad32008-09-03 16:12:24 +00006340 // Already added the first reg.
6341 --NumRegs; ++I;
6342 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnerc35847e2009-03-24 15:27:37 +00006343 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohman575fad32008-09-03 16:12:24 +00006344 Regs.push_back(*I);
6345 }
6346 }
Bill Wendlingac087582009-12-22 01:25:10 +00006347
Dan Gohmand16aa542010-05-29 17:03:36 +00006348 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
Dan Gohman575fad32008-09-03 16:12:24 +00006349 return;
6350 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006351
Dan Gohman575fad32008-09-03 16:12:24 +00006352 // Otherwise, if this was a reference to an LLVM register class, create vregs
6353 // for this reference.
Chris Lattner42eceb32009-03-24 15:25:07 +00006354 if (const TargetRegisterClass *RC = PhysReg.second) {
6355 RegVT = *RC->vt_begin();
Owen Anderson9f944592009-08-11 20:47:22 +00006356 if (OpInfo.ConstraintVT == MVT::Other)
Evan Cheng968c3b02009-03-23 08:01:15 +00006357 ValueVT = RegVT;
Dan Gohman575fad32008-09-03 16:12:24 +00006358
Evan Cheng968c3b02009-03-23 08:01:15 +00006359 // Create the appropriate number of virtual registers.
6360 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6361 for (; NumRegs; --NumRegs)
Chris Lattner42eceb32009-03-24 15:25:07 +00006362 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006363
Dan Gohmand16aa542010-05-29 17:03:36 +00006364 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
Evan Cheng968c3b02009-03-23 08:01:15 +00006365 return;
Dan Gohman575fad32008-09-03 16:12:24 +00006366 }
Mikhail Glushenkov2abe1b72010-01-01 04:41:22 +00006367
Dan Gohman575fad32008-09-03 16:12:24 +00006368 // Otherwise, we couldn't allocate enough registers for this.
6369}
6370
Dan Gohman575fad32008-09-03 16:12:24 +00006371/// visitInlineAsm - Handle a call to an InlineAsm object.
6372///
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006373void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
6374 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Dan Gohman575fad32008-09-03 16:12:24 +00006375
6376 /// ConstraintOperands - Information about all of the constraints.
John Thompsone8360b72010-10-29 17:29:13 +00006377 SDISelAsmOperandInfoVector ConstraintOperands;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006378
Eric Christopher58a24612014-10-08 09:50:54 +00006379 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Evan Chengd26fc5e2011-05-06 20:52:23 +00006380 TargetLowering::AsmOperandInfoVector
Eric Christopher58a24612014-10-08 09:50:54 +00006381 TargetConstraints = TLI.ParseConstraints(CS);
Evan Chengd26fc5e2011-05-06 20:52:23 +00006382
John Thompson1094c802010-09-13 18:15:37 +00006383 bool hasMemory = false;
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006384
Dan Gohman575fad32008-09-03 16:12:24 +00006385 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6386 unsigned ResNo = 0; // ResNo - The result number of the next output.
John Thompson1094c802010-09-13 18:15:37 +00006387 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6388 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
Dan Gohman575fad32008-09-03 16:12:24 +00006389 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006390
Patrik Hagglundf9934612012-12-19 15:19:11 +00006391 MVT OpVT = MVT::Other;
Dan Gohman575fad32008-09-03 16:12:24 +00006392
6393 // Compute the value type for each operand.
6394 switch (OpInfo.Type) {
6395 case InlineAsm::isOutput:
6396 // Indirect outputs just consume an argument.
6397 if (OpInfo.isIndirect) {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006398 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Dan Gohman575fad32008-09-03 16:12:24 +00006399 break;
6400 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006401
Dan Gohman575fad32008-09-03 16:12:24 +00006402 // The return value of the call is this value. As such, there is no
6403 // corresponding argument.
Nick Lewyckyf40df1d2011-09-30 22:19:53 +00006404 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
Chris Lattner229907c2011-07-18 04:54:35 +00006405 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
Eric Christopher58a24612014-10-08 09:50:54 +00006406 OpVT = TLI.getSimpleValueType(STy->getElementType(ResNo));
Dan Gohman575fad32008-09-03 16:12:24 +00006407 } else {
6408 assert(ResNo == 0 && "Asm only has one result!");
Eric Christopher58a24612014-10-08 09:50:54 +00006409 OpVT = TLI.getSimpleValueType(CS.getType());
Dan Gohman575fad32008-09-03 16:12:24 +00006410 }
6411 ++ResNo;
6412 break;
6413 case InlineAsm::isInput:
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006414 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Dan Gohman575fad32008-09-03 16:12:24 +00006415 break;
6416 case InlineAsm::isClobber:
6417 // Nothing to do.
6418 break;
6419 }
6420
6421 // If this is an input or an indirect output, process the call argument.
6422 // BasicBlocks are labels, currently appearing only in asm's.
6423 if (OpInfo.CallOperandVal) {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006424 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohman575fad32008-09-03 16:12:24 +00006425 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner3b1833c2008-10-17 17:05:25 +00006426 } else {
Dan Gohman575fad32008-09-03 16:12:24 +00006427 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohman575fad32008-09-03 16:12:24 +00006428 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006429
Eric Christopher58a24612014-10-08 09:50:54 +00006430 OpVT =
6431 OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, DL).getSimpleVT();
Dan Gohman575fad32008-09-03 16:12:24 +00006432 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006433
Dan Gohman575fad32008-09-03 16:12:24 +00006434 OpInfo.ConstraintVT = OpVT;
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006435
John Thompson1094c802010-09-13 18:15:37 +00006436 // Indirect operand accesses access memory.
6437 if (OpInfo.isIndirect)
6438 hasMemory = true;
6439 else {
6440 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
Evan Chengd26fc5e2011-05-06 20:52:23 +00006441 TargetLowering::ConstraintType
Eric Christopher58a24612014-10-08 09:50:54 +00006442 CType = TLI.getConstraintType(OpInfo.Codes[j]);
John Thompson1094c802010-09-13 18:15:37 +00006443 if (CType == TargetLowering::C_Memory) {
6444 hasMemory = true;
6445 break;
6446 }
6447 }
6448 }
Chris Lattner160e8ab2008-10-18 18:49:30 +00006449 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006450
John Thompson1094c802010-09-13 18:15:37 +00006451 SDValue Chain, Flag;
6452
6453 // We won't need to flush pending loads if this asm doesn't touch
6454 // memory and is nonvolatile.
6455 if (hasMemory || IA->hasSideEffects())
6456 Chain = getRoot();
6457 else
6458 Chain = DAG.getRoot();
6459
Chris Lattner160e8ab2008-10-18 18:49:30 +00006460 // Second pass over the constraints: compute which constraint option to use
6461 // and assign registers to constraints that want a specific physreg.
John Thompson1094c802010-09-13 18:15:37 +00006462 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Chris Lattner160e8ab2008-10-18 18:49:30 +00006463 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006464
John Thompson8118ef82010-09-24 22:24:05 +00006465 // If this is an output operand with a matching input operand, look up the
6466 // matching input. If their types mismatch, e.g. one is an integer, the
6467 // other is floating point, or their sizes are different, flag it as an
6468 // error.
6469 if (OpInfo.hasMatchingInput()) {
6470 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006471
John Thompson8118ef82010-09-24 22:24:05 +00006472 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Bill Wendlingd1634052012-07-19 00:04:14 +00006473 std::pair<unsigned, const TargetRegisterClass*> MatchRC =
Eric Christopher58a24612014-10-08 09:50:54 +00006474 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006475 OpInfo.ConstraintVT);
Bill Wendlingd1634052012-07-19 00:04:14 +00006476 std::pair<unsigned, const TargetRegisterClass*> InputRC =
Eric Christopher58a24612014-10-08 09:50:54 +00006477 TLI.getRegForInlineAsmConstraint(Input.ConstraintCode,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006478 Input.ConstraintVT);
John Thompson8118ef82010-09-24 22:24:05 +00006479 if ((OpInfo.ConstraintVT.isInteger() !=
6480 Input.ConstraintVT.isInteger()) ||
Eric Christopher92464be2011-07-14 20:13:52 +00006481 (MatchRC.second != InputRC.second)) {
John Thompson8118ef82010-09-24 22:24:05 +00006482 report_fatal_error("Unsupported asm: input constraint"
6483 " with a matching output constraint of"
6484 " incompatible type!");
6485 }
6486 Input.ConstraintVT = OpInfo.ConstraintVT;
6487 }
6488 }
6489
Dan Gohman575fad32008-09-03 16:12:24 +00006490 // Compute the constraint code and ConstraintType to use.
Eric Christopher58a24612014-10-08 09:50:54 +00006491 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Dan Gohman575fad32008-09-03 16:12:24 +00006492
Eric Christopher0cb6fd92013-01-11 18:12:39 +00006493 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6494 OpInfo.Type == InlineAsm::isClobber)
6495 continue;
6496
Dan Gohman575fad32008-09-03 16:12:24 +00006497 // If this is a memory input, and if the operand is not indirect, do what we
6498 // need to to provide an address for the memory input.
6499 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6500 !OpInfo.isIndirect) {
Evan Chengd26fc5e2011-05-06 20:52:23 +00006501 assert((OpInfo.isMultipleAlternative ||
6502 (OpInfo.Type == InlineAsm::isInput)) &&
Dan Gohman575fad32008-09-03 16:12:24 +00006503 "Can only indirectify direct input operands!");
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006504
Dan Gohman575fad32008-09-03 16:12:24 +00006505 // Memory operands really want the address of the value. If we don't have
6506 // an indirect input, put it in the constpool if we can, otherwise spill
6507 // it to a stack slot.
Eric Christopherfbff0e42011-06-03 17:21:23 +00006508 // TODO: This isn't quite right. We need to handle these according to
6509 // the addressing mode that the constraint wants. Also, this may take
6510 // an additional register for the computation and we don't want that
6511 // either.
Eric Christopher0713a9d2011-06-08 23:55:35 +00006512
Dan Gohman575fad32008-09-03 16:12:24 +00006513 // If the operand is a float, integer, or vector constant, spill to a
6514 // constant pool entry to get its address.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006515 const Value *OpVal = OpInfo.CallOperandVal;
Dan Gohman575fad32008-09-03 16:12:24 +00006516 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
Chris Lattner0256be92012-01-27 03:08:05 +00006517 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
Dan Gohman575fad32008-09-03 16:12:24 +00006518 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
Eric Christopher58a24612014-10-08 09:50:54 +00006519 TLI.getPointerTy());
Dan Gohman575fad32008-09-03 16:12:24 +00006520 } else {
6521 // Otherwise, create a stack slot and emit a store to it before the
6522 // asm.
Chris Lattner229907c2011-07-18 04:54:35 +00006523 Type *Ty = OpVal->getType();
Eric Christopher58a24612014-10-08 09:50:54 +00006524 uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
6525 unsigned Align = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
Dan Gohman575fad32008-09-03 16:12:24 +00006526 MachineFunction &MF = DAG.getMachineFunction();
David Greene1fbe0542009-11-12 20:49:22 +00006527 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Eric Christopher58a24612014-10-08 09:50:54 +00006528 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006529 Chain = DAG.getStore(Chain, getCurSDLoc(),
Chris Lattner1ffcf522010-09-21 16:36:31 +00006530 OpInfo.CallOperand, StackSlot,
6531 MachinePointerInfo::getFixedStack(SSFI),
David Greene39c6d012010-02-15 17:00:31 +00006532 false, false, 0);
Dan Gohman575fad32008-09-03 16:12:24 +00006533 OpInfo.CallOperand = StackSlot;
6534 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006535
Dan Gohman575fad32008-09-03 16:12:24 +00006536 // There is no longer a Value* corresponding to this operand.
Craig Topperc0196b12014-04-14 00:51:57 +00006537 OpInfo.CallOperandVal = nullptr;
Bill Wendlingac087582009-12-22 01:25:10 +00006538
Dan Gohman575fad32008-09-03 16:12:24 +00006539 // It is now an indirect operand.
6540 OpInfo.isIndirect = true;
6541 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006542
Dan Gohman575fad32008-09-03 16:12:24 +00006543 // If this constraint is for a specific register, allocate it before
6544 // anything else.
6545 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Eric Christopher58a24612014-10-08 09:50:54 +00006546 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
Dan Gohman575fad32008-09-03 16:12:24 +00006547 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006548
Dan Gohman575fad32008-09-03 16:12:24 +00006549 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattneref890172008-10-17 16:21:11 +00006550 // to register class operands.
Dan Gohman575fad32008-09-03 16:12:24 +00006551 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6552 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006553
Dan Gohman575fad32008-09-03 16:12:24 +00006554 // C_Register operands have already been allocated, Other/Memory don't need
6555 // to be.
6556 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Eric Christopher58a24612014-10-08 09:50:54 +00006557 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006558 }
6559
Dan Gohman575fad32008-09-03 16:12:24 +00006560 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6561 std::vector<SDValue> AsmNodeOperands;
6562 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
6563 AsmNodeOperands.push_back(
Dan Gohmanfeeced42010-01-04 21:00:54 +00006564 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
Eric Christopher58a24612014-10-08 09:50:54 +00006565 TLI.getPointerTy()));
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006566
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006567 // If we have a !srcloc metadata node associated with it, we want to attach
6568 // this to the ultimately generated inline asm machineinstr. To do this, we
6569 // pass in the third operand as this (potentially null) inline asm MDNode.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00006570 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006571 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006572
Chad Rosier9e1274f2012-10-30 19:11:54 +00006573 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6574 // bits as operand 3.
Evan Cheng6eb516d2011-01-07 23:50:32 +00006575 unsigned ExtraInfo = 0;
6576 if (IA->hasSideEffects())
6577 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6578 if (IA->isAlignStack())
6579 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
Chad Rosiercbd2a192012-09-05 22:17:43 +00006580 // Set the asm dialect.
Chad Rosiere53314f2012-09-05 22:40:13 +00006581 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
Chad Rosier9e1274f2012-10-30 19:11:54 +00006582
6583 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6584 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6585 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6586
6587 // Compute the constraint code and ConstraintType to use.
Eric Christopher58a24612014-10-08 09:50:54 +00006588 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chad Rosier9e1274f2012-10-30 19:11:54 +00006589
Chad Rosier86f60502012-10-30 20:01:12 +00006590 // Ideally, we would only check against memory constraints. However, the
6591 // meaning of an other constraint can be target-specific and we can't easily
6592 // reason about it. Therefore, be conservative and set MayLoad/MayStore
6593 // for other constriants as well.
Chad Rosier9e1274f2012-10-30 19:11:54 +00006594 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6595 OpInfo.ConstraintType == TargetLowering::C_Other) {
6596 if (OpInfo.Type == InlineAsm::isInput)
6597 ExtraInfo |= InlineAsm::Extra_MayLoad;
6598 else if (OpInfo.Type == InlineAsm::isOutput)
6599 ExtraInfo |= InlineAsm::Extra_MayStore;
Eric Christopher0cb6fd92013-01-11 18:12:39 +00006600 else if (OpInfo.Type == InlineAsm::isClobber)
6601 ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
Chad Rosier9e1274f2012-10-30 19:11:54 +00006602 }
6603 }
6604
Evan Cheng6eb516d2011-01-07 23:50:32 +00006605 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
Eric Christopher58a24612014-10-08 09:50:54 +00006606 TLI.getPointerTy()));
Dale Johannesen4d887f7c2010-07-02 20:16:09 +00006607
Dan Gohman575fad32008-09-03 16:12:24 +00006608 // Loop over all of the inputs, copying the operand values into the
6609 // appropriate registers and processing the output regs.
6610 RegsForValue RetValRegs;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006611
Dan Gohman575fad32008-09-03 16:12:24 +00006612 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6613 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006614
Dan Gohman575fad32008-09-03 16:12:24 +00006615 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6616 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6617
6618 switch (OpInfo.Type) {
6619 case InlineAsm::isOutput: {
6620 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6621 OpInfo.ConstraintType != TargetLowering::C_Register) {
6622 // Memory output, or 'other' output (e.g. 'X' constraint).
6623 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6624
6625 // Add information to the INLINEASM node to know about this output.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006626 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6627 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
Eric Christopher58a24612014-10-08 09:50:54 +00006628 TLI.getPointerTy()));
Dan Gohman575fad32008-09-03 16:12:24 +00006629 AsmNodeOperands.push_back(OpInfo.CallOperand);
6630 break;
6631 }
6632
6633 // Otherwise, this is a register or register class output.
6634
6635 // Copy the output from the appropriate register. Find a register that
6636 // we can use.
Chris Lattner6b77a072012-01-03 23:51:01 +00006637 if (OpInfo.AssignedRegs.Regs.empty()) {
6638 LLVMContext &Ctx = *DAG.getContext();
Stephen Lincfe7f352013-07-08 00:37:03 +00006639 Ctx.emitError(CS.getInstruction(),
Chris Lattner6b77a072012-01-03 23:51:01 +00006640 "couldn't allocate output register for constraint '" +
Eric Christophere6656ac2013-07-31 01:26:24 +00006641 Twine(OpInfo.ConstraintCode) + "'");
6642 return;
Chris Lattner6b77a072012-01-03 23:51:01 +00006643 }
Dan Gohman575fad32008-09-03 16:12:24 +00006644
6645 // If this is an indirect operand, store through the pointer after the
6646 // asm.
6647 if (OpInfo.isIndirect) {
6648 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6649 OpInfo.CallOperandVal));
6650 } else {
6651 // This is the result value of the call.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00006652 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
Dan Gohman575fad32008-09-03 16:12:24 +00006653 // Concatenate this output onto the outputs list.
6654 RetValRegs.append(OpInfo.AssignedRegs);
6655 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006656
Dan Gohman575fad32008-09-03 16:12:24 +00006657 // Add information to the INLINEASM node to know that this register is
6658 // set.
Eric Christopher029af152013-07-30 22:50:44 +00006659 OpInfo.AssignedRegs
6660 .AddInlineAsmOperands(OpInfo.isEarlyClobber
6661 ? InlineAsm::Kind_RegDefEarlyClobber
6662 : InlineAsm::Kind_RegDef,
6663 false, 0, DAG, AsmNodeOperands);
Dan Gohman575fad32008-09-03 16:12:24 +00006664 break;
6665 }
6666 case InlineAsm::isInput: {
6667 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006668
Chris Lattner860df6e2008-10-17 16:47:46 +00006669 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohman575fad32008-09-03 16:12:24 +00006670 // If this is required to match an output register we have already set,
6671 // just use its register.
Chris Lattneref890172008-10-17 16:21:11 +00006672 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006673
Dan Gohman575fad32008-09-03 16:12:24 +00006674 // Scan until we find the definition we already emitted of this operand.
6675 // When we find it, create a RegsForValue operand.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006676 unsigned CurOp = InlineAsm::Op_FirstOperand;
Dan Gohman575fad32008-09-03 16:12:24 +00006677 for (; OperandNo; --OperandNo) {
6678 // Advance to the next operand.
Evan Cheng2e559232009-03-20 18:03:34 +00006679 unsigned OpFlag =
Dan Gohmaneffb8942008-09-12 16:56:44 +00006680 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006681 assert((InlineAsm::isRegDefKind(OpFlag) ||
6682 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6683 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
Evan Cheng2e559232009-03-20 18:03:34 +00006684 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohman575fad32008-09-03 16:12:24 +00006685 }
6686
Evan Cheng2e559232009-03-20 18:03:34 +00006687 unsigned OpFlag =
Dan Gohmaneffb8942008-09-12 16:56:44 +00006688 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006689 if (InlineAsm::isRegDefKind(OpFlag) ||
6690 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
Evan Cheng2e559232009-03-20 18:03:34 +00006691 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Chris Lattner3c65a832010-04-08 00:09:16 +00006692 if (OpInfo.isIndirect) {
6693 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
Dan Gohman7c0303a2010-04-19 22:41:47 +00006694 LLVMContext &Ctx = *DAG.getContext();
Eric Christophere6656ac2013-07-31 01:26:24 +00006695 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6696 " don't know how to handle tied "
6697 "indirect register inputs");
6698 return;
Chris Lattner3c65a832010-04-08 00:09:16 +00006699 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006700
Dan Gohman575fad32008-09-03 16:12:24 +00006701 RegsForValue MatchedRegs;
Dan Gohman575fad32008-09-03 16:12:24 +00006702 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Patrik Hagglund5e6c3612012-12-13 06:34:11 +00006703 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
Evan Cheng968c3b02009-03-23 08:01:15 +00006704 MatchedRegs.RegVTs.push_back(RegVT);
6705 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng2e559232009-03-20 18:03:34 +00006706 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Chad Rosier108d5a62013-04-24 22:53:10 +00006707 i != e; ++i) {
Eric Christopher58a24612014-10-08 09:50:54 +00006708 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
Chad Rosier108d5a62013-04-24 22:53:10 +00006709 MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
6710 else {
6711 LLVMContext &Ctx = *DAG.getContext();
Eric Christophere6656ac2013-07-31 01:26:24 +00006712 Ctx.emitError(CS.getInstruction(),
6713 "inline asm error: This value"
Chad Rosier108d5a62013-04-24 22:53:10 +00006714 " type register class is not natively supported!");
Eric Christophere6656ac2013-07-31 01:26:24 +00006715 return;
Chad Rosier108d5a62013-04-24 22:53:10 +00006716 }
6717 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006718 // Use the produced MatchedRegs object to
Andrew Trickef9de2a2013-05-25 02:42:55 +00006719 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
Bill Wendling5def8912012-09-26 06:16:18 +00006720 Chain, &Flag, CS.getInstruction());
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006721 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
Evan Cheng968c3b02009-03-23 08:01:15 +00006722 true, OpInfo.getMatchedOperand(),
Bill Wendling78c5b7a2010-03-02 01:55:18 +00006723 DAG, AsmNodeOperands);
Dan Gohman575fad32008-09-03 16:12:24 +00006724 break;
Dan Gohman575fad32008-09-03 16:12:24 +00006725 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006726
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006727 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6728 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6729 "Unexpected number of operands");
6730 // Add information to the INLINEASM node to know about this input.
6731 // See InlineAsm.h isUseOperandTiedToDef.
6732 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6733 OpInfo.getMatchedOperand());
6734 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
Eric Christopher58a24612014-10-08 09:50:54 +00006735 TLI.getPointerTy()));
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006736 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6737 break;
Dan Gohman575fad32008-09-03 16:12:24 +00006738 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006739
Dale Johannesencaca5482010-07-13 20:17:05 +00006740 // Treat indirect 'X' constraint as memory.
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006741 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6742 OpInfo.isIndirect)
Dale Johannesencaca5482010-07-13 20:17:05 +00006743 OpInfo.ConstraintType = TargetLowering::C_Memory;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006744
Dale Johannesencaca5482010-07-13 20:17:05 +00006745 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Dan Gohman575fad32008-09-03 16:12:24 +00006746 std::vector<SDValue> Ops;
Eric Christopher58a24612014-10-08 09:50:54 +00006747 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
Bill Wendlinga3cd3502013-06-19 21:36:55 +00006748 Ops, DAG);
Chris Lattner6b77a072012-01-03 23:51:01 +00006749 if (Ops.empty()) {
6750 LLVMContext &Ctx = *DAG.getContext();
6751 Ctx.emitError(CS.getInstruction(),
6752 "invalid operand for inline asm constraint '" +
Eric Christophere6656ac2013-07-31 01:26:24 +00006753 Twine(OpInfo.ConstraintCode) + "'");
6754 return;
Chris Lattner6b77a072012-01-03 23:51:01 +00006755 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006756
Dan Gohman575fad32008-09-03 16:12:24 +00006757 // Add information to the INLINEASM node to know about this input.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006758 unsigned ResOpType =
6759 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006760 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Eric Christopher58a24612014-10-08 09:50:54 +00006761 TLI.getPointerTy()));
Dan Gohman575fad32008-09-03 16:12:24 +00006762 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6763 break;
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006764 }
Michael J. Spencerd3ea25e2010-10-16 08:25:21 +00006765
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006766 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Dan Gohman575fad32008-09-03 16:12:24 +00006767 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Eric Christopher58a24612014-10-08 09:50:54 +00006768 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
Dan Gohman575fad32008-09-03 16:12:24 +00006769 "Memory operands expect pointer values");
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006770
Dan Gohman575fad32008-09-03 16:12:24 +00006771 // Add information to the INLINEASM node to know about this input.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006772 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
Dale Johannesenc36660d2008-09-24 01:07:17 +00006773 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Eric Christopher58a24612014-10-08 09:50:54 +00006774 TLI.getPointerTy()));
Dan Gohman575fad32008-09-03 16:12:24 +00006775 AsmNodeOperands.push_back(InOperandVal);
6776 break;
6777 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006778
Dan Gohman575fad32008-09-03 16:12:24 +00006779 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6780 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6781 "Unknown constraint type!");
Eric Christopherdd8638f2012-07-02 21:16:43 +00006782
6783 // TODO: Support this.
6784 if (OpInfo.isIndirect) {
6785 LLVMContext &Ctx = *DAG.getContext();
6786 Ctx.emitError(CS.getInstruction(),
6787 "Don't know how to handle indirect register inputs yet "
Eric Christophere6656ac2013-07-31 01:26:24 +00006788 "for constraint '" +
6789 Twine(OpInfo.ConstraintCode) + "'");
6790 return;
Eric Christopherdd8638f2012-07-02 21:16:43 +00006791 }
Dan Gohman575fad32008-09-03 16:12:24 +00006792
6793 // Copy the input into the appropriate registers.
Chris Lattner6b77a072012-01-03 23:51:01 +00006794 if (OpInfo.AssignedRegs.Regs.empty()) {
6795 LLVMContext &Ctx = *DAG.getContext();
Stephen Lincfe7f352013-07-08 00:37:03 +00006796 Ctx.emitError(CS.getInstruction(),
Chris Lattner6b77a072012-01-03 23:51:01 +00006797 "couldn't allocate input reg for constraint '" +
Eric Christophere6656ac2013-07-31 01:26:24 +00006798 Twine(OpInfo.ConstraintCode) + "'");
6799 return;
Chris Lattner6b77a072012-01-03 23:51:01 +00006800 }
Dan Gohman575fad32008-09-03 16:12:24 +00006801
Andrew Trickef9de2a2013-05-25 02:42:55 +00006802 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
Bill Wendling5def8912012-09-26 06:16:18 +00006803 Chain, &Flag, CS.getInstruction());
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006804
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006805 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
Bill Wendling78c5b7a2010-03-02 01:55:18 +00006806 DAG, AsmNodeOperands);
Dan Gohman575fad32008-09-03 16:12:24 +00006807 break;
6808 }
6809 case InlineAsm::isClobber: {
6810 // Add the clobbered value to the operand list, so that the register
6811 // allocator is aware that the physreg got clobbered.
6812 if (!OpInfo.AssignedRegs.Regs.empty())
Jakob Stoklund Olesen537a3022011-06-27 04:08:33 +00006813 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
Bill Wendling78c5b7a2010-03-02 01:55:18 +00006814 false, 0, DAG,
Bill Wendlingac087582009-12-22 01:25:10 +00006815 AsmNodeOperands);
Dan Gohman575fad32008-09-03 16:12:24 +00006816 break;
6817 }
6818 }
6819 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006820
Chris Lattner3b9f02a2010-04-07 05:20:54 +00006821 // Finish up input operands. Set the input chain and add the flag last.
Dale Johannesen4d887f7c2010-07-02 20:16:09 +00006822 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
Dan Gohman575fad32008-09-03 16:12:24 +00006823 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006824
Andrew Trickef9de2a2013-05-25 02:42:55 +00006825 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
Craig Topper48d114b2014-04-26 18:35:24 +00006826 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
Dan Gohman575fad32008-09-03 16:12:24 +00006827 Flag = Chain.getValue(1);
6828
6829 // If this asm returns a register value, copy the result from that register
6830 // and set it as the value of the call.
6831 if (!RetValRegs.Regs.empty()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006832 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
Bill Wendling81406f62012-09-26 04:04:19 +00006833 Chain, &Flag, CS.getInstruction());
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006834
Chris Lattner160e8ab2008-10-18 18:49:30 +00006835 // FIXME: Why don't we do this for inline asms with MRVs?
6836 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
Eric Christopher58a24612014-10-08 09:50:54 +00006837 EVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006838
Chris Lattner160e8ab2008-10-18 18:49:30 +00006839 // If any of the results of the inline asm is a vector, it may have the
6840 // wrong width/num elts. This can happen for register classes that can
6841 // contain multiple different value types. The preg or vreg allocated may
6842 // not have the same VT as was expected. Convert it to the right type
6843 // with bit_convert.
6844 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006845 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
Dale Johannesened255b32009-01-30 01:34:22 +00006846 ResultType, Val);
Dan Gohman6de25562008-10-18 01:03:45 +00006847
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006848 } else if (ResultType != Val.getValueType() &&
Chris Lattner160e8ab2008-10-18 18:49:30 +00006849 ResultType.isInteger() && Val.getValueType().isInteger()) {
6850 // If a result value was tied to an input value, the computed result may
6851 // have a wider width than the expected result. Extract the relevant
6852 // portion.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006853 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
Dan Gohman6de25562008-10-18 01:03:45 +00006854 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006855
Chris Lattner160e8ab2008-10-18 18:49:30 +00006856 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner052092b2008-10-17 17:52:49 +00006857 }
Dan Gohman6de25562008-10-18 01:03:45 +00006858
Dan Gohman575fad32008-09-03 16:12:24 +00006859 setValue(CS.getInstruction(), Val);
Dale Johannesen83593f42009-04-14 00:56:56 +00006860 // Don't need to use this as a chain in this case.
6861 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6862 return;
Dan Gohman575fad32008-09-03 16:12:24 +00006863 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006864
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006865 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006866
Dan Gohman575fad32008-09-03 16:12:24 +00006867 // Process indirect outputs, first output all of the flagged copies out of
6868 // physregs.
6869 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6870 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006871 const Value *Ptr = IndirectStoresToEmit[i].second;
Andrew Trickef9de2a2013-05-25 02:42:55 +00006872 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
Bill Wendling81406f62012-09-26 04:04:19 +00006873 Chain, &Flag, IA);
Dan Gohman575fad32008-09-03 16:12:24 +00006874 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6875 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00006876
Dan Gohman575fad32008-09-03 16:12:24 +00006877 // Emit the non-flagged stores from the physregs.
6878 SmallVector<SDValue, 8> OutChains;
Bill Wendlingac087582009-12-22 01:25:10 +00006879 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006880 SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
Bill Wendlingac087582009-12-22 01:25:10 +00006881 StoresToEmit[i].first,
6882 getValue(StoresToEmit[i].second),
Chris Lattnera4f19972010-09-21 18:58:22 +00006883 MachinePointerInfo(StoresToEmit[i].second),
David Greene39c6d012010-02-15 17:00:31 +00006884 false, false, 0);
Bill Wendlingac087582009-12-22 01:25:10 +00006885 OutChains.push_back(Val);
Bill Wendlingac087582009-12-22 01:25:10 +00006886 }
6887
Dan Gohman575fad32008-09-03 16:12:24 +00006888 if (!OutChains.empty())
Craig Topper48d114b2014-04-26 18:35:24 +00006889 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
Bill Wendlingac087582009-12-22 01:25:10 +00006890
Dan Gohman575fad32008-09-03 16:12:24 +00006891 DAG.setRoot(Chain);
6892}
6893
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006894void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006895 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
Bill Wendling91313062009-12-23 00:44:51 +00006896 MVT::Other, getRoot(),
Gabor Greifeba0be72010-06-25 09:38:13 +00006897 getValue(I.getArgOperand(0)),
6898 DAG.getSrcValue(I.getArgOperand(0))));
Dan Gohman575fad32008-09-03 16:12:24 +00006899}
6900
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006901void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
Eric Christopher58a24612014-10-08 09:50:54 +00006902 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6903 const DataLayout &DL = *TLI.getDataLayout();
6904 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurSDLoc(),
Dale Johannesen3a09f552009-02-03 23:04:43 +00006905 getRoot(), getValue(I.getOperand(0)),
Rafael Espindolaa76eccf2010-07-11 04:01:49 +00006906 DAG.getSrcValue(I.getOperand(0)),
Rafael Espindola5f57f462014-02-21 18:34:28 +00006907 DL.getABITypeAlignment(I.getType()));
Dan Gohman575fad32008-09-03 16:12:24 +00006908 setValue(&I, V);
6909 DAG.setRoot(V.getValue(1));
6910}
6911
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006912void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006913 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
Bill Wendling91313062009-12-23 00:44:51 +00006914 MVT::Other, getRoot(),
Gabor Greifeba0be72010-06-25 09:38:13 +00006915 getValue(I.getArgOperand(0)),
6916 DAG.getSrcValue(I.getArgOperand(0))));
Dan Gohman575fad32008-09-03 16:12:24 +00006917}
6918
Dan Gohmanbcaf6812010-04-15 01:51:59 +00006919void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006920 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
Bill Wendling91313062009-12-23 00:44:51 +00006921 MVT::Other, getRoot(),
Gabor Greifeba0be72010-06-25 09:38:13 +00006922 getValue(I.getArgOperand(0)),
6923 getValue(I.getArgOperand(1)),
6924 DAG.getSrcValue(I.getArgOperand(0)),
6925 DAG.getSrcValue(I.getArgOperand(1))));
Dan Gohman575fad32008-09-03 16:12:24 +00006926}
6927
Andrew Trick74f4c742013-10-31 17:18:24 +00006928/// \brief Lower an argument list according to the target calling convention.
6929///
6930/// \return A tuple of <return-value, token-chain>
6931///
6932/// This is a helper for lowering intrinsics that follow a target calling
6933/// convention or require stack pointer adjustment. Only a subset of the
6934/// intrinsic's operands need to participate in the calling convention.
6935std::pair<SDValue, SDValue>
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00006936SelectionDAGBuilder::lowerCallOperands(ImmutableCallSite CS, unsigned ArgIdx,
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00006937 unsigned NumArgs, SDValue Callee,
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00006938 bool UseVoidTy,
6939 MachineBasicBlock *LandingPad) {
Andrew Trick74f4c742013-10-31 17:18:24 +00006940 TargetLowering::ArgListTy Args;
6941 Args.reserve(NumArgs);
6942
6943 // Populate the argument list.
6944 // Attributes for args start at offset 1, after the return attribute.
Andrew Trick74f4c742013-10-31 17:18:24 +00006945 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
6946 ArgI != ArgE; ++ArgI) {
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00006947 const Value *V = CS->getOperand(ArgI);
Andrew Trick74f4c742013-10-31 17:18:24 +00006948
6949 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
6950
6951 TargetLowering::ArgListEntry Entry;
6952 Entry.Node = getValue(V);
6953 Entry.Ty = V->getType();
6954 Entry.setAttributes(&CS, AttrI);
6955 Args.push_back(Entry);
6956 }
6957
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00006958 Type *retTy = UseVoidTy ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
Saleem Abdulrasoolf3a5a5c2014-05-17 21:50:17 +00006959 TargetLowering::CallLoweringInfo CLI(DAG);
6960 CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00006961 .setCallee(CS.getCallingConv(), retTy, Callee, std::move(Args), NumArgs)
6962 .setDiscardResult(CS->use_empty());
Andrew Trick74f4c742013-10-31 17:18:24 +00006963
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00006964 return lowerInvokable(CLI, LandingPad);
Andrew Trick74f4c742013-10-31 17:18:24 +00006965}
6966
Andrew Trick4a1abb72013-11-22 19:07:36 +00006967/// \brief Add a stack map intrinsic call's live variable operands to a stackmap
6968/// or patchpoint target node's operand list.
Andrew Trick391dbad2013-11-26 02:03:25 +00006969///
6970/// Constants are converted to TargetConstants purely as an optimization to
6971/// avoid constant materialization and register allocation.
6972///
6973/// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
6974/// generate addess computation nodes, and so ExpandISelPseudo can convert the
6975/// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
6976/// address materialization and register allocation, but may also be required
6977/// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
6978/// alloca in the entry block, then the runtime may assume that the alloca's
6979/// StackMap location can be read immediately after compilation and that the
6980/// location is valid at any point during execution (this is similar to the
6981/// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
6982/// only available in a register, then the runtime would need to trap when
6983/// execution reaches the StackMap in order to read the alloca's location.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00006984static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
Andrew Trick4a1abb72013-11-22 19:07:36 +00006985 SmallVectorImpl<SDValue> &Ops,
6986 SelectionDAGBuilder &Builder) {
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00006987 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
6988 SDValue OpVal = Builder.getValue(CS.getArgument(i));
Andrew Trick4a1abb72013-11-22 19:07:36 +00006989 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
6990 Ops.push_back(
6991 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
6992 Ops.push_back(
6993 Builder.DAG.getTargetConstant(C->getSExtValue(), MVT::i64));
Andrew Trick391dbad2013-11-26 02:03:25 +00006994 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
6995 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
6996 Ops.push_back(
6997 Builder.DAG.getTargetFrameIndex(FI->getIndex(), TLI.getPointerTy()));
Andrew Trick4a1abb72013-11-22 19:07:36 +00006998 } else
6999 Ops.push_back(OpVal);
7000 }
7001}
7002
Andrew Trick74f4c742013-10-31 17:18:24 +00007003/// \brief Lower llvm.experimental.stackmap directly to its target opcode.
7004void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
7005 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
7006 // [live variables...])
7007
7008 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
7009
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00007010 SDValue Chain, InFlag, Callee, NullPtr;
7011 SmallVector<SDValue, 32> Ops;
Andrew Trick74f4c742013-10-31 17:18:24 +00007012
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00007013 SDLoc DL = getCurSDLoc();
7014 Callee = getValue(CI.getCalledValue());
7015 NullPtr = DAG.getIntPtrConstant(0, true);
Andrew Trick74f4c742013-10-31 17:18:24 +00007016
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00007017 // The stackmap intrinsic only records the live variables (the arguemnts
7018 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
7019 // intrinsic, this won't be lowered to a function call. This means we don't
7020 // have to worry about calling conventions and target specific lowering code.
7021 // Instead we perform the call lowering right here.
7022 //
7023 // chain, flag = CALLSEQ_START(chain, 0)
7024 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
7025 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
7026 //
7027 Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL);
7028 InFlag = Chain.getValue(1);
Andrew Trick74f4c742013-10-31 17:18:24 +00007029
Juergen Ributzkaaa30da32014-02-12 22:17:10 +00007030 // Add the <id> and <numBytes> constants.
7031 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
7032 Ops.push_back(DAG.getTargetConstant(
7033 cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i64));
7034 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
7035 Ops.push_back(DAG.getTargetConstant(
7036 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00007037
Andrew Trick74f4c742013-10-31 17:18:24 +00007038 // Push live variables for the stack map.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007039 addStackMapLiveVars(&CI, 2, Ops, *this);
Andrew Trick74f4c742013-10-31 17:18:24 +00007040
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00007041 // We are not pushing any register mask info here on the operands list,
7042 // because the stackmap doesn't clobber anything.
Andrew Trick74f4c742013-10-31 17:18:24 +00007043
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00007044 // Push the chain and the glue flag.
7045 Ops.push_back(Chain);
7046 Ops.push_back(InFlag);
Andrew Trick74f4c742013-10-31 17:18:24 +00007047
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00007048 // Create the STACKMAP node.
Andrew Trick74f4c742013-10-31 17:18:24 +00007049 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00007050 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
7051 Chain = SDValue(SM, 0);
7052 InFlag = Chain.getValue(1);
Andrew Trick6664df12013-11-05 22:44:04 +00007053
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00007054 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
Andrew Trick6664df12013-11-05 22:44:04 +00007055
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00007056 // Stackmaps don't generate values, so nothing goes into the NodeMap.
Andrew Trick6664df12013-11-05 22:44:04 +00007057
Juergen Ributzkad1777cc2014-02-12 22:17:13 +00007058 // Set the root to the target-lowered call chain.
7059 DAG.setRoot(Chain);
Juergen Ributzkae8294752013-12-14 06:53:06 +00007060
7061 // Inform the Frame Information that we have a stackmap in this function.
7062 FuncInfo.MF->getFrameInfo()->setHasStackMap();
Andrew Trick74f4c742013-10-31 17:18:24 +00007063}
7064
7065/// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007066void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
7067 MachineBasicBlock *LandingPad) {
Andrew Tricke8cba372013-12-13 18:37:10 +00007068 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
Andrew Trick561f2212013-11-14 06:54:10 +00007069 // i32 <numBytes>,
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007070 // i8* <target>,
7071 // i32 <numArgs>,
7072 // [Args...],
7073 // [live variables...])
Andrew Trick74f4c742013-10-31 17:18:24 +00007074
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007075 CallingConv::ID CC = CS.getCallingConv();
7076 bool IsAnyRegCC = CC == CallingConv::AnyReg;
7077 bool HasDef = !CS->getType()->isVoidTy();
7078 SDValue Callee = getValue(CS->getOperand(2)); // <target>
Andrew Trick74f4c742013-10-31 17:18:24 +00007079
7080 // Get the real number of arguments participating in the call <numArgs>
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007081 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
Andrew Tricka2428e02013-11-22 19:07:33 +00007082 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
Andrew Trick74f4c742013-10-31 17:18:24 +00007083
7084 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
Andrew Tricka2428e02013-11-22 19:07:33 +00007085 // Intrinsics include all meta-operands up to but not including CC.
7086 unsigned NumMetaOpers = PatchPointOpers::CCPos;
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007087 assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
Andrew Trick74f4c742013-10-31 17:18:24 +00007088 "Not enough arguments provided to the patchpoint intrinsic");
7089
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007090 // For AnyRegCC the arguments are lowered later on manually.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007091 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
Andrew Trick74f4c742013-10-31 17:18:24 +00007092 std::pair<SDValue, SDValue> Result =
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007093 lowerCallOperands(CS, NumMetaOpers, NumCallArgs, Callee, IsAnyRegCC,
7094 LandingPad);
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007095
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007096 SDNode *CallEnd = Result.second.getNode();
7097 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007098 CallEnd = CallEnd->getOperand(0).getNode();
7099
Andrew Trick74f4c742013-10-31 17:18:24 +00007100 /// Get a call instruction from the call sequence chain.
7101 /// Tail calls are not allowed.
7102 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
7103 "Expected a callseq node.");
7104 SDNode *Call = CallEnd->getOperand(0).getNode();
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007105 bool HasGlue = Call->getGluedNode();
Andrew Trick74f4c742013-10-31 17:18:24 +00007106
7107 // Replace the target specific call node with the patchable intrinsic.
7108 SmallVector<SDValue, 8> Ops;
7109
Andrew Tricka2428e02013-11-22 19:07:33 +00007110 // Add the <id> and <numBytes> constants.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007111 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
Andrew Tricka2428e02013-11-22 19:07:33 +00007112 Ops.push_back(DAG.getTargetConstant(
Andrew Tricke8cba372013-12-13 18:37:10 +00007113 cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i64));
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007114 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
Andrew Tricka2428e02013-11-22 19:07:33 +00007115 Ops.push_back(DAG.getTargetConstant(
7116 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
7117
Andrew Trick74f4c742013-10-31 17:18:24 +00007118 // Assume that the Callee is a constant address.
Andrew Tricka2428e02013-11-22 19:07:33 +00007119 // FIXME: handle function symbols in the future.
Andrew Trick74f4c742013-10-31 17:18:24 +00007120 Ops.push_back(
Juergen Ributzka87ed9062013-11-09 01:51:33 +00007121 DAG.getIntPtrConstant(cast<ConstantSDNode>(Callee)->getZExtValue(),
7122 /*isTarget=*/true));
Andrew Trick74f4c742013-10-31 17:18:24 +00007123
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007124 // Adjust <numArgs> to account for any arguments that have been passed on the
7125 // stack instead.
Andrew Trick74f4c742013-10-31 17:18:24 +00007126 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007127 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
7128 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007129 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, MVT::i32));
7130
7131 // Add the calling convention
Juergen Ributzka87ed9062013-11-09 01:51:33 +00007132 Ops.push_back(DAG.getTargetConstant((unsigned)CC, MVT::i32));
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007133
7134 // Add the arguments we omitted previously. The register allocator should
7135 // place these in any free register.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007136 if (IsAnyRegCC)
Andrew Tricka2428e02013-11-22 19:07:33 +00007137 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007138 Ops.push_back(getValue(CS.getArgument(i)));
Andrew Trick74f4c742013-10-31 17:18:24 +00007139
Andrew Tricka2428e02013-11-22 19:07:33 +00007140 // Push the arguments from the call instruction up to the register mask.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007141 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
Andrew Trick74f4c742013-10-31 17:18:24 +00007142 for (SDNode::op_iterator i = Call->op_begin()+2; i != e; ++i)
7143 Ops.push_back(*i);
7144
7145 // Push live variables for the stack map.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007146 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, Ops, *this);
Andrew Trick74f4c742013-10-31 17:18:24 +00007147
7148 // Push the register mask info.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007149 if (HasGlue)
Andrew Trick74f4c742013-10-31 17:18:24 +00007150 Ops.push_back(*(Call->op_end()-2));
7151 else
7152 Ops.push_back(*(Call->op_end()-1));
7153
7154 // Push the chain (this is originally the first operand of the call, but
7155 // becomes now the last or second to last operand).
7156 Ops.push_back(*(Call->op_begin()));
7157
7158 // Push the glue flag (last operand).
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007159 if (HasGlue)
Andrew Trick74f4c742013-10-31 17:18:24 +00007160 Ops.push_back(*(Call->op_end()-1));
7161
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007162 SDVTList NodeTys;
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007163 if (IsAnyRegCC && HasDef) {
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007164 // Create the return types based on the intrinsic definition
7165 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7166 SmallVector<EVT, 3> ValueVTs;
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007167 ComputeValueVTs(TLI, CS->getType(), ValueVTs);
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007168 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
Andrew Trick6664df12013-11-05 22:44:04 +00007169
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007170 // There is always a chain and a glue type at the end
7171 ValueVTs.push_back(MVT::Other);
7172 ValueVTs.push_back(MVT::Glue);
Craig Topperabb4ac72014-04-16 06:10:51 +00007173 NodeTys = DAG.getVTList(ValueVTs);
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007174 } else
7175 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7176
7177 // Replace the target specific call node with a PATCHPOINT node.
Andrew Trick6664df12013-11-05 22:44:04 +00007178 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
7179 getCurSDLoc(), NodeTys, Ops);
7180
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007181 // Update the NodeMap.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007182 if (HasDef) {
7183 if (IsAnyRegCC)
7184 setValue(CS.getInstruction(), SDValue(MN, 0));
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007185 else
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007186 setValue(CS.getInstruction(), Result.first);
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007187 }
Andrew Trick6664df12013-11-05 22:44:04 +00007188
7189 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007190 // call sequence. Furthermore the location of the chain and glue can change
7191 // when the AnyReg calling convention is used and the intrinsic returns a
7192 // value.
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00007193 if (IsAnyRegCC && HasDef) {
Juergen Ributzka9969d3e2013-11-08 23:28:16 +00007194 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
7195 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
7196 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7197 } else
7198 DAG.ReplaceAllUsesWith(Call, MN);
Andrew Trick6664df12013-11-05 22:44:04 +00007199 DAG.DeleteNode(Call);
Juergen Ributzkae8294752013-12-14 06:53:06 +00007200
7201 // Inform the Frame Information that we have a patchpoint in this function.
7202 FuncInfo.MF->getFrameInfo()->setHasPatchPoint();
Andrew Trick74f4c742013-10-31 17:18:24 +00007203}
7204
Tim Northoverd82ed2e2014-06-18 11:52:44 +00007205/// Returns an AttributeSet representing the attributes applied to the return
7206/// value of the given call.
7207static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
7208 SmallVector<Attribute::AttrKind, 2> Attrs;
7209 if (CLI.RetSExt)
7210 Attrs.push_back(Attribute::SExt);
7211 if (CLI.RetZExt)
7212 Attrs.push_back(Attribute::ZExt);
7213 if (CLI.IsInReg)
7214 Attrs.push_back(Attribute::InReg);
7215
7216 return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex,
7217 Attrs);
7218}
7219
Dan Gohman575fad32008-09-03 16:12:24 +00007220/// TargetLowering::LowerCallTo - This is the default LowerCallTo
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007221/// implementation, which just calls LowerCall.
7222/// FIXME: When all targets are
7223/// migrated to using LowerCall, this hook should be integrated into SDISel.
Dan Gohman575fad32008-09-03 16:12:24 +00007224std::pair<SDValue, SDValue>
Justin Holewinskiaa583972012-05-25 16:35:28 +00007225TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
Stephen Lin699808c2013-04-30 22:49:28 +00007226 // Handle the incoming return values from the call.
7227 CLI.Ins.clear();
Tim Northoverd82ed2e2014-06-18 11:52:44 +00007228 Type *OrigRetTy = CLI.RetTy;
Stephen Lin699808c2013-04-30 22:49:28 +00007229 SmallVector<EVT, 4> RetTys;
Tim Northoverd82ed2e2014-06-18 11:52:44 +00007230 SmallVector<uint64_t, 4> Offsets;
7231 ComputeValueVTs(*this, CLI.RetTy, RetTys, &Offsets);
7232
7233 SmallVector<ISD::OutputArg, 4> Outs;
7234 GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this);
7235
7236 bool CanLowerReturn =
7237 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
7238 CLI.IsVarArg, Outs, CLI.RetTy->getContext());
7239
7240 SDValue DemoteStackSlot;
7241 int DemoteStackIdx = -100;
7242 if (!CanLowerReturn) {
7243 // FIXME: equivalent assert?
7244 // assert(!CS.hasInAllocaArgument() &&
7245 // "sret demotion is incompatible with inalloca");
7246 uint64_t TySize = getDataLayout()->getTypeAllocSize(CLI.RetTy);
7247 unsigned Align = getDataLayout()->getPrefTypeAlignment(CLI.RetTy);
7248 MachineFunction &MF = CLI.DAG.getMachineFunction();
7249 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
7250 Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
7251
7252 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy());
7253 ArgListEntry Entry;
7254 Entry.Node = DemoteStackSlot;
7255 Entry.Ty = StackSlotPtrType;
7256 Entry.isSExt = false;
7257 Entry.isZExt = false;
7258 Entry.isInReg = false;
7259 Entry.isSRet = true;
7260 Entry.isNest = false;
7261 Entry.isByVal = false;
7262 Entry.isReturned = false;
7263 Entry.Alignment = Align;
7264 CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
7265 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
7266 } else {
7267 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7268 EVT VT = RetTys[I];
7269 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7270 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7271 for (unsigned i = 0; i != NumRegs; ++i) {
7272 ISD::InputArg MyFlags;
7273 MyFlags.VT = RegisterVT;
7274 MyFlags.ArgVT = VT;
7275 MyFlags.Used = CLI.IsReturnValueUsed;
7276 if (CLI.RetSExt)
7277 MyFlags.Flags.setSExt();
7278 if (CLI.RetZExt)
7279 MyFlags.Flags.setZExt();
7280 if (CLI.IsInReg)
7281 MyFlags.Flags.setInReg();
7282 CLI.Ins.push_back(MyFlags);
7283 }
Stephen Lin699808c2013-04-30 22:49:28 +00007284 }
7285 }
7286
Dan Gohman575fad32008-09-03 16:12:24 +00007287 // Handle all of the outgoing arguments.
Justin Holewinskiaa583972012-05-25 16:35:28 +00007288 CLI.Outs.clear();
7289 CLI.OutVals.clear();
Saleem Abdulrasool9f664c12014-05-17 21:50:01 +00007290 ArgListTy &Args = CLI.getArgs();
Dan Gohman575fad32008-09-03 16:12:24 +00007291 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007292 SmallVector<EVT, 4> ValueVTs;
Dan Gohman575fad32008-09-03 16:12:24 +00007293 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
Oliver Stannardc24f2172014-05-09 14:01:47 +00007294 Type *FinalType = Args[i].Ty;
7295 if (Args[i].isByVal)
7296 FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
7297 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
7298 FinalType, CLI.CallConv, CLI.IsVarArg);
7299 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
7300 ++Value) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007301 EVT VT = ValueVTs[Value];
Justin Holewinskiaa583972012-05-25 16:35:28 +00007302 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
Chris Lattner160e8ab2008-10-18 18:49:30 +00007303 SDValue Op = SDValue(Args[i].Node.getNode(),
7304 Args[i].Node.getResNo() + Value);
Dan Gohman575fad32008-09-03 16:12:24 +00007305 ISD::ArgFlagsTy Flags;
Matt Arsenault443252c2014-04-21 18:39:13 +00007306 unsigned OriginalAlignment = getDataLayout()->getABITypeAlignment(ArgTy);
Dan Gohman575fad32008-09-03 16:12:24 +00007307
7308 if (Args[i].isZExt)
7309 Flags.setZExt();
7310 if (Args[i].isSExt)
7311 Flags.setSExt();
7312 if (Args[i].isInReg)
7313 Flags.setInReg();
7314 if (Args[i].isSRet)
7315 Flags.setSRet();
Reid Klecknerf5b76512014-01-31 23:50:57 +00007316 if (Args[i].isByVal)
Dan Gohman575fad32008-09-03 16:12:24 +00007317 Flags.setByVal();
Reid Klecknerf5b76512014-01-31 23:50:57 +00007318 if (Args[i].isInAlloca) {
7319 Flags.setInAlloca();
7320 // Set the byval flag for CCAssignFn callbacks that don't know about
7321 // inalloca. This way we can know how many bytes we should've allocated
7322 // and how many bytes a callee cleanup function will pop. If we port
7323 // inalloca to more targets, we'll have to add custom inalloca handling
7324 // in the various CC lowering callbacks.
7325 Flags.setByVal();
7326 }
7327 if (Args[i].isByVal || Args[i].isInAlloca) {
Chris Lattner229907c2011-07-18 04:54:35 +00007328 PointerType *Ty = cast<PointerType>(Args[i].Ty);
7329 Type *ElementTy = Ty->getElementType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00007330 Flags.setByValSize(getDataLayout()->getTypeAllocSize(ElementTy));
Dan Gohman575fad32008-09-03 16:12:24 +00007331 // For ByVal, alignment should come from FE. BE will guess if this
7332 // info is not there but there are cases it cannot get right.
Chris Lattner68254fc2011-05-22 23:23:02 +00007333 unsigned FrameAlign;
Dan Gohman575fad32008-09-03 16:12:24 +00007334 if (Args[i].Alignment)
7335 FrameAlign = Args[i].Alignment;
Chris Lattner68254fc2011-05-22 23:23:02 +00007336 else
7337 FrameAlign = getByValTypeAlignment(ElementTy);
Dan Gohman575fad32008-09-03 16:12:24 +00007338 Flags.setByValAlign(FrameAlign);
Dan Gohman575fad32008-09-03 16:12:24 +00007339 }
7340 if (Args[i].isNest)
7341 Flags.setNest();
Oliver Stannard51b1d462014-08-21 12:50:31 +00007342 if (NeedsRegBlock) {
Oliver Stannardc24f2172014-05-09 14:01:47 +00007343 Flags.setInConsecutiveRegs();
Oliver Stannard51b1d462014-08-21 12:50:31 +00007344 if (Value == NumValues - 1)
7345 Flags.setInConsecutiveRegsLast();
7346 }
Dan Gohman575fad32008-09-03 16:12:24 +00007347 Flags.setOrigAlign(OriginalAlignment);
7348
Patrik Hagglundbad545c2012-12-19 11:48:16 +00007349 MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
Justin Holewinskiaa583972012-05-25 16:35:28 +00007350 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
Dan Gohman575fad32008-09-03 16:12:24 +00007351 SmallVector<SDValue, 4> Parts(NumParts);
7352 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
7353
7354 if (Args[i].isSExt)
7355 ExtendKind = ISD::SIGN_EXTEND;
7356 else if (Args[i].isZExt)
7357 ExtendKind = ISD::ZERO_EXTEND;
7358
Stephen Lin699808c2013-04-30 22:49:28 +00007359 // Conservatively only handle 'returned' on non-vectors for now
7360 if (Args[i].isReturned && !Op.getValueType().isVector()) {
7361 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
7362 "unexpected use of 'returned'");
7363 // Before passing 'returned' to the target lowering code, ensure that
7364 // either the register MVT and the actual EVT are the same size or that
7365 // the return value and argument are extended in the same way; in these
7366 // cases it's safe to pass the argument register value unchanged as the
7367 // return register value (although it's at the target's option whether
7368 // to do so)
7369 // TODO: allow code generation to take advantage of partially preserved
7370 // registers rather than clobbering the entire register when the
7371 // parameter extension method is not compatible with the return
7372 // extension method
7373 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
7374 (ExtendKind != ISD::ANY_EXTEND &&
7375 CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
7376 Flags.setReturned();
7377 }
7378
Craig Topperc0196b12014-04-14 00:51:57 +00007379 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
7380 CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind);
Dan Gohman575fad32008-09-03 16:12:24 +00007381
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007382 for (unsigned j = 0; j != NumParts; ++j) {
Dan Gohman575fad32008-09-03 16:12:24 +00007383 // if it isn't first piece, alignment must be 1
Tom Stellard8d7d4de2013-10-23 00:44:24 +00007384 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
Manman Ren3d5af272012-11-01 23:49:58 +00007385 i < CLI.NumFixedArgs,
7386 i, j*Parts[j].getValueType().getStoreSize());
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007387 if (NumParts > 1 && j == 0)
7388 MyFlags.Flags.setSplit();
7389 else if (j != 0)
7390 MyFlags.Flags.setOrigAlign(1);
Dan Gohman575fad32008-09-03 16:12:24 +00007391
Justin Holewinskiaa583972012-05-25 16:35:28 +00007392 CLI.Outs.push_back(MyFlags);
7393 CLI.OutVals.push_back(Parts[j]);
Dan Gohman575fad32008-09-03 16:12:24 +00007394 }
7395 }
7396 }
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00007397
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007398 SmallVector<SDValue, 4> InVals;
Justin Holewinskiaa583972012-05-25 16:35:28 +00007399 CLI.Chain = LowerCall(CLI, InVals);
Dan Gohman695d8112009-08-06 15:37:27 +00007400
7401 // Verify that the target's LowerCall behaved as expected.
Justin Holewinskiaa583972012-05-25 16:35:28 +00007402 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
Dan Gohman695d8112009-08-06 15:37:27 +00007403 "LowerCall didn't return a valid chain!");
Justin Holewinskiaa583972012-05-25 16:35:28 +00007404 assert((!CLI.IsTailCall || InVals.empty()) &&
Dan Gohman695d8112009-08-06 15:37:27 +00007405 "LowerCall emitted a return value for a tail call!");
Justin Holewinskiaa583972012-05-25 16:35:28 +00007406 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
Dan Gohman695d8112009-08-06 15:37:27 +00007407 "LowerCall didn't emit the correct number of values!");
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007408
7409 // For a tail call, the return value is merely live-out and there aren't
7410 // any nodes in the DAG representing it. Return a special value to
7411 // indicate that a tail call has been emitted and no more Instructions
7412 // should be processed in the current block.
Justin Holewinskiaa583972012-05-25 16:35:28 +00007413 if (CLI.IsTailCall) {
7414 CLI.DAG.setRoot(CLI.Chain);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007415 return std::make_pair(SDValue(), SDValue());
7416 }
7417
Justin Holewinskiaa583972012-05-25 16:35:28 +00007418 DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
Evan Cheng180704d2010-03-11 19:38:18 +00007419 assert(InVals[i].getNode() &&
7420 "LowerCall emitted a null value!");
Justin Holewinskiaa583972012-05-25 16:35:28 +00007421 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
Evan Cheng180704d2010-03-11 19:38:18 +00007422 "LowerCall emitted a value with the wrong type!");
7423 });
7424
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007425 SmallVector<SDValue, 4> ReturnValues;
Tim Northoverd82ed2e2014-06-18 11:52:44 +00007426 if (!CanLowerReturn) {
7427 // The instruction result is the result of loading from the
7428 // hidden sret parameter.
7429 SmallVector<EVT, 1> PVTs;
7430 Type *PtrRetTy = PointerType::getUnqual(OrigRetTy);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007431
Tim Northoverd82ed2e2014-06-18 11:52:44 +00007432 ComputeValueVTs(*this, PtrRetTy, PVTs);
7433 assert(PVTs.size() == 1 && "Pointers should fit in one register");
7434 EVT PtrVT = PVTs[0];
7435
7436 unsigned NumValues = RetTys.size();
7437 ReturnValues.resize(NumValues);
7438 SmallVector<SDValue, 4> Chains(NumValues);
7439
7440 for (unsigned i = 0; i < NumValues; ++i) {
7441 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
7442 CLI.DAG.getConstant(Offsets[i], PtrVT));
7443 SDValue L = CLI.DAG.getLoad(
7444 RetTys[i], CLI.DL, CLI.Chain, Add,
7445 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]), false,
7446 false, false, 1);
7447 ReturnValues[i] = L;
7448 Chains[i] = L.getValue(1);
7449 }
7450
7451 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
7452 } else {
7453 // Collect the legal value parts into potentially illegal values
7454 // that correspond to the original function's return values.
7455 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7456 if (CLI.RetSExt)
7457 AssertOp = ISD::AssertSext;
7458 else if (CLI.RetZExt)
7459 AssertOp = ISD::AssertZext;
7460 unsigned CurReg = 0;
7461 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7462 EVT VT = RetTys[I];
7463 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7464 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7465
7466 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
7467 NumRegs, RegisterVT, VT, nullptr,
7468 AssertOp));
7469 CurReg += NumRegs;
7470 }
7471
7472 // For a function returning void, there is no return value. We can't create
7473 // such a node, so we just return a null return value in that case. In
7474 // that case, nothing will actually look at the value.
7475 if (ReturnValues.empty())
7476 return std::make_pair(SDValue(), CLI.Chain);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007477 }
7478
Justin Holewinskiaa583972012-05-25 16:35:28 +00007479 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
Craig Topper48d114b2014-04-26 18:35:24 +00007480 CLI.DAG.getVTList(RetTys), ReturnValues);
Justin Holewinskiaa583972012-05-25 16:35:28 +00007481 return std::make_pair(Res, CLI.Chain);
Dan Gohman575fad32008-09-03 16:12:24 +00007482}
7483
Duncan Sandsbe7e4142009-01-21 09:00:29 +00007484void TargetLowering::LowerOperationWrapper(SDNode *N,
7485 SmallVectorImpl<SDValue> &Results,
Dan Gohman21cea8a2010-04-17 15:26:15 +00007486 SelectionDAG &DAG) const {
Duncan Sandsbe7e4142009-01-21 09:00:29 +00007487 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptaa70798c2009-01-21 04:48:39 +00007488 if (Res.getNode())
7489 Results.push_back(Res);
7490}
7491
Dan Gohman21cea8a2010-04-17 15:26:15 +00007492SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
Torok Edwinfbcc6632009-07-14 16:55:14 +00007493 llvm_unreachable("LowerOperation not implemented for this target!");
Dan Gohman575fad32008-09-03 16:12:24 +00007494}
7495
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007496void
7497SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
Dan Gohmand4322232010-07-01 01:59:43 +00007498 SDValue Op = getNonRegisterValue(V);
Dan Gohman575fad32008-09-03 16:12:24 +00007499 assert((Op.getOpcode() != ISD::CopyFromReg ||
7500 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
7501 "Copy from a reg to the same reg!");
7502 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
7503
Eric Christopher58a24612014-10-08 09:50:54 +00007504 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7505 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
Dan Gohman575fad32008-09-03 16:12:24 +00007506 SDValue Chain = DAG.getEntryNode();
Jiangning Liuffbc6902014-09-19 05:30:35 +00007507
7508 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
7509 FuncInfo.PreferredExtendType.end())
7510 ? ISD::ANY_EXTEND
7511 : FuncInfo.PreferredExtendType[V];
7512 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
Dan Gohman575fad32008-09-03 16:12:24 +00007513 PendingExports.push_back(Chain);
7514}
7515
7516#include "llvm/CodeGen/SelectionDAGISel.h"
7517
Eli Friedman441a01a2011-05-05 16:53:34 +00007518/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
7519/// entry block, return true. This includes arguments used by switches, since
7520/// the switch may expand into multiple basic blocks.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007521static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
Eli Friedman441a01a2011-05-05 16:53:34 +00007522 // With FastISel active, we may be splitting blocks, so force creation
7523 // of virtual registers for all non-dead arguments.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007524 if (FastISel)
Eli Friedman441a01a2011-05-05 16:53:34 +00007525 return A->use_empty();
7526
7527 const BasicBlock *Entry = A->getParent()->begin();
Chandler Carruthcdf47882014-03-09 03:16:01 +00007528 for (const User *U : A->users())
Eli Friedman441a01a2011-05-05 16:53:34 +00007529 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
7530 return false; // Use not in entry block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00007531
Eli Friedman441a01a2011-05-05 16:53:34 +00007532 return true;
7533}
7534
Eli Bendersky33ebf832013-02-28 23:09:18 +00007535void SelectionDAGISel::LowerArguments(const Function &F) {
Dan Gohman1a6c47f2009-11-23 18:04:58 +00007536 SelectionDAG &DAG = SDB->DAG;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007537 SDLoc dl = SDB->getCurSDLoc();
Rafael Espindola5f57f462014-02-21 18:34:28 +00007538 const DataLayout *DL = TLI->getDataLayout();
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007539 SmallVector<ISD::InputArg, 16> Ins;
Dan Gohman575fad32008-09-03 16:12:24 +00007540
Dan Gohmand16aa542010-05-29 17:03:36 +00007541 if (!FuncInfo->CanLowerReturn) {
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007542 // Put in an sret pointer parameter before all the other parameters.
7543 SmallVector<EVT, 1> ValueVTs;
Eric Christopherb17140d2014-10-08 07:32:17 +00007544 ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007545
7546 // NOTE: Assuming that a pointer will never break down to more than one VT
7547 // or one register.
7548 ISD::ArgFlagsTy Flags;
7549 Flags.setSRet();
Bill Wendlingf7719082013-06-06 00:43:09 +00007550 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
Tom Stellard8d7d4de2013-10-23 00:44:24 +00007551 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 0, 0);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007552 Ins.push_back(RetArg);
7553 }
Kenneth Uildriks07119732009-11-07 02:11:54 +00007554
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007555 // Set up the incoming argument description vector.
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007556 unsigned Idx = 1;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007557 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007558 I != E; ++I, ++Idx) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007559 SmallVector<EVT, 4> ValueVTs;
Bill Wendlingf7719082013-06-06 00:43:09 +00007560 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007561 bool isArgValueUsed = !I->use_empty();
Tom Stellard8d7d4de2013-10-23 00:44:24 +00007562 unsigned PartBase = 0;
Oliver Stannardc24f2172014-05-09 14:01:47 +00007563 Type *FinalType = I->getType();
7564 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7565 FinalType = cast<PointerType>(FinalType)->getElementType();
7566 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
7567 FinalType, F.getCallingConv(), F.isVarArg());
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007568 for (unsigned Value = 0, NumValues = ValueVTs.size();
7569 Value != NumValues; ++Value) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007570 EVT VT = ValueVTs[Value];
Chris Lattner229907c2011-07-18 04:54:35 +00007571 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007572 ISD::ArgFlagsTy Flags;
Matt Arsenault443252c2014-04-21 18:39:13 +00007573 unsigned OriginalAlignment = DL->getABITypeAlignment(ArgTy);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007574
Bill Wendling94dcaf82012-12-30 12:45:13 +00007575 if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007576 Flags.setZExt();
Bill Wendling94dcaf82012-12-30 12:45:13 +00007577 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007578 Flags.setSExt();
Bill Wendling94dcaf82012-12-30 12:45:13 +00007579 if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007580 Flags.setInReg();
Bill Wendling94dcaf82012-12-30 12:45:13 +00007581 if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007582 Flags.setSRet();
Reid Klecknerf5b76512014-01-31 23:50:57 +00007583 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007584 Flags.setByVal();
Reid Klecknerf5b76512014-01-31 23:50:57 +00007585 if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) {
7586 Flags.setInAlloca();
7587 // Set the byval flag for CCAssignFn callbacks that don't know about
7588 // inalloca. This way we can know how many bytes we should've allocated
7589 // and how many bytes a callee cleanup function will pop. If we port
7590 // inalloca to more targets, we'll have to add custom inalloca handling
7591 // in the various CC lowering callbacks.
7592 Flags.setByVal();
7593 }
7594 if (Flags.isByVal() || Flags.isInAlloca()) {
Chris Lattner229907c2011-07-18 04:54:35 +00007595 PointerType *Ty = cast<PointerType>(I->getType());
7596 Type *ElementTy = Ty->getElementType();
Rafael Espindola5f57f462014-02-21 18:34:28 +00007597 Flags.setByValSize(DL->getTypeAllocSize(ElementTy));
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007598 // For ByVal, alignment should be passed from FE. BE will guess if
7599 // this info is not there but there are cases it cannot get right.
Chris Lattner68254fc2011-05-22 23:23:02 +00007600 unsigned FrameAlign;
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007601 if (F.getParamAlignment(Idx))
7602 FrameAlign = F.getParamAlignment(Idx);
Chris Lattner68254fc2011-05-22 23:23:02 +00007603 else
Bill Wendlingf7719082013-06-06 00:43:09 +00007604 FrameAlign = TLI->getByValTypeAlignment(ElementTy);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007605 Flags.setByValAlign(FrameAlign);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007606 }
Bill Wendling94dcaf82012-12-30 12:45:13 +00007607 if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007608 Flags.setNest();
Oliver Stannard51b1d462014-08-21 12:50:31 +00007609 if (NeedsRegBlock) {
Oliver Stannardc24f2172014-05-09 14:01:47 +00007610 Flags.setInConsecutiveRegs();
Oliver Stannard51b1d462014-08-21 12:50:31 +00007611 if (Value == NumValues - 1)
7612 Flags.setInConsecutiveRegsLast();
7613 }
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007614 Flags.setOrigAlign(OriginalAlignment);
7615
Bill Wendlingf7719082013-06-06 00:43:09 +00007616 MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7617 unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007618 for (unsigned i = 0; i != NumRegs; ++i) {
Tom Stellard8d7d4de2013-10-23 00:44:24 +00007619 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
7620 Idx-1, PartBase+i*RegisterVT.getStoreSize());
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007621 if (NumRegs > 1 && i == 0)
7622 MyFlags.Flags.setSplit();
7623 // if it isn't first piece, alignment must be 1
7624 else if (i > 0)
7625 MyFlags.Flags.setOrigAlign(1);
7626 Ins.push_back(MyFlags);
7627 }
Tom Stellard8d7d4de2013-10-23 00:44:24 +00007628 PartBase += VT.getStoreSize();
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007629 }
7630 }
7631
7632 // Call the target to set up the argument values.
7633 SmallVector<SDValue, 8> InVals;
Eric Christopherb17140d2014-10-08 07:32:17 +00007634 SDValue NewRoot = TLI->LowerFormalArguments(
7635 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
Dan Gohman695d8112009-08-06 15:37:27 +00007636
7637 // Verify that the target's LowerFormalArguments behaved as expected.
Owen Anderson9f944592009-08-11 20:47:22 +00007638 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
Dan Gohman695d8112009-08-06 15:37:27 +00007639 "LowerFormalArguments didn't return a valid chain!");
7640 assert(InVals.size() == Ins.size() &&
7641 "LowerFormalArguments didn't emit the correct number of values!");
Bill Wendlingd8549812009-12-22 21:35:02 +00007642 DEBUG({
7643 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
7644 assert(InVals[i].getNode() &&
7645 "LowerFormalArguments emitted a null value!");
Duncan Sandsf5dda012010-11-03 11:35:31 +00007646 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
Bill Wendlingd8549812009-12-22 21:35:02 +00007647 "LowerFormalArguments emitted a value with the wrong type!");
7648 }
7649 });
Bill Wendling919b7aa2009-12-22 02:10:19 +00007650
Dan Gohman695d8112009-08-06 15:37:27 +00007651 // Update the DAG with the new chain value resulting from argument lowering.
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007652 DAG.setRoot(NewRoot);
7653
7654 // Set up the argument values.
7655 unsigned i = 0;
7656 Idx = 1;
Dan Gohmand16aa542010-05-29 17:03:36 +00007657 if (!FuncInfo->CanLowerReturn) {
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007658 // Create a virtual register for the sret pointer, and put in a copy
7659 // from the sret argument into it.
7660 SmallVector<EVT, 1> ValueVTs;
Bill Wendlingf7719082013-06-06 00:43:09 +00007661 ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
Patrik Hagglund5e6c3612012-12-13 06:34:11 +00007662 MVT VT = ValueVTs[0].getSimpleVT();
Bill Wendlingf7719082013-06-06 00:43:09 +00007663 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007664 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Bill Wendling78c5b7a2010-03-02 01:55:18 +00007665 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
Craig Topperc0196b12014-04-14 00:51:57 +00007666 RegVT, VT, nullptr, AssertOp);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007667
Dan Gohman1a6c47f2009-11-23 18:04:58 +00007668 MachineFunction& MF = SDB->DAG.getMachineFunction();
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007669 MachineRegisterInfo& RegInfo = MF.getRegInfo();
Bill Wendlingf7719082013-06-06 00:43:09 +00007670 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
Dan Gohmand16aa542010-05-29 17:03:36 +00007671 FuncInfo->DemoteRegister = SRetReg;
Eric Christopher58a24612014-10-08 09:50:54 +00007672 NewRoot =
7673 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007674 DAG.setRoot(NewRoot);
Bill Wendling919b7aa2009-12-22 02:10:19 +00007675
Kenneth Uildriks9f344062009-11-11 19:59:24 +00007676 // i indexes lowered arguments. Bump it past the hidden sret argument.
7677 // Idx indexes LLVM arguments. Don't touch it.
7678 ++i;
7679 }
Bill Wendling919b7aa2009-12-22 02:10:19 +00007680
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007681 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007682 ++I, ++Idx) {
7683 SmallVector<SDValue, 4> ArgValues;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007684 SmallVector<EVT, 4> ValueVTs;
Bill Wendlingf7719082013-06-06 00:43:09 +00007685 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00007686 unsigned NumValues = ValueVTs.size();
Devang Patelb0c76392010-06-01 19:59:01 +00007687
7688 // If this argument is unused then remember its value. It is used to generate
7689 // debugging information.
Adrian Prantl9c930592013-05-16 23:44:12 +00007690 if (I->use_empty() && NumValues) {
Devang Patelb0c76392010-06-01 19:59:01 +00007691 SDB->setUnusedArgValue(I, InVals[i]);
7692
Adrian Prantl9c930592013-05-16 23:44:12 +00007693 // Also remember any frame index for use in FastISel.
7694 if (FrameIndexSDNode *FI =
7695 dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
7696 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7697 }
7698
Eli Friedman441a01a2011-05-05 16:53:34 +00007699 for (unsigned Val = 0; Val != NumValues; ++Val) {
7700 EVT VT = ValueVTs[Val];
Bill Wendlingf7719082013-06-06 00:43:09 +00007701 MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7702 unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007703
7704 if (!I->use_empty()) {
7705 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Bill Wendling94dcaf82012-12-30 12:45:13 +00007706 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007707 AssertOp = ISD::AssertSext;
Bill Wendling94dcaf82012-12-30 12:45:13 +00007708 else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007709 AssertOp = ISD::AssertZext;
7710
Bill Wendling78c5b7a2010-03-02 01:55:18 +00007711 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
Bill Wendling919b7aa2009-12-22 02:10:19 +00007712 NumParts, PartVT, VT,
Craig Topperc0196b12014-04-14 00:51:57 +00007713 nullptr, AssertOp));
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007714 }
Bill Wendling919b7aa2009-12-22 02:10:19 +00007715
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007716 i += NumParts;
7717 }
Bill Wendling919b7aa2009-12-22 02:10:19 +00007718
Eli Friedman441a01a2011-05-05 16:53:34 +00007719 // We don't need to do anything else for unused arguments.
7720 if (ArgValues.empty())
7721 continue;
7722
Devang Patel9d904e12011-09-08 22:59:09 +00007723 // Note down frame index.
7724 if (FrameIndexSDNode *FI =
Bill Wendlingd1634052012-07-19 00:04:14 +00007725 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
Devang Patel9d904e12011-09-08 22:59:09 +00007726 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
Devang Patel86ec8b32010-08-31 22:22:42 +00007727
Craig Topper2d2aa0c2014-04-30 07:17:30 +00007728 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007729 SDB->getCurSDLoc());
Devang Patel9d904e12011-09-08 22:59:09 +00007730
Eli Friedman441a01a2011-05-05 16:53:34 +00007731 SDB->setValue(I, Res);
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007732 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
Stephen Lincfe7f352013-07-08 00:37:03 +00007733 if (LoadSDNode *LNode =
Devang Patel9d904e12011-09-08 22:59:09 +00007734 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
7735 if (FrameIndexSDNode *FI =
7736 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
7737 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7738 }
Bill Wendling919b7aa2009-12-22 02:10:19 +00007739
Eli Friedman441a01a2011-05-05 16:53:34 +00007740 // If this argument is live outside of the entry block, insert a copy from
7741 // wherever we got it to the vreg that other BB's will reference it as.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007742 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
Eli Friedman441a01a2011-05-05 16:53:34 +00007743 // If we can, though, try to skip creating an unnecessary vreg.
7744 // FIXME: This isn't very clean... it would be nice to make this more
Eli Friedman768de0a2011-05-10 21:50:58 +00007745 // general. It's also subtly incompatible with the hacks FastISel
7746 // uses with vregs.
Eli Friedman441a01a2011-05-05 16:53:34 +00007747 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
7748 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
7749 FuncInfo->ValueMap[I] = Reg;
7750 continue;
7751 }
7752 }
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007753 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
Eli Friedman441a01a2011-05-05 16:53:34 +00007754 FuncInfo->InitializeRegForValue(I);
Dan Gohman1a6c47f2009-11-23 18:04:58 +00007755 SDB->CopyToExportRegsIfNeeded(I);
Dan Gohman575fad32008-09-03 16:12:24 +00007756 }
Dan Gohman575fad32008-09-03 16:12:24 +00007757 }
Bill Wendling919b7aa2009-12-22 02:10:19 +00007758
Dan Gohmanf9bbcd12009-08-05 01:29:28 +00007759 assert(i == InVals.size() && "Argument register count mismatch!");
Dan Gohman575fad32008-09-03 16:12:24 +00007760
7761 // Finally, if the target has anything special to do, allow it to do so.
7762 // FIXME: this should insert code into the DAG!
Dan Gohmanc87b74d2010-04-14 20:17:22 +00007763 EmitFunctionEntryCode();
Dan Gohman575fad32008-09-03 16:12:24 +00007764}
7765
7766/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
7767/// ensure constants are generated when needed. Remember the virtual registers
7768/// that need to be added to the Machine PHI nodes as input. We cannot just
7769/// directly add them, because expansion might result in multiple MBB's for one
7770/// BB. As such, the start of the BB might correspond to a different MBB than
7771/// the end.
7772///
7773void
Dan Gohmanc594eab2010-04-22 20:46:50 +00007774SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007775 const TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohman575fad32008-09-03 16:12:24 +00007776
7777 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
7778
7779 // Check successor nodes' PHI nodes that expect a constant to be available
7780 // from this block.
7781 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007782 const BasicBlock *SuccBB = TI->getSuccessor(succ);
Dan Gohman575fad32008-09-03 16:12:24 +00007783 if (!isa<PHINode>(SuccBB->begin())) continue;
Dan Gohmanc594eab2010-04-22 20:46:50 +00007784 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00007785
Dan Gohman575fad32008-09-03 16:12:24 +00007786 // If this terminator has multiple identical successors (common for
7787 // switches), only handle each succ once.
David Blaikie70573dc2014-11-19 07:49:26 +00007788 if (!SuccsHandled.insert(SuccMBB).second)
7789 continue;
Mikhail Glushenkovb2f9a732009-01-16 06:53:46 +00007790
Dan Gohman575fad32008-09-03 16:12:24 +00007791 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Dan Gohman575fad32008-09-03 16:12:24 +00007792
7793 // At this point we know that there is a 1-1 correspondence between LLVM PHI
7794 // nodes and Machine PHI nodes, but the incoming operands have not been
7795 // emitted yet.
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007796 for (BasicBlock::const_iterator I = SuccBB->begin();
7797 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Dan Gohman575fad32008-09-03 16:12:24 +00007798 // Ignore dead phi's.
7799 if (PN->use_empty()) continue;
7800
Rafael Espindolae53b7d12011-05-13 15:18:06 +00007801 // Skip empty types
7802 if (PN->getType()->isEmptyTy())
7803 continue;
7804
Dan Gohman575fad32008-09-03 16:12:24 +00007805 unsigned Reg;
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007806 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Dan Gohman575fad32008-09-03 16:12:24 +00007807
Dan Gohmanbcaf6812010-04-15 01:51:59 +00007808 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
Dan Gohmanc594eab2010-04-22 20:46:50 +00007809 unsigned &RegOut = ConstantsOut[C];
Dan Gohman575fad32008-09-03 16:12:24 +00007810 if (RegOut == 0) {
Dan Gohman93f59202010-07-02 00:10:16 +00007811 RegOut = FuncInfo.CreateRegs(C->getType());
Dan Gohmanc594eab2010-04-22 20:46:50 +00007812 CopyValueToVirtualRegister(C, RegOut);
Dan Gohman575fad32008-09-03 16:12:24 +00007813 }
7814 Reg = RegOut;
7815 } else {
Dan Gohman9576645a2010-07-01 01:33:21 +00007816 DenseMap<const Value *, unsigned>::iterator I =
7817 FuncInfo.ValueMap.find(PHIOp);
7818 if (I != FuncInfo.ValueMap.end())
7819 Reg = I->second;
7820 else {
Dan Gohman575fad32008-09-03 16:12:24 +00007821 assert(isa<AllocaInst>(PHIOp) &&
Dan Gohmanc594eab2010-04-22 20:46:50 +00007822 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
Dan Gohman575fad32008-09-03 16:12:24 +00007823 "Didn't codegen value into a register!??");
Dan Gohman93f59202010-07-02 00:10:16 +00007824 Reg = FuncInfo.CreateRegs(PHIOp->getType());
Dan Gohmanc594eab2010-04-22 20:46:50 +00007825 CopyValueToVirtualRegister(PHIOp, Reg);
Dan Gohman575fad32008-09-03 16:12:24 +00007826 }
7827 }
7828
7829 // Remember that this register needs to added to the machine PHI node as
7830 // the input for this MBB.
Owen Anderson53aa7a92009-08-10 22:56:29 +00007831 SmallVector<EVT, 4> ValueVTs;
Eric Christopher58a24612014-10-08 09:50:54 +00007832 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7833 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
Dan Gohman575fad32008-09-03 16:12:24 +00007834 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007835 EVT VT = ValueVTs[vti];
Eric Christopher58a24612014-10-08 09:50:54 +00007836 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
Dan Gohman575fad32008-09-03 16:12:24 +00007837 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Dan Gohmanc594eab2010-04-22 20:46:50 +00007838 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Dan Gohman575fad32008-09-03 16:12:24 +00007839 Reg += NumRegisters;
7840 }
7841 }
7842 }
Bill Wendlinga3cd3502013-06-19 21:36:55 +00007843
Dan Gohmanc594eab2010-04-22 20:46:50 +00007844 ConstantsOut.clear();
Dan Gohman7bda51f2008-09-03 23:12:08 +00007845}
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00007846
7847/// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
7848/// is 0.
7849MachineBasicBlock *
7850SelectionDAGBuilder::StackProtectorDescriptor::
7851AddSuccessorMBB(const BasicBlock *BB,
7852 MachineBasicBlock *ParentMBB,
Akira Hatanakab9991a22014-12-01 04:27:03 +00007853 bool IsLikely,
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00007854 MachineBasicBlock *SuccMBB) {
7855 // If SuccBB has not been created yet, create it.
7856 if (!SuccMBB) {
7857 MachineFunction *MF = ParentMBB->getParent();
7858 MachineFunction::iterator BBI = ParentMBB;
7859 SuccMBB = MF->CreateMachineBasicBlock(BB);
7860 MF->insert(++BBI, SuccMBB);
7861 }
7862 // Add it as a successor of ParentMBB.
Akira Hatanakab9991a22014-12-01 04:27:03 +00007863 ParentMBB->addSuccessor(
7864 SuccMBB, BranchProbabilityInfo::getBranchWeightStackProtector(IsLikely));
Michael Gottesmanb27f0f12013-08-20 07:00:16 +00007865 return SuccMBB;
7866}