blob: b587884b5048aee5d86da52c33f478365c4831c3 [file] [log] [blame]
Dan Gohman2048b852009-11-23 18:04:58 +00001//===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
Dan Gohmanf0cbcd42008-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
14#define DEBUG_TYPE "isel"
Devang Patel00190342010-03-15 19:15:44 +000015#include "SDNodeDbgValue.h"
Dan Gohman2048b852009-11-23 18:04:58 +000016#include "SelectionDAGBuilder.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000017#include "llvm/ADT/BitVector.h"
Michael J. Spencer84ac4d52010-10-16 08:25:41 +000018#include "llvm/ADT/PostOrderIterator.h"
Dan Gohman5b229802008-09-04 20:49:27 +000019#include "llvm/ADT/SmallSet.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000020#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner8047d9a2009-12-24 00:37:38 +000021#include "llvm/Analysis/ConstantFolding.h"
Nadav Rotemc05d3062012-09-06 09:17:37 +000022#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000023#include "llvm/Constants.h"
24#include "llvm/CallingConv.h"
Bill Wendling0bcbd1d2012-06-28 00:05:13 +000025#include "llvm/DebugInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000026#include "llvm/DerivedTypes.h"
27#include "llvm/Function.h"
28#include "llvm/GlobalVariable.h"
29#include "llvm/InlineAsm.h"
30#include "llvm/Instructions.h"
31#include "llvm/Intrinsics.h"
32#include "llvm/IntrinsicInst.h"
Chris Lattner6129c372010-04-08 00:09:16 +000033#include "llvm/LLVMContext.h"
Bill Wendlingb2a42982008-11-06 02:29:10 +000034#include "llvm/Module.h"
Dan Gohman5eb6d652010-04-21 01:22:34 +000035#include "llvm/CodeGen/Analysis.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000036#include "llvm/CodeGen/FastISel.h"
Dan Gohman4c3fd9f2010-07-07 16:01:37 +000037#include "llvm/CodeGen/FunctionLoweringInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000038#include "llvm/CodeGen/GCStrategy.h"
39#include "llvm/CodeGen/GCMetadata.h"
40#include "llvm/CodeGen/MachineFunction.h"
41#include "llvm/CodeGen/MachineFrameInfo.h"
42#include "llvm/CodeGen/MachineInstrBuilder.h"
43#include "llvm/CodeGen/MachineJumpTableInfo.h"
44#include "llvm/CodeGen/MachineModuleInfo.h"
45#include "llvm/CodeGen/MachineRegisterInfo.h"
46#include "llvm/CodeGen/SelectionDAG.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000047#include "llvm/Target/TargetData.h"
Anton Korobeynikov16c29b52011-01-10 12:39:04 +000048#include "llvm/Target/TargetFrameLowering.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000049#include "llvm/Target/TargetInstrInfo.h"
Dale Johannesen49de9822009-02-05 01:49:45 +000050#include "llvm/Target/TargetIntrinsicInfo.h"
Owen Anderson243eb9e2011-12-08 22:15:21 +000051#include "llvm/Target/TargetLibraryInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000052#include "llvm/Target/TargetLowering.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000053#include "llvm/Target/TargetOptions.h"
Mikhail Glushenkov2388a582009-01-16 07:02:28 +000054#include "llvm/Support/CommandLine.h"
Stepan Dyatkovskiy0aa32d52012-05-29 12:26:47 +000055#include "llvm/Support/IntegersSubsetMapping.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000056#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000057#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000058#include "llvm/Support/MathExtras.h"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +000059#include "llvm/Support/raw_ostream.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000060#include <algorithm>
61using namespace llvm;
62
Dale Johannesen601d3c02008-09-05 01:48:15 +000063/// LimitFloatPrecision - Generate low-precision inline sequences for
64/// some float libcalls (6, 8 or 12 bits).
65static unsigned LimitFloatPrecision;
66
67static cl::opt<unsigned, true>
68LimitFPPrecision("limit-float-precision",
69 cl::desc("Generate low-precision inline sequences "
70 "for some float libcalls"),
71 cl::location(LimitFloatPrecision),
72 cl::init(0));
73
Andrew Trickde91f3c2010-11-12 17:50:46 +000074// Limit the width of DAG chains. This is important in general to prevent
75// prevent DAG-based analysis from blowing up. For example, alias analysis and
76// load clustering may not complete in reasonable time. It is difficult to
77// recognize and avoid this situation within each individual analysis, and
78// future analyses are likely to have the same behavior. Limiting DAG width is
Andrew Trickb9e6fe12010-11-20 07:26:51 +000079// the safe approach, and will be especially important with global DAGs.
Andrew Trickde91f3c2010-11-12 17:50:46 +000080//
81// MaxParallelChains default is arbitrarily high to avoid affecting
82// optimization, but could be lowered to improve compile time. Any ld-ld-st-st
Andrew Trickb9e6fe12010-11-20 07:26:51 +000083// sequence over this should have been converted to llvm.memcpy by the
84// frontend. It easy to induce this behavior with .ll code such as:
85// %buffer = alloca [4096 x i8]
86// %data = load [4096 x i8]* %argPtr
87// store [4096 x i8] %data, [4096 x i8]* %buffer
Andrew Trick778583a2011-03-11 17:46:59 +000088static const unsigned MaxParallelChains = 64;
Andrew Trickde91f3c2010-11-12 17:50:46 +000089
Chris Lattner3ac18842010-08-24 23:20:40 +000090static SDValue getCopyFromPartsVector(SelectionDAG &DAG, DebugLoc DL,
91 const SDValue *Parts, unsigned NumParts,
92 EVT PartVT, EVT ValueVT);
Michael J. Spencere70c5262010-10-16 08:25:21 +000093
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000094/// getCopyFromParts - Create a value that contains the specified legal parts
95/// combined into the value they represent. If the parts combine to a type
96/// larger then ValueVT then AssertOp can be used to specify whether the extra
97/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
98/// (ISD::AssertSext).
Chris Lattner3ac18842010-08-24 23:20:40 +000099static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc DL,
Dale Johannesen66978ee2009-01-31 02:22:37 +0000100 const SDValue *Parts,
Owen Andersone50ed302009-08-10 22:56:29 +0000101 unsigned NumParts, EVT PartVT, EVT ValueVT,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000102 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Chris Lattner3ac18842010-08-24 23:20:40 +0000103 if (ValueVT.isVector())
104 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT);
Michael J. Spencere70c5262010-10-16 08:25:21 +0000105
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000106 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohmane9530ec2009-01-15 16:58:17 +0000107 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000108 SDValue Val = Parts[0];
109
110 if (NumParts > 1) {
111 // Assemble the value from multiple parts.
Chris Lattner3ac18842010-08-24 23:20:40 +0000112 if (ValueVT.isInteger()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000113 unsigned PartBits = PartVT.getSizeInBits();
114 unsigned ValueBits = ValueVT.getSizeInBits();
115
116 // Assemble the power of 2 part.
117 unsigned RoundParts = NumParts & (NumParts - 1) ?
118 1 << Log2_32(NumParts) : NumParts;
119 unsigned RoundBits = PartBits * RoundParts;
Owen Andersone50ed302009-08-10 22:56:29 +0000120 EVT RoundVT = RoundBits == ValueBits ?
Owen Anderson23b9b192009-08-12 00:36:31 +0000121 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000122 SDValue Lo, Hi;
123
Owen Anderson23b9b192009-08-12 00:36:31 +0000124 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000125
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000126 if (RoundParts > 2) {
Chris Lattner3ac18842010-08-24 23:20:40 +0000127 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000128 PartVT, HalfVT);
Chris Lattner3ac18842010-08-24 23:20:40 +0000129 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
Bill Wendling3ea3c242009-12-22 02:10:19 +0000130 RoundParts / 2, PartVT, HalfVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000131 } else {
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000132 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
133 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000134 }
Bill Wendling3ea3c242009-12-22 02:10:19 +0000135
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000136 if (TLI.isBigEndian())
137 std::swap(Lo, Hi);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000138
Chris Lattner3ac18842010-08-24 23:20:40 +0000139 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000140
141 if (RoundParts < NumParts) {
142 // Assemble the trailing non-power-of-2 part.
143 unsigned OddParts = NumParts - RoundParts;
Owen Anderson23b9b192009-08-12 00:36:31 +0000144 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
Chris Lattner3ac18842010-08-24 23:20:40 +0000145 Hi = getCopyFromParts(DAG, DL,
Bill Wendling3ea3c242009-12-22 02:10:19 +0000146 Parts + RoundParts, OddParts, PartVT, OddVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000147
148 // Combine the round and odd parts.
149 Lo = Val;
150 if (TLI.isBigEndian())
151 std::swap(Lo, Hi);
Owen Anderson23b9b192009-08-12 00:36:31 +0000152 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Chris Lattner3ac18842010-08-24 23:20:40 +0000153 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
154 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000155 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands92abc622009-01-31 15:50:11 +0000156 TLI.getPointerTy()));
Chris Lattner3ac18842010-08-24 23:20:40 +0000157 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
158 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000159 }
Eli Friedman2ac8b322009-05-20 06:02:09 +0000160 } else if (PartVT.isFloatingPoint()) {
161 // FP split into multiple FP parts (for ppcf128)
Owen Anderson825b72b2009-08-11 20:47:22 +0000162 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
Eli Friedman2ac8b322009-05-20 06:02:09 +0000163 "Unexpected split");
164 SDValue Lo, Hi;
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000165 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
166 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000167 if (TLI.isBigEndian())
168 std::swap(Lo, Hi);
Chris Lattner3ac18842010-08-24 23:20:40 +0000169 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000170 } else {
171 // FP split into integer parts (soft fp)
172 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
173 !PartVT.isVector() && "Unexpected split");
Owen Anderson23b9b192009-08-12 00:36:31 +0000174 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
Chris Lattner3ac18842010-08-24 23:20:40 +0000175 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000176 }
177 }
178
179 // There is now one part, held in Val. Correct it to match ValueVT.
180 PartVT = Val.getValueType();
181
182 if (PartVT == ValueVT)
183 return Val;
184
Chris Lattner3ac18842010-08-24 23:20:40 +0000185 if (PartVT.isInteger() && ValueVT.isInteger()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000186 if (ValueVT.bitsLT(PartVT)) {
187 // For a truncate, see if we have any information to
188 // indicate whether the truncated bits will always be
189 // zero or sign-extension.
190 if (AssertOp != ISD::DELETED_NODE)
Chris Lattner3ac18842010-08-24 23:20:40 +0000191 Val = DAG.getNode(AssertOp, DL, PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000192 DAG.getValueType(ValueVT));
Chris Lattner3ac18842010-08-24 23:20:40 +0000193 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000194 }
Chris Lattner3ac18842010-08-24 23:20:40 +0000195 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000196 }
197
198 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Chris Lattner3ac18842010-08-24 23:20:40 +0000199 // FP_ROUND's are always exact here.
200 if (ValueVT.bitsLT(Val.getValueType()))
201 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
Pete Cooperf57e1c22012-01-17 01:54:07 +0000202 DAG.getTargetConstant(1, TLI.getPointerTy()));
Bill Wendling3ea3c242009-12-22 02:10:19 +0000203
Chris Lattner3ac18842010-08-24 23:20:40 +0000204 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000205 }
206
Bill Wendling4533cac2010-01-28 21:51:40 +0000207 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000208 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000209
Torok Edwinc23197a2009-07-14 16:55:14 +0000210 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000211}
212
Chris Lattner3ac18842010-08-24 23:20:40 +0000213/// getCopyFromParts - Create a value that contains the specified legal parts
214/// combined into the value they represent. If the parts combine to a type
215/// larger then ValueVT then AssertOp can be used to specify whether the extra
216/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
217/// (ISD::AssertSext).
218static SDValue getCopyFromPartsVector(SelectionDAG &DAG, DebugLoc DL,
219 const SDValue *Parts, unsigned NumParts,
220 EVT PartVT, EVT ValueVT) {
221 assert(ValueVT.isVector() && "Not a vector value");
222 assert(NumParts > 0 && "No parts to assemble!");
223 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
224 SDValue Val = Parts[0];
Michael J. Spencere70c5262010-10-16 08:25:21 +0000225
Chris Lattner3ac18842010-08-24 23:20:40 +0000226 // Handle a multi-element vector.
227 if (NumParts > 1) {
228 EVT IntermediateVT, RegisterVT;
229 unsigned NumIntermediates;
230 unsigned NumRegs =
231 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
232 NumIntermediates, RegisterVT);
233 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
234 NumParts = NumRegs; // Silence a compiler warning.
235 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
236 assert(RegisterVT == Parts[0].getValueType() &&
237 "Part type doesn't match part!");
Michael J. Spencere70c5262010-10-16 08:25:21 +0000238
Chris Lattner3ac18842010-08-24 23:20:40 +0000239 // Assemble the parts into intermediate operands.
240 SmallVector<SDValue, 8> Ops(NumIntermediates);
241 if (NumIntermediates == NumParts) {
242 // If the register was not expanded, truncate or copy the value,
243 // as appropriate.
244 for (unsigned i = 0; i != NumParts; ++i)
245 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
246 PartVT, IntermediateVT);
247 } else if (NumParts > 0) {
248 // If the intermediate type was expanded, build the intermediate
249 // operands from the parts.
250 assert(NumParts % NumIntermediates == 0 &&
251 "Must expand into a divisible number of parts!");
252 unsigned Factor = NumParts / NumIntermediates;
253 for (unsigned i = 0; i != NumIntermediates; ++i)
254 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
255 PartVT, IntermediateVT);
256 }
Michael J. Spencere70c5262010-10-16 08:25:21 +0000257
Chris Lattner3ac18842010-08-24 23:20:40 +0000258 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
259 // intermediate operands.
260 Val = DAG.getNode(IntermediateVT.isVector() ?
261 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, DL,
262 ValueVT, &Ops[0], NumIntermediates);
263 }
Michael J. Spencere70c5262010-10-16 08:25:21 +0000264
Chris Lattner3ac18842010-08-24 23:20:40 +0000265 // There is now one part, held in Val. Correct it to match ValueVT.
266 PartVT = Val.getValueType();
Michael J. Spencere70c5262010-10-16 08:25:21 +0000267
Chris Lattner3ac18842010-08-24 23:20:40 +0000268 if (PartVT == ValueVT)
269 return Val;
Michael J. Spencere70c5262010-10-16 08:25:21 +0000270
Chris Lattnere6f7c262010-08-25 22:49:25 +0000271 if (PartVT.isVector()) {
272 // If the element type of the source/dest vectors are the same, but the
273 // parts vector has more elements than the value vector, then we have a
274 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
275 // elements we want.
276 if (PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
277 assert(PartVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
278 "Cannot narrow, it would be a lossy transformation");
279 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
280 DAG.getIntPtrConstant(0));
Michael J. Spencere70c5262010-10-16 08:25:21 +0000281 }
282
Chris Lattnere6f7c262010-08-25 22:49:25 +0000283 // Vector/Vector bitcast.
Nadav Rotem0b666362011-06-04 20:58:08 +0000284 if (ValueVT.getSizeInBits() == PartVT.getSizeInBits())
285 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
286
287 assert(PartVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
288 "Cannot handle this kind of promotion");
289 // Promoted vector extract
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000290 bool Smaller = ValueVT.bitsLE(PartVT);
291 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
292 DL, ValueVT, Val);
Nadav Rotem0b666362011-06-04 20:58:08 +0000293
Chris Lattnere6f7c262010-08-25 22:49:25 +0000294 }
Eric Christopher471e4222011-06-08 23:55:35 +0000295
Eric Christopher9aaa02a2011-06-01 19:55:10 +0000296 // Trivial bitcast if the types are the same size and the destination
297 // vector type is legal.
298 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits() &&
299 TLI.isTypeLegal(ValueVT))
300 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
Michael J. Spencere70c5262010-10-16 08:25:21 +0000301
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000302 // Handle cases such as i8 -> <1 x i1>
303 assert(ValueVT.getVectorNumElements() == 1 &&
Chris Lattner3ac18842010-08-24 23:20:40 +0000304 "Only trivial scalar-to-vector conversions should get here!");
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000305
306 if (ValueVT.getVectorNumElements() == 1 &&
307 ValueVT.getVectorElementType() != PartVT) {
308 bool Smaller = ValueVT.bitsLE(PartVT);
309 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
310 DL, ValueVT.getScalarType(), Val);
311 }
312
Chris Lattner3ac18842010-08-24 23:20:40 +0000313 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
314}
315
316
317
Chris Lattnera13b8602010-08-24 23:10:06 +0000318
319static void getCopyToPartsVector(SelectionDAG &DAG, DebugLoc dl,
320 SDValue Val, SDValue *Parts, unsigned NumParts,
321 EVT PartVT);
Michael J. Spencere70c5262010-10-16 08:25:21 +0000322
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000323/// getCopyToParts - Create a series of nodes that contain the specified value
324/// split into legal parts. If the parts contain more bits than Val, then, for
325/// integers, ExtendKind can be used to specify how to generate the extra bits.
Chris Lattnera13b8602010-08-24 23:10:06 +0000326static void getCopyToParts(SelectionDAG &DAG, DebugLoc DL,
Bill Wendling3ea3c242009-12-22 02:10:19 +0000327 SDValue Val, SDValue *Parts, unsigned NumParts,
328 EVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000329 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Owen Andersone50ed302009-08-10 22:56:29 +0000330 EVT ValueVT = Val.getValueType();
Michael J. Spencere70c5262010-10-16 08:25:21 +0000331
Chris Lattnera13b8602010-08-24 23:10:06 +0000332 // Handle the vector case separately.
333 if (ValueVT.isVector())
334 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT);
Michael J. Spencere70c5262010-10-16 08:25:21 +0000335
Chris Lattnera13b8602010-08-24 23:10:06 +0000336 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000337 unsigned PartBits = PartVT.getSizeInBits();
Dale Johannesen8a36f502009-02-25 22:39:13 +0000338 unsigned OrigNumParts = NumParts;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000339 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
340
Chris Lattnera13b8602010-08-24 23:10:06 +0000341 if (NumParts == 0)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000342 return;
343
Chris Lattnera13b8602010-08-24 23:10:06 +0000344 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
345 if (PartVT == ValueVT) {
346 assert(NumParts == 1 && "No-op copy with multiple parts!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000347 Parts[0] = Val;
348 return;
349 }
350
Chris Lattnera13b8602010-08-24 23:10:06 +0000351 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
352 // If the parts cover more bits than the value has, promote the value.
353 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
354 assert(NumParts == 1 && "Do not know what to promote to!");
355 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
356 } else {
Bill Wendling9e8ceb02012-02-23 23:25:25 +0000357 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
358 ValueVT.isInteger() &&
Michael J. Spencere70c5262010-10-16 08:25:21 +0000359 "Unknown mismatch!");
Chris Lattnera13b8602010-08-24 23:10:06 +0000360 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
361 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
Bill Wendling9e8ceb02012-02-23 23:25:25 +0000362 if (PartVT == MVT::x86mmx)
363 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattnera13b8602010-08-24 23:10:06 +0000364 }
365 } else if (PartBits == ValueVT.getSizeInBits()) {
366 // Different types of the same size.
367 assert(NumParts == 1 && PartVT != ValueVT);
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000368 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattnera13b8602010-08-24 23:10:06 +0000369 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
370 // If the parts cover less bits than value has, truncate the value.
Bill Wendling9e8ceb02012-02-23 23:25:25 +0000371 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
372 ValueVT.isInteger() &&
Chris Lattnera13b8602010-08-24 23:10:06 +0000373 "Unknown mismatch!");
374 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
375 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
Bill Wendling9e8ceb02012-02-23 23:25:25 +0000376 if (PartVT == MVT::x86mmx)
377 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattnera13b8602010-08-24 23:10:06 +0000378 }
379
380 // The value may have changed - recompute ValueVT.
381 ValueVT = Val.getValueType();
382 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
383 "Failed to tile the value with PartVT!");
384
385 if (NumParts == 1) {
386 assert(PartVT == ValueVT && "Type conversion failed!");
387 Parts[0] = Val;
388 return;
389 }
390
391 // Expand the value into multiple parts.
392 if (NumParts & (NumParts - 1)) {
393 // The number of parts is not a power of 2. Split off and copy the tail.
394 assert(PartVT.isInteger() && ValueVT.isInteger() &&
395 "Do not know what to expand to!");
396 unsigned RoundParts = 1 << Log2_32(NumParts);
397 unsigned RoundBits = RoundParts * PartBits;
398 unsigned OddParts = NumParts - RoundParts;
399 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
400 DAG.getIntPtrConstant(RoundBits));
401 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT);
402
403 if (TLI.isBigEndian())
404 // The odd parts were reversed by getCopyToParts - unreverse them.
405 std::reverse(Parts + RoundParts, Parts + NumParts);
406
407 NumParts = RoundParts;
408 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
409 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
410 }
411
412 // The number of parts is a power of 2. Repeatedly bisect the value using
413 // EXTRACT_ELEMENT.
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000414 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
Chris Lattnera13b8602010-08-24 23:10:06 +0000415 EVT::getIntegerVT(*DAG.getContext(),
416 ValueVT.getSizeInBits()),
417 Val);
418
419 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
420 for (unsigned i = 0; i < NumParts; i += StepSize) {
421 unsigned ThisBits = StepSize * PartBits / 2;
422 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
423 SDValue &Part0 = Parts[i];
424 SDValue &Part1 = Parts[i+StepSize/2];
425
426 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
427 ThisVT, Part0, DAG.getIntPtrConstant(1));
428 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
429 ThisVT, Part0, DAG.getIntPtrConstant(0));
430
431 if (ThisBits == PartBits && ThisVT != PartVT) {
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000432 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
433 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
Chris Lattnera13b8602010-08-24 23:10:06 +0000434 }
435 }
436 }
437
438 if (TLI.isBigEndian())
439 std::reverse(Parts, Parts + OrigNumParts);
440}
441
442
443/// getCopyToPartsVector - Create a series of nodes that contain the specified
444/// value split into legal parts.
445static void getCopyToPartsVector(SelectionDAG &DAG, DebugLoc DL,
446 SDValue Val, SDValue *Parts, unsigned NumParts,
447 EVT PartVT) {
448 EVT ValueVT = Val.getValueType();
449 assert(ValueVT.isVector() && "Not a vector");
450 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Michael J. Spencere70c5262010-10-16 08:25:21 +0000451
Chris Lattnera13b8602010-08-24 23:10:06 +0000452 if (NumParts == 1) {
Chris Lattnere6f7c262010-08-25 22:49:25 +0000453 if (PartVT == ValueVT) {
454 // Nothing to do.
455 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
456 // Bitconvert vector->vector case.
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000457 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattnere6f7c262010-08-25 22:49:25 +0000458 } else if (PartVT.isVector() &&
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000459 PartVT.getVectorElementType() == ValueVT.getVectorElementType() &&
Chris Lattnere6f7c262010-08-25 22:49:25 +0000460 PartVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
461 EVT ElementVT = PartVT.getVectorElementType();
462 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
463 // undef elements.
464 SmallVector<SDValue, 16> Ops;
465 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
466 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
467 ElementVT, Val, DAG.getIntPtrConstant(i)));
Michael J. Spencere70c5262010-10-16 08:25:21 +0000468
Chris Lattnere6f7c262010-08-25 22:49:25 +0000469 for (unsigned i = ValueVT.getVectorNumElements(),
470 e = PartVT.getVectorNumElements(); i != e; ++i)
471 Ops.push_back(DAG.getUNDEF(ElementVT));
472
473 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, &Ops[0], Ops.size());
474
475 // FIXME: Use CONCAT for 2x -> 4x.
Michael J. Spencere70c5262010-10-16 08:25:21 +0000476
Chris Lattnere6f7c262010-08-25 22:49:25 +0000477 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
478 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
Nadav Rotem0b666362011-06-04 20:58:08 +0000479 } else if (PartVT.isVector() &&
480 PartVT.getVectorElementType().bitsGE(
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000481 ValueVT.getVectorElementType()) &&
Nadav Rotem0b666362011-06-04 20:58:08 +0000482 PartVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
483
484 // Promoted vector extract
Nadav Rotemc6341e62011-06-19 08:49:38 +0000485 bool Smaller = PartVT.bitsLE(ValueVT);
486 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
487 DL, PartVT, Val);
Nadav Rotem0b666362011-06-04 20:58:08 +0000488 } else{
Chris Lattnere6f7c262010-08-25 22:49:25 +0000489 // Vector -> scalar conversion.
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000490 assert(ValueVT.getVectorNumElements() == 1 &&
Chris Lattnere6f7c262010-08-25 22:49:25 +0000491 "Only trivial vector-to-scalar conversions should get here!");
492 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
493 PartVT, Val, DAG.getIntPtrConstant(0));
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000494
495 bool Smaller = ValueVT.bitsLE(PartVT);
496 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
497 DL, PartVT, Val);
Chris Lattnera13b8602010-08-24 23:10:06 +0000498 }
Michael J. Spencere70c5262010-10-16 08:25:21 +0000499
Chris Lattnera13b8602010-08-24 23:10:06 +0000500 Parts[0] = Val;
501 return;
502 }
Michael J. Spencere70c5262010-10-16 08:25:21 +0000503
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000504 // Handle a multi-element vector.
Owen Andersone50ed302009-08-10 22:56:29 +0000505 EVT IntermediateVT, RegisterVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000506 unsigned NumIntermediates;
Owen Anderson23b9b192009-08-12 00:36:31 +0000507 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
Devang Patel8f09bea2010-08-26 20:32:32 +0000508 IntermediateVT,
509 NumIntermediates, RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000510 unsigned NumElements = ValueVT.getVectorNumElements();
Michael J. Spencere70c5262010-10-16 08:25:21 +0000511
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000512 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
513 NumParts = NumRegs; // Silence a compiler warning.
514 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
Michael J. Spencere70c5262010-10-16 08:25:21 +0000515
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000516 // Split the vector into intermediate operands.
517 SmallVector<SDValue, 8> Ops(NumIntermediates);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000518 for (unsigned i = 0; i != NumIntermediates; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000519 if (IntermediateVT.isVector())
Chris Lattnera13b8602010-08-24 23:10:06 +0000520 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000521 IntermediateVT, Val,
Chris Lattnera13b8602010-08-24 23:10:06 +0000522 DAG.getIntPtrConstant(i * (NumElements / NumIntermediates)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000523 else
Chris Lattnera13b8602010-08-24 23:10:06 +0000524 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
Chris Lattnere6f7c262010-08-25 22:49:25 +0000525 IntermediateVT, Val, DAG.getIntPtrConstant(i));
Bill Wendling3ea3c242009-12-22 02:10:19 +0000526 }
Michael J. Spencere70c5262010-10-16 08:25:21 +0000527
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000528 // Split the intermediate operands into legal parts.
529 if (NumParts == NumIntermediates) {
530 // If the register was not expanded, promote or copy the value,
531 // as appropriate.
532 for (unsigned i = 0; i != NumParts; ++i)
Chris Lattnera13b8602010-08-24 23:10:06 +0000533 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000534 } else if (NumParts > 0) {
535 // If the intermediate type was expanded, split each the value into
536 // legal parts.
537 assert(NumParts % NumIntermediates == 0 &&
538 "Must expand into a divisible number of parts!");
539 unsigned Factor = NumParts / NumIntermediates;
540 for (unsigned i = 0; i != NumIntermediates; ++i)
Chris Lattnera13b8602010-08-24 23:10:06 +0000541 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000542 }
543}
544
Chris Lattnera13b8602010-08-24 23:10:06 +0000545
546
547
Dan Gohman462f6b52010-05-29 17:53:24 +0000548namespace {
549 /// RegsForValue - This struct represents the registers (physical or virtual)
550 /// that a particular set of values is assigned, and the type information
551 /// about the value. The most common situation is to represent one value at a
552 /// time, but struct or array values are handled element-wise as multiple
553 /// values. The splitting of aggregates is performed recursively, so that we
554 /// never have aggregate-typed registers. The values at this point do not
555 /// necessarily have legal types, so each value may require one or more
556 /// registers of some legal type.
557 ///
558 struct RegsForValue {
559 /// ValueVTs - The value types of the values, which may not be legal, and
560 /// may need be promoted or synthesized from one or more registers.
561 ///
562 SmallVector<EVT, 4> ValueVTs;
563
564 /// RegVTs - The value types of the registers. This is the same size as
565 /// ValueVTs and it records, for each value, what the type of the assigned
566 /// register or registers are. (Individual values are never synthesized
567 /// from more than one type of register.)
568 ///
569 /// With virtual registers, the contents of RegVTs is redundant with TLI's
570 /// getRegisterType member function, however when with physical registers
571 /// it is necessary to have a separate record of the types.
572 ///
573 SmallVector<EVT, 4> RegVTs;
574
575 /// Regs - This list holds the registers assigned to the values.
576 /// Each legal or promoted value requires one register, and each
577 /// expanded value requires multiple registers.
578 ///
579 SmallVector<unsigned, 4> Regs;
580
581 RegsForValue() {}
582
583 RegsForValue(const SmallVector<unsigned, 4> &regs,
584 EVT regvt, EVT valuevt)
585 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
586
Dan Gohman462f6b52010-05-29 17:53:24 +0000587 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000588 unsigned Reg, Type *Ty) {
Dan Gohman462f6b52010-05-29 17:53:24 +0000589 ComputeValueVTs(tli, Ty, ValueVTs);
590
591 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
592 EVT ValueVT = ValueVTs[Value];
593 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
594 EVT RegisterVT = tli.getRegisterType(Context, ValueVT);
595 for (unsigned i = 0; i != NumRegs; ++i)
596 Regs.push_back(Reg + i);
597 RegVTs.push_back(RegisterVT);
598 Reg += NumRegs;
599 }
600 }
601
602 /// areValueTypesLegal - Return true if types of all the values are legal.
603 bool areValueTypesLegal(const TargetLowering &TLI) {
604 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
605 EVT RegisterVT = RegVTs[Value];
606 if (!TLI.isTypeLegal(RegisterVT))
607 return false;
608 }
609 return true;
610 }
611
612 /// append - Add the specified values to this one.
613 void append(const RegsForValue &RHS) {
614 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
615 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
616 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
617 }
618
619 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
620 /// this value and returns the result as a ValueVTs value. This uses
621 /// Chain/Flag as the input and updates them for the output Chain/Flag.
622 /// If the Flag pointer is NULL, no flag is used.
623 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
624 DebugLoc dl,
625 SDValue &Chain, SDValue *Flag) const;
626
627 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
628 /// specified value into the registers specified by this object. This uses
629 /// Chain/Flag as the input and updates them for the output Chain/Flag.
630 /// If the Flag pointer is NULL, no flag is used.
631 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
632 SDValue &Chain, SDValue *Flag) const;
633
634 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
635 /// operand list. This adds the code marker, matching input operand index
636 /// (if applicable), and includes the number of values added into it.
637 void AddInlineAsmOperands(unsigned Kind,
638 bool HasMatching, unsigned MatchingIdx,
639 SelectionDAG &DAG,
640 std::vector<SDValue> &Ops) const;
641 };
642}
643
644/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
645/// this value and returns the result as a ValueVT value. This uses
646/// Chain/Flag as the input and updates them for the output Chain/Flag.
647/// If the Flag pointer is NULL, no flag is used.
648SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
649 FunctionLoweringInfo &FuncInfo,
650 DebugLoc dl,
651 SDValue &Chain, SDValue *Flag) const {
Dan Gohman7da5d3f2010-07-26 18:15:41 +0000652 // A Value with type {} or [0 x %t] needs no registers.
653 if (ValueVTs.empty())
654 return SDValue();
655
Dan Gohman462f6b52010-05-29 17:53:24 +0000656 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
657
658 // Assemble the legal parts into the final values.
659 SmallVector<SDValue, 4> Values(ValueVTs.size());
660 SmallVector<SDValue, 8> Parts;
661 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
662 // Copy the legal parts from the registers.
663 EVT ValueVT = ValueVTs[Value];
664 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
665 EVT RegisterVT = RegVTs[Value];
666
667 Parts.resize(NumRegs);
668 for (unsigned i = 0; i != NumRegs; ++i) {
669 SDValue P;
670 if (Flag == 0) {
671 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
672 } else {
673 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
674 *Flag = P.getValue(2);
675 }
676
677 Chain = P.getValue(1);
Chris Lattnerd5b4db92010-12-13 01:11:17 +0000678 Parts[i] = P;
Dan Gohman462f6b52010-05-29 17:53:24 +0000679
680 // If the source register was virtual and if we know something about it,
681 // add an assert node.
Chris Lattnerd5b4db92010-12-13 01:11:17 +0000682 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
Cameron Zwariche1497b92011-02-24 10:00:08 +0000683 !RegisterVT.isInteger() || RegisterVT.isVector())
Chris Lattnerd5b4db92010-12-13 01:11:17 +0000684 continue;
Cameron Zwariche1497b92011-02-24 10:00:08 +0000685
686 const FunctionLoweringInfo::LiveOutInfo *LOI =
687 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
688 if (!LOI)
689 continue;
Dan Gohman462f6b52010-05-29 17:53:24 +0000690
Chris Lattnerd5b4db92010-12-13 01:11:17 +0000691 unsigned RegSize = RegisterVT.getSizeInBits();
Cameron Zwariche1497b92011-02-24 10:00:08 +0000692 unsigned NumSignBits = LOI->NumSignBits;
693 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
Dan Gohman462f6b52010-05-29 17:53:24 +0000694
Chris Lattnerd5b4db92010-12-13 01:11:17 +0000695 // FIXME: We capture more information than the dag can represent. For
696 // now, just use the tightest assertzext/assertsext possible.
697 bool isSExt = true;
698 EVT FromVT(MVT::Other);
699 if (NumSignBits == RegSize)
700 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
701 else if (NumZeroBits >= RegSize-1)
702 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
703 else if (NumSignBits > RegSize-8)
704 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
705 else if (NumZeroBits >= RegSize-8)
706 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
707 else if (NumSignBits > RegSize-16)
708 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
709 else if (NumZeroBits >= RegSize-16)
710 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
711 else if (NumSignBits > RegSize-32)
712 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
713 else if (NumZeroBits >= RegSize-32)
714 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
715 else
716 continue;
Dan Gohman462f6b52010-05-29 17:53:24 +0000717
Chris Lattnerd5b4db92010-12-13 01:11:17 +0000718 // Add an assertion node.
719 assert(FromVT != MVT::Other);
720 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
721 RegisterVT, P, DAG.getValueType(FromVT));
Dan Gohman462f6b52010-05-29 17:53:24 +0000722 }
723
724 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
725 NumRegs, RegisterVT, ValueVT);
726 Part += NumRegs;
727 Parts.clear();
728 }
729
730 return DAG.getNode(ISD::MERGE_VALUES, dl,
731 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
732 &Values[0], ValueVTs.size());
733}
734
735/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
736/// specified value into the registers specified by this object. This uses
737/// Chain/Flag as the input and updates them for the output Chain/Flag.
738/// If the Flag pointer is NULL, no flag is used.
739void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
740 SDValue &Chain, SDValue *Flag) const {
741 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
742
743 // Get the list of the values's legal parts.
744 unsigned NumRegs = Regs.size();
745 SmallVector<SDValue, 8> Parts(NumRegs);
746 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
747 EVT ValueVT = ValueVTs[Value];
748 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
749 EVT RegisterVT = RegVTs[Value];
750
Chris Lattner3ac18842010-08-24 23:20:40 +0000751 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
Dan Gohman462f6b52010-05-29 17:53:24 +0000752 &Parts[Part], NumParts, RegisterVT);
753 Part += NumParts;
754 }
755
756 // Copy the parts into the registers.
757 SmallVector<SDValue, 8> Chains(NumRegs);
758 for (unsigned i = 0; i != NumRegs; ++i) {
759 SDValue Part;
760 if (Flag == 0) {
761 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
762 } else {
763 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
764 *Flag = Part.getValue(1);
765 }
766
767 Chains[i] = Part.getValue(0);
768 }
769
770 if (NumRegs == 1 || Flag)
771 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
772 // flagged to it. That is the CopyToReg nodes and the user are considered
773 // a single scheduling unit. If we create a TokenFactor and return it as
774 // chain, then the TokenFactor is both a predecessor (operand) of the
775 // user as well as a successor (the TF operands are flagged to the user).
776 // c1, f1 = CopyToReg
777 // c2, f2 = CopyToReg
778 // c3 = TokenFactor c1, c2
779 // ...
780 // = op c3, ..., f2
781 Chain = Chains[NumRegs-1];
782 else
783 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
784}
785
786/// AddInlineAsmOperands - Add this value to the specified inlineasm node
787/// operand list. This adds the code marker and includes the number of
788/// values added into it.
789void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
790 unsigned MatchingIdx,
791 SelectionDAG &DAG,
792 std::vector<SDValue> &Ops) const {
793 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
794
795 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
796 if (HasMatching)
797 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
Jakob Stoklund Olesen459b74b2011-10-12 23:37:29 +0000798 else if (!Regs.empty() &&
799 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
800 // Put the register class of the virtual registers in the flag word. That
801 // way, later passes can recompute register class constraints for inline
802 // assembly as well as normal instructions.
803 // Don't do this for tied operands that can use the regclass information
804 // from the def.
805 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
806 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
807 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
808 }
809
Dan Gohman462f6b52010-05-29 17:53:24 +0000810 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
811 Ops.push_back(Res);
812
813 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
814 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
815 EVT RegisterVT = RegVTs[Value];
816 for (unsigned i = 0; i != NumRegs; ++i) {
817 assert(Reg < Regs.size() && "Mismatch in # registers expected");
818 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
819 }
820 }
821}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000822
Owen Anderson243eb9e2011-12-08 22:15:21 +0000823void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
824 const TargetLibraryInfo *li) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000825 AA = &aa;
826 GFI = gfi;
Owen Anderson243eb9e2011-12-08 22:15:21 +0000827 LibInfo = li;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000828 TD = DAG.getTarget().getTargetData();
Richard Smithcb1f68d2012-08-22 00:42:39 +0000829 Context = DAG.getContext();
Bill Wendling4ed1fb02011-10-15 01:00:26 +0000830 LPadToCallSiteMap.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000831}
832
Dan Gohmanb02b62a2010-04-14 18:24:06 +0000833/// clear - Clear out the current SelectionDAG and the associated
Dan Gohman2048b852009-11-23 18:04:58 +0000834/// state and prepare this SelectionDAGBuilder object to be used
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000835/// for a new block. This doesn't clear out information about
836/// additional blocks that are needed to complete switch lowering
837/// or PHI node updating; that information is cleared out as it is
838/// consumed.
Dan Gohman2048b852009-11-23 18:04:58 +0000839void SelectionDAGBuilder::clear() {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000840 NodeMap.clear();
Devang Patel9126c0d2010-06-01 19:59:01 +0000841 UnusedArgNodeMap.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000842 PendingLoads.clear();
843 PendingExports.clear();
Chris Lattnera4f2bb02010-04-02 20:17:23 +0000844 CurDebugLoc = DebugLoc();
Dan Gohman98ca4f22009-08-05 01:29:28 +0000845 HasTailCall = false;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000846}
847
Devang Patel23385752011-05-23 17:44:13 +0000848/// clearDanglingDebugInfo - Clear the dangling debug information
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000849/// map. This function is separated from the clear so that debug
Devang Patel23385752011-05-23 17:44:13 +0000850/// information that is dangling in a basic block can be properly
851/// resolved in a different basic block. This allows the
852/// SelectionDAG to resolve dangling debug information attached
853/// to PHI nodes.
854void SelectionDAGBuilder::clearDanglingDebugInfo() {
855 DanglingDebugInfoMap.clear();
856}
857
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000858/// getRoot - Return the current virtual root of the Selection DAG,
859/// flushing any PendingLoad items. This must be done before emitting
860/// a store or any other node that may need to be ordered after any
861/// prior load instructions.
862///
Dan Gohman2048b852009-11-23 18:04:58 +0000863SDValue SelectionDAGBuilder::getRoot() {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000864 if (PendingLoads.empty())
865 return DAG.getRoot();
866
867 if (PendingLoads.size() == 1) {
868 SDValue Root = PendingLoads[0];
869 DAG.setRoot(Root);
870 PendingLoads.clear();
871 return Root;
872 }
873
874 // Otherwise, we have to make a token factor node.
Owen Anderson825b72b2009-08-11 20:47:22 +0000875 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000876 &PendingLoads[0], PendingLoads.size());
877 PendingLoads.clear();
878 DAG.setRoot(Root);
879 return Root;
880}
881
882/// getControlRoot - Similar to getRoot, but instead of flushing all the
883/// PendingLoad items, flush all the PendingExports items. It is necessary
884/// to do this before emitting a terminator instruction.
885///
Dan Gohman2048b852009-11-23 18:04:58 +0000886SDValue SelectionDAGBuilder::getControlRoot() {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000887 SDValue Root = DAG.getRoot();
888
889 if (PendingExports.empty())
890 return Root;
891
892 // Turn all of the CopyToReg chains into one factored node.
893 if (Root.getOpcode() != ISD::EntryToken) {
894 unsigned i = 0, e = PendingExports.size();
895 for (; i != e; ++i) {
896 assert(PendingExports[i].getNode()->getNumOperands() > 1);
897 if (PendingExports[i].getNode()->getOperand(0) == Root)
898 break; // Don't add the root if we already indirectly depend on it.
899 }
900
901 if (i == e)
902 PendingExports.push_back(Root);
903 }
904
Owen Anderson825b72b2009-08-11 20:47:22 +0000905 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000906 &PendingExports[0],
907 PendingExports.size());
908 PendingExports.clear();
909 DAG.setRoot(Root);
910 return Root;
911}
912
Bill Wendling4533cac2010-01-28 21:51:40 +0000913void SelectionDAGBuilder::AssignOrderingToNode(const SDNode *Node) {
914 if (DAG.GetOrdering(Node) != 0) return; // Already has ordering.
915 DAG.AssignOrdering(Node, SDNodeOrder);
916
917 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
918 AssignOrderingToNode(Node->getOperand(I).getNode());
919}
920
Dan Gohman46510a72010-04-15 01:51:59 +0000921void SelectionDAGBuilder::visit(const Instruction &I) {
Dan Gohmanc105a2b2010-04-22 20:55:53 +0000922 // Set up outgoing PHI node register values before emitting the terminator.
923 if (isa<TerminatorInst>(&I))
924 HandlePHINodesInSuccessorBlocks(I.getParent());
925
Dan Gohman8ba3aa72010-04-20 00:48:35 +0000926 CurDebugLoc = I.getDebugLoc();
927
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000928 visit(I.getOpcode(), I);
Dan Gohman8ba3aa72010-04-20 00:48:35 +0000929
Dan Gohman92884f72010-04-20 15:03:56 +0000930 if (!isa<TerminatorInst>(&I) && !HasTailCall)
931 CopyToExportRegsIfNeeded(&I);
932
Dan Gohman8ba3aa72010-04-20 00:48:35 +0000933 CurDebugLoc = DebugLoc();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000934}
935
Dan Gohmanba5be5c2010-04-20 15:00:41 +0000936void SelectionDAGBuilder::visitPHI(const PHINode &) {
937 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
938}
939
Dan Gohman46510a72010-04-15 01:51:59 +0000940void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000941 // Note: this doesn't use InstVisitor, because it has to work with
942 // ConstantExpr's in addition to instructions.
943 switch (Opcode) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000944 default: llvm_unreachable("Unknown instruction type encountered!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000945 // Build the switch statement using the Instruction.def file.
946#define HANDLE_INST(NUM, OPCODE, CLASS) \
Galina Kistanova72ea0c92012-07-19 04:50:12 +0000947 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000948#include "llvm/Instruction.def"
949 }
Bill Wendling4533cac2010-01-28 21:51:40 +0000950
951 // Assign the ordering to the freshly created DAG nodes.
952 if (NodeMap.count(&I)) {
953 ++SDNodeOrder;
954 AssignOrderingToNode(getValue(&I).getNode());
955 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000956}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000957
Dale Johannesenbdc09d92010-07-16 00:02:08 +0000958// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
959// generate the debug data structures now that we've seen its definition.
960void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
961 SDValue Val) {
962 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
Devang Patel4cf81c42010-08-26 23:35:15 +0000963 if (DDI.getDI()) {
964 const DbgValueInst *DI = DDI.getDI();
Dale Johannesenbdc09d92010-07-16 00:02:08 +0000965 DebugLoc dl = DDI.getdl();
966 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
Devang Patel4cf81c42010-08-26 23:35:15 +0000967 MDNode *Variable = DI->getVariable();
968 uint64_t Offset = DI->getOffset();
Dale Johannesenbdc09d92010-07-16 00:02:08 +0000969 SDDbgValue *SDV;
970 if (Val.getNode()) {
Devang Patel78a06e52010-08-25 20:39:26 +0000971 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, Val)) {
Dale Johannesenbdc09d92010-07-16 00:02:08 +0000972 SDV = DAG.getDbgValue(Variable, Val.getNode(),
973 Val.getResNo(), Offset, dl, DbgSDNodeOrder);
974 DAG.AddDbgValue(SDV, Val.getNode(), false);
975 }
Owen Anderson95771af2011-02-25 21:41:48 +0000976 } else
Eric Christopher0822e012012-02-23 03:39:43 +0000977 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Dale Johannesenbdc09d92010-07-16 00:02:08 +0000978 DanglingDebugInfoMap[V] = DanglingDebugInfo();
979 }
980}
981
Nick Lewycky8de34002011-09-30 22:19:53 +0000982/// getValue - Return an SDValue for the given Value.
Dan Gohman2048b852009-11-23 18:04:58 +0000983SDValue SelectionDAGBuilder::getValue(const Value *V) {
Dan Gohman28a17352010-07-01 01:59:43 +0000984 // If we already have an SDValue for this value, use it. It's important
985 // to do this first, so that we don't create a CopyFromReg if we already
986 // have a regular SDValue.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000987 SDValue &N = NodeMap[V];
988 if (N.getNode()) return N;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000989
Dan Gohman28a17352010-07-01 01:59:43 +0000990 // If there's a virtual register allocated and initialized for this
991 // value, use it.
992 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
993 if (It != FuncInfo.ValueMap.end()) {
994 unsigned InReg = It->second;
995 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
996 SDValue Chain = DAG.getEntryNode();
Nick Lewycky8de34002011-09-30 22:19:53 +0000997 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain, NULL);
Devang Patel8f314282011-01-25 18:09:58 +0000998 resolveDanglingDebugInfo(V, N);
999 return N;
Dan Gohman28a17352010-07-01 01:59:43 +00001000 }
1001
1002 // Otherwise create a new SDValue and remember it.
1003 SDValue Val = getValueImpl(V);
1004 NodeMap[V] = Val;
Dale Johannesenbdc09d92010-07-16 00:02:08 +00001005 resolveDanglingDebugInfo(V, Val);
Dan Gohman28a17352010-07-01 01:59:43 +00001006 return Val;
1007}
1008
1009/// getNonRegisterValue - Return an SDValue for the given Value, but
1010/// don't look in FuncInfo.ValueMap for a virtual register.
1011SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1012 // If we already have an SDValue for this value, use it.
1013 SDValue &N = NodeMap[V];
1014 if (N.getNode()) return N;
1015
1016 // Otherwise create a new SDValue and remember it.
1017 SDValue Val = getValueImpl(V);
1018 NodeMap[V] = Val;
Dale Johannesenbdc09d92010-07-16 00:02:08 +00001019 resolveDanglingDebugInfo(V, Val);
Dan Gohman28a17352010-07-01 01:59:43 +00001020 return Val;
1021}
1022
Dale Johannesenbdc09d92010-07-16 00:02:08 +00001023/// getValueImpl - Helper function for getValue and getNonRegisterValue.
Dan Gohman28a17352010-07-01 01:59:43 +00001024/// Create an SDValue for the given value.
1025SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
Dan Gohman383b5f62010-04-17 15:32:28 +00001026 if (const Constant *C = dyn_cast<Constant>(V)) {
Owen Andersone50ed302009-08-10 22:56:29 +00001027 EVT VT = TLI.getValueType(V->getType(), true);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001028
Dan Gohman383b5f62010-04-17 15:32:28 +00001029 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman28a17352010-07-01 01:59:43 +00001030 return DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001031
Dan Gohman383b5f62010-04-17 15:32:28 +00001032 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
Devang Patel0d881da2010-07-06 22:08:15 +00001033 return DAG.getGlobalAddress(GV, getCurDebugLoc(), VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001034
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001035 if (isa<ConstantPointerNull>(C))
Dan Gohman28a17352010-07-01 01:59:43 +00001036 return DAG.getConstant(0, TLI.getPointerTy());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001037
Dan Gohman383b5f62010-04-17 15:32:28 +00001038 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman28a17352010-07-01 01:59:43 +00001039 return DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001040
Nate Begeman9008ca62009-04-27 18:41:29 +00001041 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
Dan Gohman28a17352010-07-01 01:59:43 +00001042 return DAG.getUNDEF(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001043
Dan Gohman383b5f62010-04-17 15:32:28 +00001044 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001045 visit(CE->getOpcode(), *CE);
1046 SDValue N1 = NodeMap[V];
Dan Gohmanac7d05c2010-04-16 16:55:18 +00001047 assert(N1.getNode() && "visit didn't populate the NodeMap!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001048 return N1;
1049 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001050
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001051 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1052 SmallVector<SDValue, 4> Constants;
1053 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1054 OI != OE; ++OI) {
1055 SDNode *Val = getValue(*OI).getNode();
Dan Gohmaned48caf2009-09-08 01:44:02 +00001056 // If the operand is an empty aggregate, there are no values.
1057 if (!Val) continue;
1058 // Add each leaf value from the operand to the Constants list
1059 // to form a flattened list of all the values.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001060 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1061 Constants.push_back(SDValue(Val, i));
1062 }
Bill Wendling87710f02009-12-21 23:47:40 +00001063
Bill Wendling4533cac2010-01-28 21:51:40 +00001064 return DAG.getMergeValues(&Constants[0], Constants.size(),
1065 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001066 }
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001067
1068 if (const ConstantDataSequential *CDS =
1069 dyn_cast<ConstantDataSequential>(C)) {
1070 SmallVector<SDValue, 4> Ops;
Chris Lattner0f193b82012-01-25 01:27:20 +00001071 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001072 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1073 // Add each leaf value from the operand to the Constants list
1074 // to form a flattened list of all the values.
1075 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1076 Ops.push_back(SDValue(Val, i));
1077 }
1078
1079 if (isa<ArrayType>(CDS->getType()))
1080 return DAG.getMergeValues(&Ops[0], Ops.size(), getCurDebugLoc());
1081 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
1082 VT, &Ops[0], Ops.size());
1083 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001084
Duncan Sands1df98592010-02-16 11:11:14 +00001085 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001086 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1087 "Unknown struct or array constant!");
1088
Owen Andersone50ed302009-08-10 22:56:29 +00001089 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001090 ComputeValueVTs(TLI, C->getType(), ValueVTs);
1091 unsigned NumElts = ValueVTs.size();
1092 if (NumElts == 0)
1093 return SDValue(); // empty struct
1094 SmallVector<SDValue, 4> Constants(NumElts);
1095 for (unsigned i = 0; i != NumElts; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +00001096 EVT EltVT = ValueVTs[i];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001097 if (isa<UndefValue>(C))
Dale Johannesene8d72302009-02-06 23:05:02 +00001098 Constants[i] = DAG.getUNDEF(EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001099 else if (EltVT.isFloatingPoint())
1100 Constants[i] = DAG.getConstantFP(0, EltVT);
1101 else
1102 Constants[i] = DAG.getConstant(0, EltVT);
1103 }
Bill Wendling87710f02009-12-21 23:47:40 +00001104
Bill Wendling4533cac2010-01-28 21:51:40 +00001105 return DAG.getMergeValues(&Constants[0], NumElts,
1106 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001107 }
1108
Dan Gohman383b5f62010-04-17 15:32:28 +00001109 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
Dan Gohman29cbade2009-11-20 23:18:13 +00001110 return DAG.getBlockAddress(BA, VT);
Dan Gohman8c2b5252009-10-30 01:27:03 +00001111
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001112 VectorType *VecTy = cast<VectorType>(V->getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001113 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001114
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001115 // Now that we know the number and type of the elements, get that number of
1116 // elements into the Ops array based on what kind of constant it is.
1117 SmallVector<SDValue, 16> Ops;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001118 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001119 for (unsigned i = 0; i != NumElements; ++i)
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001120 Ops.push_back(getValue(CV->getOperand(i)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001121 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +00001122 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Owen Andersone50ed302009-08-10 22:56:29 +00001123 EVT EltVT = TLI.getValueType(VecTy->getElementType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001124
1125 SDValue Op;
Nate Begeman9008ca62009-04-27 18:41:29 +00001126 if (EltVT.isFloatingPoint())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001127 Op = DAG.getConstantFP(0, EltVT);
1128 else
1129 Op = DAG.getConstant(0, EltVT);
1130 Ops.assign(NumElements, Op);
1131 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001132
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001133 // Create a BUILD_VECTOR node.
Bill Wendling4533cac2010-01-28 21:51:40 +00001134 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
1135 VT, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001136 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001137
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001138 // If this is a static alloca, generate it as the frameindex instead of
1139 // computation.
1140 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1141 DenseMap<const AllocaInst*, int>::iterator SI =
1142 FuncInfo.StaticAllocaMap.find(AI);
1143 if (SI != FuncInfo.StaticAllocaMap.end())
1144 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1145 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001146
Dan Gohman28a17352010-07-01 01:59:43 +00001147 // If this is an instruction which fast-isel has deferred, select it now.
1148 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
Dan Gohman84023e02010-07-10 09:00:22 +00001149 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1150 RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
1151 SDValue Chain = DAG.getEntryNode();
1152 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain, NULL);
Dan Gohman28a17352010-07-01 01:59:43 +00001153 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001154
Dan Gohman28a17352010-07-01 01:59:43 +00001155 llvm_unreachable("Can't get register for value!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001156}
1157
Dan Gohman46510a72010-04-15 01:51:59 +00001158void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
Dan Gohman98ca4f22009-08-05 01:29:28 +00001159 SDValue Chain = getControlRoot();
1160 SmallVector<ISD::OutputArg, 8> Outs;
Dan Gohmanc9403652010-07-07 15:54:55 +00001161 SmallVector<SDValue, 8> OutVals;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00001162
Dan Gohman7451d3e2010-05-29 17:03:36 +00001163 if (!FuncInfo.CanLowerReturn) {
1164 unsigned DemoteReg = FuncInfo.DemoteRegister;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001165 const Function *F = I.getParent()->getParent();
1166
1167 // Emit a store of the return value through the virtual register.
1168 // Leave Outs empty so that LowerReturn won't try to load return
1169 // registers the usual way.
1170 SmallVector<EVT, 1> PtrValueVTs;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00001171 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001172 PtrValueVTs);
1173
1174 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1175 SDValue RetOp = getValue(I.getOperand(0));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00001176
Owen Andersone50ed302009-08-10 22:56:29 +00001177 SmallVector<EVT, 4> ValueVTs;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001178 SmallVector<uint64_t, 4> Offsets;
1179 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
Dan Gohman7ea1ca62008-10-21 20:00:42 +00001180 unsigned NumValues = ValueVTs.size();
Dan Gohman7ea1ca62008-10-21 20:00:42 +00001181
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001182 SmallVector<SDValue, 4> Chains(NumValues);
Bill Wendling87710f02009-12-21 23:47:40 +00001183 for (unsigned i = 0; i != NumValues; ++i) {
Chris Lattnera13b8602010-08-24 23:10:06 +00001184 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(),
1185 RetPtr.getValueType(), RetPtr,
1186 DAG.getIntPtrConstant(Offsets[i]));
Bill Wendling87710f02009-12-21 23:47:40 +00001187 Chains[i] =
1188 DAG.getStore(Chain, getCurDebugLoc(),
1189 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
Chris Lattner84bd98a2010-09-21 18:58:22 +00001190 // FIXME: better loc info would be nice.
1191 Add, MachinePointerInfo(), false, false, 0);
Bill Wendling87710f02009-12-21 23:47:40 +00001192 }
1193
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001194 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
1195 MVT::Other, &Chains[0], NumValues);
Chris Lattner25d58372010-02-28 18:53:13 +00001196 } else if (I.getNumOperands() != 0) {
1197 SmallVector<EVT, 4> ValueVTs;
1198 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
1199 unsigned NumValues = ValueVTs.size();
1200 if (NumValues) {
1201 SDValue RetOp = getValue(I.getOperand(0));
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001202 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1203 EVT VT = ValueVTs[j];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001204
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001205 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001206
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001207 const Function *F = I.getParent()->getParent();
1208 if (F->paramHasAttr(0, Attribute::SExt))
1209 ExtendKind = ISD::SIGN_EXTEND;
1210 else if (F->paramHasAttr(0, Attribute::ZExt))
1211 ExtendKind = ISD::ZERO_EXTEND;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001212
Cameron Zwarich7bbf0ee2011-03-17 14:53:37 +00001213 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1214 VT = TLI.getTypeForExtArgOrReturn(*DAG.getContext(), VT, ExtendKind);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001215
1216 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
1217 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
1218 SmallVector<SDValue, 4> Parts(NumParts);
Bill Wendling46ada192010-03-02 01:55:18 +00001219 getCopyToParts(DAG, getCurDebugLoc(),
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001220 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1221 &Parts[0], NumParts, PartVT, ExtendKind);
1222
1223 // 'inreg' on function refers to return value
1224 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1225 if (F->paramHasAttr(0, Attribute::InReg))
1226 Flags.setInReg();
1227
1228 // Propagate extension type if any
Cameron Zwarich8df6bf52011-03-16 22:20:07 +00001229 if (ExtendKind == ISD::SIGN_EXTEND)
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001230 Flags.setSExt();
Cameron Zwarich8df6bf52011-03-16 22:20:07 +00001231 else if (ExtendKind == ISD::ZERO_EXTEND)
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001232 Flags.setZExt();
1233
Dan Gohmanc9403652010-07-07 15:54:55 +00001234 for (unsigned i = 0; i < NumParts; ++i) {
1235 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1236 /*isfixed=*/true));
1237 OutVals.push_back(Parts[i]);
1238 }
Evan Cheng3927f432009-03-25 20:20:11 +00001239 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001240 }
1241 }
Dan Gohman98ca4f22009-08-05 01:29:28 +00001242
1243 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001244 CallingConv::ID CallConv =
1245 DAG.getMachineFunction().getFunction()->getCallingConv();
Dan Gohman98ca4f22009-08-05 01:29:28 +00001246 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
Dan Gohmanc9403652010-07-07 15:54:55 +00001247 Outs, OutVals, getCurDebugLoc(), DAG);
Dan Gohman5e866062009-08-06 15:37:27 +00001248
1249 // Verify that the target's LowerReturn behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00001250 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00001251 "LowerReturn didn't return a valid chain!");
1252
1253 // Update the DAG with the new chain value resulting from return lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +00001254 DAG.setRoot(Chain);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001255}
1256
Dan Gohmanad62f532009-04-23 23:13:24 +00001257/// CopyToExportRegsIfNeeded - If the given value has virtual registers
1258/// created for it, emit nodes to copy the value into the virtual
1259/// registers.
Dan Gohman46510a72010-04-15 01:51:59 +00001260void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
Rafael Espindola3fa82832011-05-13 15:18:06 +00001261 // Skip empty types
1262 if (V->getType()->isEmptyTy())
1263 return;
1264
Dan Gohman33b7a292010-04-16 17:15:02 +00001265 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1266 if (VMI != FuncInfo.ValueMap.end()) {
1267 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1268 CopyValueToVirtualRegister(V, VMI->second);
Dan Gohmanad62f532009-04-23 23:13:24 +00001269 }
1270}
1271
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001272/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1273/// the current basic block, add it to ValueMap now so that we'll get a
1274/// CopyTo/FromReg.
Dan Gohman46510a72010-04-15 01:51:59 +00001275void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001276 // No need to export constants.
1277 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001278
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001279 // Already exported?
1280 if (FuncInfo.isExportedInst(V)) return;
1281
1282 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1283 CopyValueToVirtualRegister(V, Reg);
1284}
1285
Dan Gohman46510a72010-04-15 01:51:59 +00001286bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
Dan Gohman2048b852009-11-23 18:04:58 +00001287 const BasicBlock *FromBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001288 // The operands of the setcc have to be in this block. We don't know
1289 // how to export them from some other block.
Dan Gohman46510a72010-04-15 01:51:59 +00001290 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001291 // Can export from current BB.
1292 if (VI->getParent() == FromBB)
1293 return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001294
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001295 // Is already exported, noop.
1296 return FuncInfo.isExportedInst(V);
1297 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001298
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001299 // If this is an argument, we can export it if the BB is the entry block or
1300 // if it is already exported.
1301 if (isa<Argument>(V)) {
1302 if (FromBB == &FromBB->getParent()->getEntryBlock())
1303 return true;
1304
1305 // Otherwise, can only export this if it is already exported.
1306 return FuncInfo.isExportedInst(V);
1307 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001308
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001309 // Otherwise, constants can always be exported.
1310 return true;
1311}
1312
Jakub Staszak7cc2b072011-06-16 20:22:37 +00001313/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
Jakub Staszak25101bb2011-12-20 20:03:10 +00001314uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1315 const MachineBasicBlock *Dst) const {
Jakub Staszak7cc2b072011-06-16 20:22:37 +00001316 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1317 if (!BPI)
1318 return 0;
Jakub Staszak95ece8e2011-07-29 20:05:36 +00001319 const BasicBlock *SrcBB = Src->getBasicBlock();
1320 const BasicBlock *DstBB = Dst->getBasicBlock();
Jakub Staszak7cc2b072011-06-16 20:22:37 +00001321 return BPI->getEdgeWeight(SrcBB, DstBB);
1322}
1323
Jakub Staszakc8f34de2011-07-29 22:25:21 +00001324void SelectionDAGBuilder::
1325addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1326 uint32_t Weight /* = 0 */) {
1327 if (!Weight)
1328 Weight = getEdgeWeight(Src, Dst);
1329 Src->addSuccessor(Dst, Weight);
Jakub Staszak7cc2b072011-06-16 20:22:37 +00001330}
1331
1332
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001333static bool InBlock(const Value *V, const BasicBlock *BB) {
1334 if (const Instruction *I = dyn_cast<Instruction>(V))
1335 return I->getParent() == BB;
1336 return true;
1337}
1338
Dan Gohmanc2277342008-10-17 21:16:08 +00001339/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1340/// This function emits a branch and is used at the leaves of an OR or an
1341/// AND operator tree.
1342///
1343void
Dan Gohman46510a72010-04-15 01:51:59 +00001344SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
Dan Gohman2048b852009-11-23 18:04:58 +00001345 MachineBasicBlock *TBB,
1346 MachineBasicBlock *FBB,
Dan Gohman99be8ae2010-04-19 22:41:47 +00001347 MachineBasicBlock *CurBB,
1348 MachineBasicBlock *SwitchBB) {
Dan Gohmanc2277342008-10-17 21:16:08 +00001349 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001350
Dan Gohmanc2277342008-10-17 21:16:08 +00001351 // If the leaf of the tree is a comparison, merge the condition into
1352 // the caseblock.
Dan Gohman46510a72010-04-15 01:51:59 +00001353 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
Dan Gohmanc2277342008-10-17 21:16:08 +00001354 // The operands of the cmp have to be in this block. We don't know
1355 // how to export them from some other block. If this is the first block
1356 // of the sequence, no exporting is needed.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001357 if (CurBB == SwitchBB ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001358 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1359 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001360 ISD::CondCode Condition;
Dan Gohman46510a72010-04-15 01:51:59 +00001361 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001362 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohman46510a72010-04-15 01:51:59 +00001363 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001364 Condition = getFCmpCondCode(FC->getPredicate());
Nick Lewycky8a8d4792011-12-02 22:16:29 +00001365 if (TM.Options.NoNaNsFPMath)
1366 Condition = getFCmpCodeWithoutNaN(Condition);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001367 } else {
1368 Condition = ISD::SETEQ; // silence warning.
Torok Edwinc23197a2009-07-14 16:55:14 +00001369 llvm_unreachable("Unknown compare instruction");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001370 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001371
1372 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001373 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1374 SwitchCases.push_back(CB);
1375 return;
1376 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001377 }
1378
1379 // Create a CaseBlock record representing this branch.
Owen Anderson5defacc2009-07-31 17:39:07 +00001380 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohmanc2277342008-10-17 21:16:08 +00001381 NULL, TBB, FBB, CurBB);
1382 SwitchCases.push_back(CB);
1383}
1384
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001385/// FindMergedConditions - If Cond is an expression like
Dan Gohman46510a72010-04-15 01:51:59 +00001386void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
Dan Gohman2048b852009-11-23 18:04:58 +00001387 MachineBasicBlock *TBB,
1388 MachineBasicBlock *FBB,
1389 MachineBasicBlock *CurBB,
Dan Gohman99be8ae2010-04-19 22:41:47 +00001390 MachineBasicBlock *SwitchBB,
Dan Gohman2048b852009-11-23 18:04:58 +00001391 unsigned Opc) {
Dan Gohmanc2277342008-10-17 21:16:08 +00001392 // If this node is not part of the or/and tree, emit it as a branch.
Dan Gohman46510a72010-04-15 01:51:59 +00001393 const Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001394 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001395 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1396 BOp->getParent() != CurBB->getBasicBlock() ||
1397 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1398 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Dan Gohman99be8ae2010-04-19 22:41:47 +00001399 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001400 return;
1401 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001402
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001403 // Create TmpBB after CurBB.
1404 MachineFunction::iterator BBI = CurBB;
1405 MachineFunction &MF = DAG.getMachineFunction();
1406 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1407 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001408
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001409 if (Opc == Instruction::Or) {
1410 // Codegen X | Y as:
1411 // jmp_if_X TBB
1412 // jmp TmpBB
1413 // TmpBB:
1414 // jmp_if_Y TBB
1415 // jmp FBB
1416 //
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001417
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001418 // Emit the LHS condition.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001419 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001420
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001421 // Emit the RHS condition into TmpBB.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001422 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001423 } else {
1424 assert(Opc == Instruction::And && "Unknown merge op!");
1425 // Codegen X & Y as:
1426 // jmp_if_X TmpBB
1427 // jmp FBB
1428 // TmpBB:
1429 // jmp_if_Y TBB
1430 // jmp FBB
1431 //
1432 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001433
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001434 // Emit the LHS condition.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001435 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001436
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001437 // Emit the RHS condition into TmpBB.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001438 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001439 }
1440}
1441
1442/// If the set of cases should be emitted as a series of branches, return true.
1443/// If we should emit this as a bunch of and/or'd together conditions, return
1444/// false.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001445bool
Dan Gohman2048b852009-11-23 18:04:58 +00001446SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001447 if (Cases.size() != 2) return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001448
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001449 // If this is two comparisons of the same values or'd or and'd together, they
1450 // will get folded into a single comparison, so don't emit two blocks.
1451 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1452 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1453 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1454 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1455 return false;
1456 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001457
Chris Lattner133ce872010-01-02 00:00:03 +00001458 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1459 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1460 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1461 Cases[0].CC == Cases[1].CC &&
1462 isa<Constant>(Cases[0].CmpRHS) &&
1463 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1464 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1465 return false;
1466 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1467 return false;
1468 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00001469
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001470 return true;
1471}
1472
Dan Gohman46510a72010-04-15 01:51:59 +00001473void SelectionDAGBuilder::visitBr(const BranchInst &I) {
Dan Gohman84023e02010-07-10 09:00:22 +00001474 MachineBasicBlock *BrMBB = FuncInfo.MBB;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001475
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001476 // Update machine-CFG edges.
1477 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1478
1479 // Figure out which block is immediately after the current one.
1480 MachineBasicBlock *NextBlock = 0;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001481 MachineFunction::iterator BBI = BrMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001482 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001483 NextBlock = BBI;
1484
1485 if (I.isUnconditional()) {
1486 // Update machine-CFG edges.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001487 BrMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001488
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001489 // If this is not a fall-through branch, emit the branch.
Bill Wendling4533cac2010-01-28 21:51:40 +00001490 if (Succ0MBB != NextBlock)
1491 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001492 MVT::Other, getControlRoot(),
Bill Wendling4533cac2010-01-28 21:51:40 +00001493 DAG.getBasicBlock(Succ0MBB)));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001494
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001495 return;
1496 }
1497
1498 // If this condition is one of the special cases we handle, do special stuff
1499 // now.
Dan Gohman46510a72010-04-15 01:51:59 +00001500 const Value *CondVal = I.getCondition();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001501 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1502
1503 // If this is a series of conditions that are or'd or and'd together, emit
1504 // this as a sequence of branches instead of setcc's with and/or operations.
Chris Lattnerde189be2010-11-30 18:12:52 +00001505 // As long as jumps are not expensive, this should improve performance.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001506 // For example, instead of something like:
1507 // cmp A, B
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001508 // C = seteq
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001509 // cmp D, E
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001510 // F = setle
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001511 // or C, F
1512 // jnz foo
1513 // Emit:
1514 // cmp A, B
1515 // je foo
1516 // cmp D, E
1517 // jle foo
1518 //
Dan Gohman46510a72010-04-15 01:51:59 +00001519 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Owen Anderson95771af2011-02-25 21:41:48 +00001520 if (!TLI.isJumpExpensive() &&
Chris Lattnerde189be2010-11-30 18:12:52 +00001521 BOp->hasOneUse() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001522 (BOp->getOpcode() == Instruction::And ||
1523 BOp->getOpcode() == Instruction::Or)) {
Dan Gohman99be8ae2010-04-19 22:41:47 +00001524 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1525 BOp->getOpcode());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001526 // If the compares in later blocks need to use values not currently
1527 // exported from this block, export them now. This block should always
1528 // be the first entry.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001529 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001530
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001531 // Allow some cases to be rejected.
1532 if (ShouldEmitAsBranches(SwitchCases)) {
1533 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1534 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1535 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1536 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001537
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001538 // Emit the branch for this block.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001539 visitSwitchCase(SwitchCases[0], BrMBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001540 SwitchCases.erase(SwitchCases.begin());
1541 return;
1542 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001543
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001544 // Okay, we decided not to do this, remove any inserted MBB's and clear
1545 // SwitchCases.
1546 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001547 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001548
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001549 SwitchCases.clear();
1550 }
1551 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001552
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001553 // Create a CaseBlock record representing this branch.
Owen Anderson5defacc2009-07-31 17:39:07 +00001554 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohman99be8ae2010-04-19 22:41:47 +00001555 NULL, Succ0MBB, Succ1MBB, BrMBB);
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001556
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001557 // Use visitSwitchCase to actually insert the fast branch sequence for this
1558 // cond branch.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001559 visitSwitchCase(CB, BrMBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001560}
1561
1562/// visitSwitchCase - Emits the necessary code to represent a single node in
1563/// the binary search tree resulting from lowering a switch instruction.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001564void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1565 MachineBasicBlock *SwitchBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001566 SDValue Cond;
1567 SDValue CondLHS = getValue(CB.CmpLHS);
Dale Johannesenf5d97892009-02-04 01:48:28 +00001568 DebugLoc dl = getCurDebugLoc();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001569
1570 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001571 if (CB.CmpMHS == NULL) {
1572 // Fold "(X == true)" to X and "(X == false)" to !X to
1573 // handle common cases produced by branch lowering.
Owen Anderson5defacc2009-07-31 17:39:07 +00001574 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
Owen Andersonf53c3712009-07-21 02:47:59 +00001575 CB.CC == ISD::SETEQ)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001576 Cond = CondLHS;
Owen Anderson5defacc2009-07-31 17:39:07 +00001577 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
Owen Andersonf53c3712009-07-21 02:47:59 +00001578 CB.CC == ISD::SETEQ) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001579 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001580 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001581 } else
Owen Anderson825b72b2009-08-11 20:47:22 +00001582 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001583 } else {
Stepan Dyatkovskiyc187df22012-05-17 08:56:30 +00001584 assert(CB.CC == ISD::SETCC_INVALID &&
1585 "Condition is undefined for to-the-range belonging check.");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001586
Anton Korobeynikov23218582008-12-23 22:25:27 +00001587 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1588 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001589
1590 SDValue CmpOp = getValue(CB.CmpMHS);
Owen Andersone50ed302009-08-10 22:56:29 +00001591 EVT VT = CmpOp.getValueType();
Stepan Dyatkovskiyc187df22012-05-17 08:56:30 +00001592
1593 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(false)) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001594 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Stepan Dyatkovskiyc187df22012-05-17 08:56:30 +00001595 ISD::SETULE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001596 } else {
Dale Johannesenf5d97892009-02-04 01:48:28 +00001597 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001598 VT, CmpOp, DAG.getConstant(Low, VT));
Owen Anderson825b72b2009-08-11 20:47:22 +00001599 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001600 DAG.getConstant(High-Low, VT), ISD::SETULE);
1601 }
1602 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001603
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001604 // Update successor info
Jakub Staszakc8f34de2011-07-29 22:25:21 +00001605 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
Jakob Stoklund Olesene7fdef42012-08-20 21:39:52 +00001606 // TrueBB and FalseBB are always different unless the incoming IR is
1607 // degenerate. This only happens when running llc on weird IR.
1608 if (CB.TrueBB != CB.FalseBB)
1609 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001610
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001611 // Set NextBlock to be the MBB immediately after the current one, if any.
1612 // This is used to avoid emitting unnecessary branches to the next block.
1613 MachineBasicBlock *NextBlock = 0;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001614 MachineFunction::iterator BBI = SwitchBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001615 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001616 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001617
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001618 // If the lhs block is the next block, invert the condition so that we can
1619 // fall through to the lhs instead of the rhs block.
1620 if (CB.TrueBB == NextBlock) {
1621 std::swap(CB.TrueBB, CB.FalseBB);
1622 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001623 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001624 }
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001625
Dale Johannesenf5d97892009-02-04 01:48:28 +00001626 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00001627 MVT::Other, getControlRoot(), Cond,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001628 DAG.getBasicBlock(CB.TrueBB));
Bill Wendling87710f02009-12-21 23:47:40 +00001629
Evan Cheng266a99d2010-09-23 06:51:55 +00001630 // Insert the false branch. Do this even if it's a fall through branch,
1631 // this makes it easier to do DAG optimizations which require inverting
1632 // the branch condition.
1633 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1634 DAG.getBasicBlock(CB.FalseBB));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001635
1636 DAG.setRoot(BrCond);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001637}
1638
1639/// visitJumpTable - Emit JumpTable node in the current MBB
Dan Gohman2048b852009-11-23 18:04:58 +00001640void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001641 // Emit the code for the jump table
1642 assert(JT.Reg != -1U && "Should lower JT Header first!");
Owen Andersone50ed302009-08-10 22:56:29 +00001643 EVT PTy = TLI.getPointerTy();
Dale Johannesena04b7572009-02-03 23:04:43 +00001644 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1645 JT.Reg, PTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001646 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001647 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1648 MVT::Other, Index.getValue(1),
1649 Table, Index);
1650 DAG.setRoot(BrJumpTable);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001651}
1652
1653/// visitJumpTableHeader - This function emits necessary code to produce index
1654/// in the JumpTable from switch case.
Dan Gohman2048b852009-11-23 18:04:58 +00001655void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
Dan Gohman99be8ae2010-04-19 22:41:47 +00001656 JumpTableHeader &JTH,
1657 MachineBasicBlock *SwitchBB) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001658 // Subtract the lowest switch case value from the value being switched on and
1659 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001660 // difference between smallest and largest cases.
1661 SDValue SwitchOp = getValue(JTH.SValue);
Owen Andersone50ed302009-08-10 22:56:29 +00001662 EVT VT = SwitchOp.getValueType();
Bill Wendling87710f02009-12-21 23:47:40 +00001663 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001664 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001665
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001666 // The SDNode we just created, which holds the value being switched on minus
Dan Gohmanf451cb82010-02-10 16:03:48 +00001667 // the smallest case value, needs to be copied to a virtual register so it
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001668 // can be used as an index into the jump table in a subsequent basic block.
1669 // This value may be smaller or larger than the target's pointer type, and
1670 // therefore require extension or truncating.
Bill Wendling87710f02009-12-21 23:47:40 +00001671 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001672
Dan Gohman89496d02010-07-02 00:10:16 +00001673 unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001674 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1675 JumpTableReg, SwitchOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001676 JT.Reg = JumpTableReg;
1677
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001678 // Emit the range check for the jump table, and branch to the default block
1679 // for the switch statement if the value being switched on exceeds the largest
1680 // case in the switch.
Dale Johannesenf5d97892009-02-04 01:48:28 +00001681 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00001682 TLI.getSetCCResultType(Sub.getValueType()), Sub,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001683 DAG.getConstant(JTH.Last-JTH.First,VT),
1684 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001685
1686 // Set NextBlock to be the MBB immediately after the current one, if any.
1687 // This is used to avoid emitting unnecessary branches to the next block.
1688 MachineBasicBlock *NextBlock = 0;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001689 MachineFunction::iterator BBI = SwitchBB;
Bill Wendling87710f02009-12-21 23:47:40 +00001690
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001691 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001692 NextBlock = BBI;
1693
Dale Johannesen66978ee2009-01-31 02:22:37 +00001694 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001695 MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001696 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001697
Bill Wendling4533cac2010-01-28 21:51:40 +00001698 if (JT.MBB != NextBlock)
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001699 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1700 DAG.getBasicBlock(JT.MBB));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001701
Bill Wendling87710f02009-12-21 23:47:40 +00001702 DAG.setRoot(BrCond);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001703}
1704
1705/// visitBitTestHeader - This function emits necessary code to produce value
1706/// suitable for "bit tests"
Dan Gohman99be8ae2010-04-19 22:41:47 +00001707void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1708 MachineBasicBlock *SwitchBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001709 // Subtract the minimum value
1710 SDValue SwitchOp = getValue(B.SValue);
Owen Andersone50ed302009-08-10 22:56:29 +00001711 EVT VT = SwitchOp.getValueType();
Bill Wendling87710f02009-12-21 23:47:40 +00001712 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001713 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001714
1715 // Check range
Dale Johannesenf5d97892009-02-04 01:48:28 +00001716 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00001717 TLI.getSetCCResultType(Sub.getValueType()),
1718 Sub, DAG.getConstant(B.Range, VT),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001719 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001720
Evan Chengd08e5b42011-01-06 01:02:44 +00001721 // Determine the type of the test operands.
1722 bool UsePtrType = false;
1723 if (!TLI.isTypeLegal(VT))
1724 UsePtrType = true;
1725 else {
1726 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
Eli Friedman5c75af62011-10-12 22:46:45 +00001727 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
Evan Chengd08e5b42011-01-06 01:02:44 +00001728 // Switch table case range are encoded into series of masks.
1729 // Just use pointer type, it's guaranteed to fit.
1730 UsePtrType = true;
1731 break;
1732 }
1733 }
1734 if (UsePtrType) {
1735 VT = TLI.getPointerTy();
1736 Sub = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), VT);
1737 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001738
Evan Chengd08e5b42011-01-06 01:02:44 +00001739 B.RegVT = VT;
1740 B.Reg = FuncInfo.CreateReg(VT);
Dale Johannesena04b7572009-02-03 23:04:43 +00001741 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
Evan Chengd08e5b42011-01-06 01:02:44 +00001742 B.Reg, Sub);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001743
1744 // Set NextBlock to be the MBB immediately after the current one, if any.
1745 // This is used to avoid emitting unnecessary branches to the next block.
1746 MachineBasicBlock *NextBlock = 0;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001747 MachineFunction::iterator BBI = SwitchBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001748 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001749 NextBlock = BBI;
1750
1751 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1752
Jakub Staszak7cc2b072011-06-16 20:22:37 +00001753 addSuccessorWithWeight(SwitchBB, B.Default);
1754 addSuccessorWithWeight(SwitchBB, MBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001755
Dale Johannesen66978ee2009-01-31 02:22:37 +00001756 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001757 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001758 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001759
Evan Cheng8c1f4322010-09-23 18:32:19 +00001760 if (MBB != NextBlock)
1761 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1762 DAG.getBasicBlock(MBB));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001763
Bill Wendling87710f02009-12-21 23:47:40 +00001764 DAG.setRoot(BrRange);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001765}
1766
1767/// visitBitTestCase - this function produces one "bit test"
Evan Chengd08e5b42011-01-06 01:02:44 +00001768void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1769 MachineBasicBlock* NextMBB,
Manman Ren1a710fd2012-08-24 18:14:27 +00001770 uint32_t BranchWeightToNext,
Dan Gohman2048b852009-11-23 18:04:58 +00001771 unsigned Reg,
Dan Gohman99be8ae2010-04-19 22:41:47 +00001772 BitTestCase &B,
1773 MachineBasicBlock *SwitchBB) {
Evan Chengd08e5b42011-01-06 01:02:44 +00001774 EVT VT = BB.RegVT;
1775 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1776 Reg, VT);
Dan Gohman8e0163a2010-06-24 02:06:24 +00001777 SDValue Cmp;
Benjamin Kramer3ff25512011-07-14 01:38:42 +00001778 unsigned PopCount = CountPopulation_64(B.Mask);
1779 if (PopCount == 1) {
Dan Gohman8e0163a2010-06-24 02:06:24 +00001780 // Testing for a single bit; just compare the shift count with what it
1781 // would need to be to shift a 1 bit in that position.
1782 Cmp = DAG.getSetCC(getCurDebugLoc(),
Evan Chengd08e5b42011-01-06 01:02:44 +00001783 TLI.getSetCCResultType(VT),
Dan Gohman8e0163a2010-06-24 02:06:24 +00001784 ShiftOp,
Evan Chengd08e5b42011-01-06 01:02:44 +00001785 DAG.getConstant(CountTrailingZeros_64(B.Mask), VT),
Dan Gohman8e0163a2010-06-24 02:06:24 +00001786 ISD::SETEQ);
Benjamin Kramer3ff25512011-07-14 01:38:42 +00001787 } else if (PopCount == BB.Range) {
1788 // There is only one zero bit in the range, test for it directly.
1789 Cmp = DAG.getSetCC(getCurDebugLoc(),
1790 TLI.getSetCCResultType(VT),
1791 ShiftOp,
1792 DAG.getConstant(CountTrailingOnes_64(B.Mask), VT),
1793 ISD::SETNE);
Dan Gohman8e0163a2010-06-24 02:06:24 +00001794 } else {
1795 // Make desired shift
Evan Chengd08e5b42011-01-06 01:02:44 +00001796 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(), VT,
1797 DAG.getConstant(1, VT), ShiftOp);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001798
Dan Gohman8e0163a2010-06-24 02:06:24 +00001799 // Emit bit tests and jumps
1800 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
Evan Chengd08e5b42011-01-06 01:02:44 +00001801 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
Dan Gohman8e0163a2010-06-24 02:06:24 +00001802 Cmp = DAG.getSetCC(getCurDebugLoc(),
Evan Chengd08e5b42011-01-06 01:02:44 +00001803 TLI.getSetCCResultType(VT),
1804 AndOp, DAG.getConstant(0, VT),
Dan Gohman8e0163a2010-06-24 02:06:24 +00001805 ISD::SETNE);
1806 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001807
Manman Ren1a710fd2012-08-24 18:14:27 +00001808 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
1809 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
1810 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
1811 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001812
Dale Johannesen66978ee2009-01-31 02:22:37 +00001813 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001814 MVT::Other, getControlRoot(),
Dan Gohman8e0163a2010-06-24 02:06:24 +00001815 Cmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001816
1817 // Set NextBlock to be the MBB immediately after the current one, if any.
1818 // This is used to avoid emitting unnecessary branches to the next block.
1819 MachineBasicBlock *NextBlock = 0;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001820 MachineFunction::iterator BBI = SwitchBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001821 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001822 NextBlock = BBI;
1823
Evan Cheng8c1f4322010-09-23 18:32:19 +00001824 if (NextMBB != NextBlock)
1825 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1826 DAG.getBasicBlock(NextMBB));
Bill Wendling0777e922009-12-21 21:59:52 +00001827
Bill Wendling87710f02009-12-21 23:47:40 +00001828 DAG.setRoot(BrAnd);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001829}
1830
Dan Gohman46510a72010-04-15 01:51:59 +00001831void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
Dan Gohman84023e02010-07-10 09:00:22 +00001832 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001833
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001834 // Retrieve successors.
1835 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1836 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1837
Gabor Greifb67e6b32009-01-15 11:10:44 +00001838 const Value *Callee(I.getCalledValue());
Nuno Lopes85b40892012-06-28 22:30:12 +00001839 const Function *Fn = dyn_cast<Function>(Callee);
Gabor Greifb67e6b32009-01-15 11:10:44 +00001840 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001841 visitInlineAsm(&I);
Nuno Lopes85b40892012-06-28 22:30:12 +00001842 else if (Fn && Fn->isIntrinsic()) {
1843 assert(Fn->getIntrinsicID() == Intrinsic::donothing);
Nuno Lopes4532bf62012-07-18 00:07:17 +00001844 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
Nuno Lopes85b40892012-06-28 22:30:12 +00001845 } else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001846 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001847
1848 // If the value of the invoke is used outside of its defining block, make it
1849 // available as a virtual register.
Dan Gohmanad62f532009-04-23 23:13:24 +00001850 CopyToExportRegsIfNeeded(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001851
1852 // Update successor info
Chandler Carruthf2645682011-11-22 11:37:46 +00001853 addSuccessorWithWeight(InvokeMBB, Return);
1854 addSuccessorWithWeight(InvokeMBB, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001855
1856 // Drop into normal successor.
Bill Wendling4533cac2010-01-28 21:51:40 +00001857 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1858 MVT::Other, getControlRoot(),
1859 DAG.getBasicBlock(Return)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001860}
1861
Bill Wendlingdccc03b2011-07-31 06:30:59 +00001862void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
1863 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
1864}
1865
Bill Wendling2ac0e6b2011-08-17 21:56:44 +00001866void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
1867 assert(FuncInfo.MBB->isLandingPad() &&
1868 "Call to landingpad not in landing pad!");
1869
1870 MachineBasicBlock *MBB = FuncInfo.MBB;
1871 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
1872 AddLandingPadInfo(LP, MMI, MBB);
1873
Bill Wendlingbdf9db62012-02-13 23:47:16 +00001874 // If there aren't registers to copy the values into (e.g., during SjLj
1875 // exceptions), then don't bother to create these DAG nodes.
Lang Hames07961342012-02-14 04:45:49 +00001876 if (TLI.getExceptionPointerRegister() == 0 &&
Bill Wendlingbdf9db62012-02-13 23:47:16 +00001877 TLI.getExceptionSelectorRegister() == 0)
1878 return;
1879
Bill Wendling2ac0e6b2011-08-17 21:56:44 +00001880 SmallVector<EVT, 2> ValueVTs;
1881 ComputeValueVTs(TLI, LP.getType(), ValueVTs);
1882
1883 // Insert the EXCEPTIONADDR instruction.
1884 assert(FuncInfo.MBB->isLandingPad() &&
1885 "Call to eh.exception not in landing pad!");
1886 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
1887 SDValue Ops[2];
1888 Ops[0] = DAG.getRoot();
1889 SDValue Op1 = DAG.getNode(ISD::EXCEPTIONADDR, getCurDebugLoc(), VTs, Ops, 1);
1890 SDValue Chain = Op1.getValue(1);
1891
1892 // Insert the EHSELECTION instruction.
1893 VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
1894 Ops[0] = Op1;
1895 Ops[1] = Chain;
1896 SDValue Op2 = DAG.getNode(ISD::EHSELECTION, getCurDebugLoc(), VTs, Ops, 2);
1897 Chain = Op2.getValue(1);
1898 Op2 = DAG.getSExtOrTrunc(Op2, getCurDebugLoc(), MVT::i32);
1899
1900 Ops[0] = Op1;
1901 Ops[1] = Op2;
1902 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
1903 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1904 &Ops[0], 2);
1905
1906 std::pair<SDValue, SDValue> RetPair = std::make_pair(Res, Chain);
1907 setValue(&LP, RetPair.first);
1908 DAG.setRoot(RetPair.second);
1909}
1910
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001911/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1912/// small case ranges).
Dan Gohman2048b852009-11-23 18:04:58 +00001913bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1914 CaseRecVector& WorkList,
Dan Gohman46510a72010-04-15 01:51:59 +00001915 const Value* SV,
Dan Gohman99be8ae2010-04-19 22:41:47 +00001916 MachineBasicBlock *Default,
1917 MachineBasicBlock *SwitchBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001918 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001919 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001920 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001921 return false;
1922
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001923 // Get the MachineFunction which holds the current MBB. This is used when
1924 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001925 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001926
1927 // Figure out which block is immediately after the current one.
1928 MachineBasicBlock *NextBlock = 0;
1929 MachineFunction::iterator BBI = CR.CaseBB;
1930
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001931 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001932 NextBlock = BBI;
1933
Manman Ren1a710fd2012-08-24 18:14:27 +00001934 BranchProbabilityInfo *BPI = FuncInfo.BPI;
Benjamin Kramerce750f02010-11-22 09:45:38 +00001935 // If any two of the cases has the same destination, and if one value
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001936 // is the same as the other, but has one bit unset that the other has set,
1937 // use bit manipulation to do two compares at once. For example:
1938 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Benjamin Kramerce750f02010-11-22 09:45:38 +00001939 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
1940 // TODO: Handle cases where CR.CaseBB != SwitchBB.
1941 if (Size == 2 && CR.CaseBB == SwitchBB) {
1942 Case &Small = *CR.Range.first;
1943 Case &Big = *(CR.Range.second-1);
1944
1945 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
1946 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
1947 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
1948
1949 // Check that there is only one bit different.
1950 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
1951 (SmallValue | BigValue) == BigValue) {
1952 // Isolate the common bit.
1953 APInt CommonBit = BigValue & ~SmallValue;
1954 assert((SmallValue | CommonBit) == BigValue &&
1955 CommonBit.countPopulation() == 1 && "Not a common bit?");
1956
1957 SDValue CondLHS = getValue(SV);
1958 EVT VT = CondLHS.getValueType();
1959 DebugLoc DL = getCurDebugLoc();
1960
1961 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
1962 DAG.getConstant(CommonBit, VT));
1963 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
1964 Or, DAG.getConstant(BigValue, VT),
1965 ISD::SETEQ);
1966
1967 // Update successor info.
Manman Ren1a710fd2012-08-24 18:14:27 +00001968 // Both Small and Big will jump to Small.BB, so we sum up the weights.
1969 addSuccessorWithWeight(SwitchBB, Small.BB,
1970 Small.ExtraWeight + Big.ExtraWeight);
1971 addSuccessorWithWeight(SwitchBB, Default,
1972 // The default destination is the first successor in IR.
1973 BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
Benjamin Kramerce750f02010-11-22 09:45:38 +00001974
1975 // Insert the true branch.
1976 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
1977 getControlRoot(), Cond,
1978 DAG.getBasicBlock(Small.BB));
1979
1980 // Insert the false branch.
1981 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
1982 DAG.getBasicBlock(Default));
1983
1984 DAG.setRoot(BrCond);
1985 return true;
1986 }
1987 }
1988 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001989
Benjamin Kramerc511b2a2012-05-26 20:01:32 +00001990 // Order cases by weight so the most likely case will be checked first.
Manman Ren1a710fd2012-08-24 18:14:27 +00001991 uint32_t UnhandledWeights = 0;
Benjamin Kramerc511b2a2012-05-26 20:01:32 +00001992 if (BPI) {
1993 for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
Manman Ren1a710fd2012-08-24 18:14:27 +00001994 uint32_t IWeight = I->ExtraWeight;
1995 UnhandledWeights += IWeight;
Benjamin Kramerc511b2a2012-05-26 20:01:32 +00001996 for (CaseItr J = CR.Range.first; J < I; ++J) {
Manman Ren1a710fd2012-08-24 18:14:27 +00001997 uint32_t JWeight = J->ExtraWeight;
Benjamin Kramerc511b2a2012-05-26 20:01:32 +00001998 if (IWeight > JWeight)
1999 std::swap(*I, *J);
2000 }
2001 }
2002 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002003 // Rearrange the case blocks so that the last one falls through if possible.
Benjamin Kramerc511b2a2012-05-26 20:01:32 +00002004 Case &BackCase = *(CR.Range.second-1);
Benjamin Kramer5db954d2012-05-26 21:19:12 +00002005 if (Size > 1 &&
2006 NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002007 // The last case block won't fall through into 'NextBlock' if we emit the
2008 // branches in this order. See if rearranging a case value would help.
Benjamin Kramerc511b2a2012-05-26 20:01:32 +00002009 // We start at the bottom as it's the case with the least weight.
Benjamin Kramercf1d69d2012-05-27 10:56:55 +00002010 for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002011 if (I->BB == NextBlock) {
2012 std::swap(*I, BackCase);
2013 break;
2014 }
2015 }
2016 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002017
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002018 // Create a CaseBlock record representing a conditional branch to
2019 // the Case's target mbb if the value being switched on SV is equal
2020 // to C.
2021 MachineBasicBlock *CurBlock = CR.CaseBB;
2022 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2023 MachineBasicBlock *FallThrough;
2024 if (I != E-1) {
2025 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2026 CurMF->insert(BBI, FallThrough);
Dan Gohman8e5c0da2009-04-09 02:33:36 +00002027
2028 // Put SV in a virtual register to make it available from the new blocks.
2029 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002030 } else {
2031 // If the last case doesn't match, go to the default block.
2032 FallThrough = Default;
2033 }
2034
Dan Gohman46510a72010-04-15 01:51:59 +00002035 const Value *RHS, *LHS, *MHS;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002036 ISD::CondCode CC;
2037 if (I->High == I->Low) {
2038 // This is just small small case range :) containing exactly 1 case
2039 CC = ISD::SETEQ;
2040 LHS = SV; RHS = I->High; MHS = NULL;
2041 } else {
Stepan Dyatkovskiyc187df22012-05-17 08:56:30 +00002042 CC = ISD::SETCC_INVALID;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002043 LHS = I->Low; MHS = SV; RHS = I->High;
2044 }
Jakub Staszakc8f34de2011-07-29 22:25:21 +00002045
Manman Ren1a710fd2012-08-24 18:14:27 +00002046 // The false weight should be sum of all un-handled cases.
2047 UnhandledWeights -= I->ExtraWeight;
Jakub Staszakc8f34de2011-07-29 22:25:21 +00002048 CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
2049 /* me */ CurBlock,
Manman Ren1a710fd2012-08-24 18:14:27 +00002050 /* trueweight */ I->ExtraWeight,
2051 /* falseweight */ UnhandledWeights);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002052
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002053 // If emitting the first comparison, just call visitSwitchCase to emit the
2054 // code into the current block. Otherwise, push the CaseBlock onto the
2055 // vector to be later processed by SDISel, and insert the node's MBB
2056 // before the next MBB.
Dan Gohman99be8ae2010-04-19 22:41:47 +00002057 if (CurBlock == SwitchBB)
2058 visitSwitchCase(CB, SwitchBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002059 else
2060 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002061
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002062 CurBlock = FallThrough;
2063 }
2064
2065 return true;
2066}
2067
2068static inline bool areJTsAllowed(const TargetLowering &TLI) {
Evan Cheng769951f2012-07-02 22:39:56 +00002069 return TLI.supportJumpTables() &&
Owen Anderson825b72b2009-08-11 20:47:22 +00002070 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
2071 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002072}
Anton Korobeynikov23218582008-12-23 22:25:27 +00002073
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002074static APInt ComputeRange(const APInt &First, const APInt &Last) {
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002075 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
Stepan Dyatkovskiyc187df22012-05-17 08:56:30 +00002076 APInt LastExt = Last.zext(BitWidth), FirstExt = First.zext(BitWidth);
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002077 return (LastExt - FirstExt + 1ULL);
2078}
2079
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002080/// handleJTSwitchCase - Emit jumptable for current switch case range
Chris Lattnerc3ab3882011-09-09 22:06:59 +00002081bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
2082 CaseRecVector &WorkList,
2083 const Value *SV,
2084 MachineBasicBlock *Default,
Dan Gohman99be8ae2010-04-19 22:41:47 +00002085 MachineBasicBlock *SwitchBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002086 Case& FrontCase = *CR.Range.first;
2087 Case& BackCase = *(CR.Range.second-1);
2088
Chris Lattnere880efe2009-11-07 07:50:34 +00002089 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2090 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002091
Chris Lattnere880efe2009-11-07 07:50:34 +00002092 APInt TSize(First.getBitWidth(), 0);
Chris Lattnerc3ab3882011-09-09 22:06:59 +00002093 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002094 TSize += I->size();
2095
Dan Gohmane0567812010-04-08 23:03:40 +00002096 if (!areJTsAllowed(TLI) || TSize.ult(4))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002097 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002098
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002099 APInt Range = ComputeRange(First, Last);
Jakob Stoklund Olesen79443912011-10-26 01:47:48 +00002100 // The density is TSize / Range. Require at least 40%.
2101 // It should not be possible for IntTSize to saturate for sane code, but make
2102 // sure we handle Range saturation correctly.
2103 uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
2104 uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
2105 if (IntTSize * 10 < IntRange * 4)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002106 return false;
2107
David Greene4b69d992010-01-05 01:24:57 +00002108 DEBUG(dbgs() << "Lowering jump table\n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002109 << "First entry: " << First << ". Last entry: " << Last << '\n'
Jakob Stoklund Olesen79443912011-10-26 01:47:48 +00002110 << "Range: " << Range << ". Size: " << TSize << ".\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002111
2112 // Get the MachineFunction which holds the current MBB. This is used when
2113 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00002114 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002115
2116 // Figure out which block is immediately after the current one.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002117 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands51498522009-09-06 18:03:32 +00002118 ++BBI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002119
2120 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2121
2122 // Create a new basic block to hold the code for loading the address
2123 // of the jump table, and jumping to it. Update successor information;
2124 // we will either branch to the default case for the switch, or the jump
2125 // table.
2126 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2127 CurMF->insert(BBI, JumpTableBB);
Jakub Staszak7cc2b072011-06-16 20:22:37 +00002128
2129 addSuccessorWithWeight(CR.CaseBB, Default);
2130 addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002131
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002132 // Build a vector of destination BBs, corresponding to each target
2133 // of the jump table. If the value of the jump table slot corresponds to
2134 // a case statement, push the case's BB onto the vector, otherwise, push
2135 // the default BB.
2136 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002137 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002138 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Chris Lattner071c62f2010-01-25 23:26:13 +00002139 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
2140 const APInt &High = cast<ConstantInt>(I->High)->getValue();
Anton Korobeynikov23218582008-12-23 22:25:27 +00002141
Stepan Dyatkovskiyc187df22012-05-17 08:56:30 +00002142 if (Low.ule(TEI) && TEI.ule(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002143 DestBBs.push_back(I->BB);
2144 if (TEI==High)
2145 ++I;
2146 } else {
2147 DestBBs.push_back(Default);
2148 }
2149 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002150
Manman Ren1a710fd2012-08-24 18:14:27 +00002151 // Calculate weight for each unique destination in CR.
2152 DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
2153 if (FuncInfo.BPI)
2154 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2155 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2156 DestWeights.find(I->BB);
2157 if (Itr != DestWeights.end())
2158 Itr->second += I->ExtraWeight;
2159 else
2160 DestWeights[I->BB] = I->ExtraWeight;
2161 }
2162
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002163 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002164 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2165 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002166 E = DestBBs.end(); I != E; ++I) {
2167 if (!SuccsHandled[(*I)->getNumber()]) {
2168 SuccsHandled[(*I)->getNumber()] = true;
Manman Ren1a710fd2012-08-24 18:14:27 +00002169 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2170 DestWeights.find(*I);
2171 addSuccessorWithWeight(JumpTableBB, *I,
2172 Itr != DestWeights.end() ? Itr->second : 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002173 }
2174 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002175
Bob Wilsond1ec31d2010-03-18 18:42:41 +00002176 // Create a jump table index for this jump table.
Chris Lattner071c62f2010-01-25 23:26:13 +00002177 unsigned JTEncoding = TLI.getJumpTableEncoding();
2178 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
Bob Wilsond1ec31d2010-03-18 18:42:41 +00002179 ->createJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002180
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002181 // Set the jump table information so that we can codegen it as a second
2182 // MachineBasicBlock
2183 JumpTable JT(-1U, JTI, JumpTableBB, Default);
Dan Gohman99be8ae2010-04-19 22:41:47 +00002184 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2185 if (CR.CaseBB == SwitchBB)
2186 visitJumpTableHeader(JT, JTH, SwitchBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002187
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002188 JTCases.push_back(JumpTableBlock(JTH, JT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002189 return true;
2190}
2191
2192/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2193/// 2 subtrees.
Dan Gohman2048b852009-11-23 18:04:58 +00002194bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2195 CaseRecVector& WorkList,
Dan Gohman46510a72010-04-15 01:51:59 +00002196 const Value* SV,
Dan Gohman99be8ae2010-04-19 22:41:47 +00002197 MachineBasicBlock *Default,
2198 MachineBasicBlock *SwitchBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002199 // Get the MachineFunction which holds the current MBB. This is used when
2200 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00002201 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002202
2203 // Figure out which block is immediately after the current one.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002204 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands51498522009-09-06 18:03:32 +00002205 ++BBI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002206
2207 Case& FrontCase = *CR.Range.first;
2208 Case& BackCase = *(CR.Range.second-1);
2209 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2210
2211 // Size is the number of Cases represented by this range.
2212 unsigned Size = CR.Range.second - CR.Range.first;
2213
Chris Lattnere880efe2009-11-07 07:50:34 +00002214 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2215 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002216 double FMetric = 0;
2217 CaseItr Pivot = CR.Range.first + Size/2;
2218
2219 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2220 // (heuristically) allow us to emit JumpTable's later.
Chris Lattnere880efe2009-11-07 07:50:34 +00002221 APInt TSize(First.getBitWidth(), 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002222 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2223 I!=E; ++I)
2224 TSize += I->size();
2225
Chris Lattnere880efe2009-11-07 07:50:34 +00002226 APInt LSize = FrontCase.size();
2227 APInt RSize = TSize-LSize;
David Greene4b69d992010-01-05 01:24:57 +00002228 DEBUG(dbgs() << "Selecting best pivot: \n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002229 << "First: " << First << ", Last: " << Last <<'\n'
2230 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002231 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2232 J!=E; ++I, ++J) {
Chris Lattnere880efe2009-11-07 07:50:34 +00002233 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2234 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002235 APInt Range = ComputeRange(LEnd, RBegin);
Stepan Dyatkovskiyc2c52a62012-05-15 06:50:18 +00002236 assert((Range - 2ULL).isNonNegative() &&
2237 "Invalid case distance");
Chris Lattnerc3e4e592011-04-09 06:57:13 +00002238 // Use volatile double here to avoid excess precision issues on some hosts,
2239 // e.g. that use 80-bit X87 registers.
2240 volatile double LDensity =
2241 (double)LSize.roundToDouble() /
Chris Lattnere880efe2009-11-07 07:50:34 +00002242 (LEnd - First + 1ULL).roundToDouble();
Chris Lattnerc3e4e592011-04-09 06:57:13 +00002243 volatile double RDensity =
2244 (double)RSize.roundToDouble() /
Chris Lattnere880efe2009-11-07 07:50:34 +00002245 (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002246 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002247 // Should always split in some non-trivial place
David Greene4b69d992010-01-05 01:24:57 +00002248 DEBUG(dbgs() <<"=>Step\n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002249 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2250 << "LDensity: " << LDensity
2251 << ", RDensity: " << RDensity << '\n'
2252 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002253 if (FMetric < Metric) {
2254 Pivot = J;
2255 FMetric = Metric;
David Greene4b69d992010-01-05 01:24:57 +00002256 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002257 }
2258
2259 LSize += J->size();
2260 RSize -= J->size();
2261 }
2262 if (areJTsAllowed(TLI)) {
2263 // If our case is dense we *really* should handle it earlier!
2264 assert((FMetric > 0) && "Should handle dense range earlier!");
2265 } else {
2266 Pivot = CR.Range.first + Size/2;
2267 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002268
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002269 CaseRange LHSR(CR.Range.first, Pivot);
2270 CaseRange RHSR(Pivot, CR.Range.second);
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002271 const Constant *C = Pivot->Low;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002272 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002273
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002274 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002275 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002276 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002277 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002278 // Pivot's Value, then we can branch directly to the LHS's Target,
2279 // rather than creating a leaf node for it.
2280 if ((LHSR.second - LHSR.first) == 1 &&
2281 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00002282 cast<ConstantInt>(C)->getValue() ==
2283 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002284 TrueBB = LHSR.first->BB;
2285 } else {
2286 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2287 CurMF->insert(BBI, TrueBB);
2288 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00002289
2290 // Put SV in a virtual register to make it available from the new blocks.
2291 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002292 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002293
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002294 // Similar to the optimization above, if the Value being switched on is
2295 // known to be less than the Constant CR.LT, and the current Case Value
2296 // is CR.LT - 1, then we can branch directly to the target block for
2297 // the current Case Value, rather than emitting a RHS leaf node for it.
2298 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00002299 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2300 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002301 FalseBB = RHSR.first->BB;
2302 } else {
2303 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2304 CurMF->insert(BBI, FalseBB);
2305 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00002306
2307 // Put SV in a virtual register to make it available from the new blocks.
2308 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002309 }
2310
2311 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002312 // the LHS node if the value being switched on SV is less than C.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002313 // Otherwise, branch to LHS.
Stepan Dyatkovskiyc187df22012-05-17 08:56:30 +00002314 CaseBlock CB(ISD::SETULT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002315
Dan Gohman99be8ae2010-04-19 22:41:47 +00002316 if (CR.CaseBB == SwitchBB)
2317 visitSwitchCase(CB, SwitchBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002318 else
2319 SwitchCases.push_back(CB);
2320
2321 return true;
2322}
2323
2324/// handleBitTestsSwitchCase - if current case range has few destination and
2325/// range span less, than machine word bitwidth, encode case range into series
2326/// of masks and emit bit tests with these masks.
Dan Gohman2048b852009-11-23 18:04:58 +00002327bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2328 CaseRecVector& WorkList,
Dan Gohman46510a72010-04-15 01:51:59 +00002329 const Value* SV,
Dan Gohman99be8ae2010-04-19 22:41:47 +00002330 MachineBasicBlock* Default,
2331 MachineBasicBlock *SwitchBB){
Owen Andersone50ed302009-08-10 22:56:29 +00002332 EVT PTy = TLI.getPointerTy();
Owen Anderson77547be2009-08-10 18:56:59 +00002333 unsigned IntPtrBits = PTy.getSizeInBits();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002334
2335 Case& FrontCase = *CR.Range.first;
2336 Case& BackCase = *(CR.Range.second-1);
2337
2338 // Get the MachineFunction which holds the current MBB. This is used when
2339 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00002340 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002341
Anton Korobeynikovd34167a2009-05-08 18:51:34 +00002342 // If target does not have legal shift left, do not emit bit tests at all.
2343 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
2344 return false;
2345
Anton Korobeynikov23218582008-12-23 22:25:27 +00002346 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002347 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2348 I!=E; ++I) {
2349 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002350 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002351 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002352
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002353 // Count unique destinations
2354 SmallSet<MachineBasicBlock*, 4> Dests;
2355 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2356 Dests.insert(I->BB);
2357 if (Dests.size() > 3)
2358 // Don't bother the code below, if there are too much unique destinations
2359 return false;
2360 }
David Greene4b69d992010-01-05 01:24:57 +00002361 DEBUG(dbgs() << "Total number of unique destinations: "
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002362 << Dests.size() << '\n'
2363 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00002364
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002365 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002366 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2367 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002368 APInt cmpRange = maxValue - minValue;
2369
David Greene4b69d992010-01-05 01:24:57 +00002370 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002371 << "Low bound: " << minValue << '\n'
2372 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00002373
Dan Gohmane0567812010-04-08 23:03:40 +00002374 if (cmpRange.uge(IntPtrBits) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002375 (!(Dests.size() == 1 && numCmps >= 3) &&
2376 !(Dests.size() == 2 && numCmps >= 5) &&
2377 !(Dests.size() >= 3 && numCmps >= 6)))
2378 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002379
David Greene4b69d992010-01-05 01:24:57 +00002380 DEBUG(dbgs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00002381 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2382
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002383 // Optimize the case where all the case values fit in a
2384 // word without having to subtract minValue. In this case,
2385 // we can optimize away the subtraction.
Stepan Dyatkovskiyc187df22012-05-17 08:56:30 +00002386 if (maxValue.ult(IntPtrBits)) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00002387 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002388 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00002389 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002390 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002391
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002392 CaseBitsVector CasesBits;
2393 unsigned i, count = 0;
2394
2395 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2396 MachineBasicBlock* Dest = I->BB;
2397 for (i = 0; i < count; ++i)
2398 if (Dest == CasesBits[i].BB)
2399 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002400
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002401 if (i == count) {
2402 assert((count < 3) && "Too much destinations to test!");
Manman Ren1a710fd2012-08-24 18:14:27 +00002403 CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002404 count++;
2405 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002406
2407 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2408 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2409
2410 uint64_t lo = (lowValue - lowBound).getZExtValue();
2411 uint64_t hi = (highValue - lowBound).getZExtValue();
Manman Ren1a710fd2012-08-24 18:14:27 +00002412 CasesBits[i].ExtraWeight += I->ExtraWeight;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002413
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002414 for (uint64_t j = lo; j <= hi; j++) {
2415 CasesBits[i].Mask |= 1ULL << j;
2416 CasesBits[i].Bits++;
2417 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002418
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002419 }
2420 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00002421
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002422 BitTestInfo BTC;
2423
2424 // Figure out which block is immediately after the current one.
2425 MachineFunction::iterator BBI = CR.CaseBB;
2426 ++BBI;
2427
2428 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2429
David Greene4b69d992010-01-05 01:24:57 +00002430 DEBUG(dbgs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002431 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
David Greene4b69d992010-01-05 01:24:57 +00002432 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002433 << ", Bits: " << CasesBits[i].Bits
2434 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002435
2436 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2437 CurMF->insert(BBI, CaseBB);
2438 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2439 CaseBB,
Manman Ren1a710fd2012-08-24 18:14:27 +00002440 CasesBits[i].BB, CasesBits[i].ExtraWeight));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00002441
2442 // Put SV in a virtual register to make it available from the new blocks.
2443 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002444 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002445
2446 BitTestBlock BTB(lowBound, cmpRange, SV,
Evan Chengd08e5b42011-01-06 01:02:44 +00002447 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002448 CR.CaseBB, Default, BTC);
2449
Dan Gohman99be8ae2010-04-19 22:41:47 +00002450 if (CR.CaseBB == SwitchBB)
2451 visitBitTestHeader(BTB, SwitchBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002452
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002453 BitTestCases.push_back(BTB);
2454
2455 return true;
2456}
2457
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002458/// Clusterify - Transform simple list of Cases into list of CaseRange's
Dan Gohman2048b852009-11-23 18:04:58 +00002459size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2460 const SwitchInst& SI) {
Stepan Dyatkovskiy05cfe2e2012-05-18 08:32:28 +00002461
2462 /// Use a shorter form of declaration, and also
2463 /// show the we want to use CRSBuilder as Clusterifier.
Stepan Dyatkovskiy4319a552012-06-02 07:26:00 +00002464 typedef IntegersSubsetMapping<MachineBasicBlock> Clusterifier;
Stepan Dyatkovskiy05cfe2e2012-05-18 08:32:28 +00002465
2466 Clusterifier TheClusterifier;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002467
Manman Ren1a710fd2012-08-24 18:14:27 +00002468 BranchProbabilityInfo *BPI = FuncInfo.BPI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002469 // Start with "simple" cases
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002470 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002471 i != e; ++i) {
2472 const BasicBlock *SuccBB = i.getCaseSuccessor();
Jakub Staszakc8f34de2011-07-29 22:25:21 +00002473 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
2474
Manman Ren1a710fd2012-08-24 18:14:27 +00002475 TheClusterifier.add(i.getCaseValueEx(), SMBB,
2476 BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002477 }
Stepan Dyatkovskiy05cfe2e2012-05-18 08:32:28 +00002478
2479 TheClusterifier.optimize();
2480
Stepan Dyatkovskiy05cfe2e2012-05-18 08:32:28 +00002481 size_t numCmps = 0;
2482 for (Clusterifier::RangeIterator i = TheClusterifier.begin(),
2483 e = TheClusterifier.end(); i != e; ++i, ++numCmps) {
Stepan Dyatkovskiy66d79ce2012-07-04 05:53:05 +00002484 Clusterifier::Cluster &C = *i;
Manman Ren1a710fd2012-08-24 18:14:27 +00002485 // Update edge weight for the cluster.
2486 unsigned W = C.first.Weight;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002487
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002488 // FIXME: Currently work with ConstantInt based numbers.
2489 // Changing it to APInt based is a pretty heavy for this commit.
Stepan Dyatkovskiy66d79ce2012-07-04 05:53:05 +00002490 Cases.push_back(Case(C.first.getLow().toConstantInt(),
2491 C.first.getHigh().toConstantInt(), C.second, W));
Stepan Dyatkovskiy05cfe2e2012-05-18 08:32:28 +00002492
Stepan Dyatkovskiy66d79ce2012-07-04 05:53:05 +00002493 if (C.first.getLow() != C.first.getHigh())
Stepan Dyatkovskiy05cfe2e2012-05-18 08:32:28 +00002494 // A range counts double, since it requires two compares.
2495 ++numCmps;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002496 }
2497
2498 return numCmps;
2499}
2500
Jakob Stoklund Olesen2622f462010-09-30 19:44:31 +00002501void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2502 MachineBasicBlock *Last) {
2503 // Update JTCases.
2504 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2505 if (JTCases[i].first.HeaderBB == First)
2506 JTCases[i].first.HeaderBB = Last;
2507
2508 // Update BitTestCases.
2509 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2510 if (BitTestCases[i].Parent == First)
2511 BitTestCases[i].Parent = Last;
2512}
2513
Dan Gohman46510a72010-04-15 01:51:59 +00002514void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
Dan Gohman84023e02010-07-10 09:00:22 +00002515 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
Dan Gohman99be8ae2010-04-19 22:41:47 +00002516
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002517 // Figure out which block is immediately after the current one.
2518 MachineBasicBlock *NextBlock = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002519 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2520
2521 // If there is only the default destination, branch to it if it is not the
2522 // next basic block. Otherwise, just fall through.
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002523 if (!SI.getNumCases()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002524 // Update machine-CFG edges.
2525
2526 // If this is not a fall-through branch, emit the branch.
Dan Gohman99be8ae2010-04-19 22:41:47 +00002527 SwitchMBB->addSuccessor(Default);
Bill Wendling4533cac2010-01-28 21:51:40 +00002528 if (Default != NextBlock)
2529 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2530 MVT::Other, getControlRoot(),
2531 DAG.getBasicBlock(Default)));
Bill Wendling49fcff82009-12-21 22:30:11 +00002532
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002533 return;
2534 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002535
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002536 // If there are any non-default case statements, create a vector of Cases
2537 // representing each one, and sort the vector so that we can efficiently
2538 // create a binary search tree from them.
2539 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002540 size_t numCmps = Clusterify(Cases, SI);
David Greene4b69d992010-01-05 01:24:57 +00002541 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002542 << ". Total compares: " << numCmps << '\n');
Duncan Sands17001ce2011-10-18 12:44:00 +00002543 (void)numCmps;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002544
2545 // Get the Value to be switched on and default basic blocks, which will be
2546 // inserted into CaseBlock records, representing basic blocks in the binary
2547 // search tree.
Eli Friedmanbb5a7442011-09-29 20:21:17 +00002548 const Value *SV = SI.getCondition();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002549
2550 // Push the initial CaseRec onto the worklist
2551 CaseRecVector WorkList;
Dan Gohman99be8ae2010-04-19 22:41:47 +00002552 WorkList.push_back(CaseRec(SwitchMBB,0,0,
2553 CaseRange(Cases.begin(),Cases.end())));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002554
2555 while (!WorkList.empty()) {
2556 // Grab a record representing a case range to process off the worklist
2557 CaseRec CR = WorkList.back();
2558 WorkList.pop_back();
2559
Dan Gohman99be8ae2010-04-19 22:41:47 +00002560 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002561 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002562
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002563 // If the range has few cases (two or less) emit a series of specific
2564 // tests.
Dan Gohman99be8ae2010-04-19 22:41:47 +00002565 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002566 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002567
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002568 // If the switch has more than 5 blocks, and at least 40% dense, and the
2569 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002570 // lowering the switch to a binary tree of conditional branches.
Dan Gohman99be8ae2010-04-19 22:41:47 +00002571 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002572 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002573
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002574 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2575 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
Dan Gohman99be8ae2010-04-19 22:41:47 +00002576 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002577 }
2578}
2579
Dan Gohman46510a72010-04-15 01:51:59 +00002580void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
Dan Gohman84023e02010-07-10 09:00:22 +00002581 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
Dan Gohman99be8ae2010-04-19 22:41:47 +00002582
Jakob Stoklund Olesen598b24c2010-02-11 00:34:18 +00002583 // Update machine-CFG edges with unique successors.
Jakob Stoklund Olesenb5b90ed2010-02-11 18:06:56 +00002584 SmallVector<BasicBlock*, 32> succs;
Jakob Stoklund Olesen598b24c2010-02-11 00:34:18 +00002585 succs.reserve(I.getNumSuccessors());
Dan Gohmaneef55dc2009-10-27 22:10:34 +00002586 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
Jakob Stoklund Olesen598b24c2010-02-11 00:34:18 +00002587 succs.push_back(I.getSuccessor(i));
Jakob Stoklund Olesenb5b90ed2010-02-11 18:06:56 +00002588 array_pod_sort(succs.begin(), succs.end());
Jakob Stoklund Olesen598b24c2010-02-11 00:34:18 +00002589 succs.erase(std::unique(succs.begin(), succs.end()), succs.end());
Jakub Staszak7cc2b072011-06-16 20:22:37 +00002590 for (unsigned i = 0, e = succs.size(); i != e; ++i) {
2591 MachineBasicBlock *Succ = FuncInfo.MBBMap[succs[i]];
2592 addSuccessorWithWeight(IndirectBrMBB, Succ);
2593 }
Dan Gohmaneef55dc2009-10-27 22:10:34 +00002594
Bill Wendling4533cac2010-01-28 21:51:40 +00002595 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2596 MVT::Other, getControlRoot(),
2597 getValue(I.getAddress())));
Bill Wendling49fcff82009-12-21 22:30:11 +00002598}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002599
Dan Gohman46510a72010-04-15 01:51:59 +00002600void SelectionDAGBuilder::visitFSub(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002601 // -0.0 - X --> fneg
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002602 Type *Ty = I.getType();
Chris Lattner2ca5c862011-02-15 00:14:00 +00002603 if (isa<Constant>(I.getOperand(0)) &&
2604 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2605 SDValue Op2 = getValue(I.getOperand(1));
2606 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2607 Op2.getValueType(), Op2));
2608 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002609 }
Bill Wendling49fcff82009-12-21 22:30:11 +00002610
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002611 visitBinary(I, ISD::FSUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002612}
2613
Dan Gohman46510a72010-04-15 01:51:59 +00002614void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002615 SDValue Op1 = getValue(I.getOperand(0));
2616 SDValue Op2 = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00002617 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2618 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002619}
2620
Dan Gohman46510a72010-04-15 01:51:59 +00002621void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002622 SDValue Op1 = getValue(I.getOperand(0));
2623 SDValue Op2 = getValue(I.getOperand(1));
Owen Anderson95771af2011-02-25 21:41:48 +00002624
2625 MVT ShiftTy = TLI.getShiftAmountTy(Op2.getValueType());
2626
Chris Lattnerd3027732011-02-13 09:02:52 +00002627 // Coerce the shift amount to the right type if we can.
2628 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
Chris Lattner915eeb42011-02-13 09:10:56 +00002629 unsigned ShiftSize = ShiftTy.getSizeInBits();
2630 unsigned Op2Size = Op2.getValueType().getSizeInBits();
Chris Lattnerd3027732011-02-13 09:02:52 +00002631 DebugLoc DL = getCurDebugLoc();
Owen Anderson95771af2011-02-25 21:41:48 +00002632
Dan Gohman57fc82d2009-04-09 03:51:29 +00002633 // If the operand is smaller than the shift count type, promote it.
Chris Lattnerd3027732011-02-13 09:02:52 +00002634 if (ShiftSize > Op2Size)
2635 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
Owen Anderson95771af2011-02-25 21:41:48 +00002636
Dan Gohman57fc82d2009-04-09 03:51:29 +00002637 // If the operand is larger than the shift count type but the shift
2638 // count type has enough bits to represent any shift value, truncate
2639 // it now. This is a common case and it exposes the truncate to
2640 // optimization early.
Chris Lattnerd3027732011-02-13 09:02:52 +00002641 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2642 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2643 // Otherwise we'll need to temporarily settle for some other convenient
Chris Lattnere0751182011-02-13 19:09:16 +00002644 // type. Type legalization will make adjustments once the shiftee is split.
Chris Lattnerd3027732011-02-13 09:02:52 +00002645 else
Chris Lattnere0751182011-02-13 19:09:16 +00002646 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002647 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002648
Bill Wendling4533cac2010-01-28 21:51:40 +00002649 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2650 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002651}
2652
Benjamin Kramer9c640302011-07-08 10:31:30 +00002653void SelectionDAGBuilder::visitSDiv(const User &I) {
Benjamin Kramer9c640302011-07-08 10:31:30 +00002654 SDValue Op1 = getValue(I.getOperand(0));
2655 SDValue Op2 = getValue(I.getOperand(1));
2656
2657 // Turn exact SDivs into multiplications.
2658 // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2659 // exact bit.
Benjamin Kramer3492a4a2011-07-08 12:08:24 +00002660 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2661 !isa<ConstantSDNode>(Op1) &&
Benjamin Kramer9c640302011-07-08 10:31:30 +00002662 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
2663 setValue(&I, TLI.BuildExactSDIV(Op1, Op2, getCurDebugLoc(), DAG));
2664 else
2665 setValue(&I, DAG.getNode(ISD::SDIV, getCurDebugLoc(), Op1.getValueType(),
2666 Op1, Op2));
2667}
2668
Dan Gohman46510a72010-04-15 01:51:59 +00002669void SelectionDAGBuilder::visitICmp(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002670 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
Dan Gohman46510a72010-04-15 01:51:59 +00002671 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002672 predicate = IC->getPredicate();
Dan Gohman46510a72010-04-15 01:51:59 +00002673 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002674 predicate = ICmpInst::Predicate(IC->getPredicate());
2675 SDValue Op1 = getValue(I.getOperand(0));
2676 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002677 ISD::CondCode Opcode = getICmpCondCode(predicate);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002678
Owen Andersone50ed302009-08-10 22:56:29 +00002679 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002680 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002681}
2682
Dan Gohman46510a72010-04-15 01:51:59 +00002683void SelectionDAGBuilder::visitFCmp(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002684 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
Dan Gohman46510a72010-04-15 01:51:59 +00002685 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002686 predicate = FC->getPredicate();
Dan Gohman46510a72010-04-15 01:51:59 +00002687 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002688 predicate = FCmpInst::Predicate(FC->getPredicate());
2689 SDValue Op1 = getValue(I.getOperand(0));
2690 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002691 ISD::CondCode Condition = getFCmpCondCode(predicate);
Nick Lewycky8a8d4792011-12-02 22:16:29 +00002692 if (TM.Options.NoNaNsFPMath)
2693 Condition = getFCmpCodeWithoutNaN(Condition);
Owen Andersone50ed302009-08-10 22:56:29 +00002694 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002695 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002696}
2697
Dan Gohman46510a72010-04-15 01:51:59 +00002698void SelectionDAGBuilder::visitSelect(const User &I) {
Owen Andersone50ed302009-08-10 22:56:29 +00002699 SmallVector<EVT, 4> ValueVTs;
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002700 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2701 unsigned NumValues = ValueVTs.size();
Bill Wendling49fcff82009-12-21 22:30:11 +00002702 if (NumValues == 0) return;
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002703
Bill Wendling49fcff82009-12-21 22:30:11 +00002704 SmallVector<SDValue, 4> Values(NumValues);
2705 SDValue Cond = getValue(I.getOperand(0));
2706 SDValue TrueVal = getValue(I.getOperand(1));
2707 SDValue FalseVal = getValue(I.getOperand(2));
Duncan Sands28b77e92011-09-06 19:07:46 +00002708 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2709 ISD::VSELECT : ISD::SELECT;
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002710
Bill Wendling4533cac2010-01-28 21:51:40 +00002711 for (unsigned i = 0; i != NumValues; ++i)
Duncan Sands28b77e92011-09-06 19:07:46 +00002712 Values[i] = DAG.getNode(OpCode, getCurDebugLoc(),
2713 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
Chris Lattnerb3e87b22010-03-12 07:15:36 +00002714 Cond,
Bill Wendling49fcff82009-12-21 22:30:11 +00002715 SDValue(TrueVal.getNode(),
2716 TrueVal.getResNo() + i),
2717 SDValue(FalseVal.getNode(),
2718 FalseVal.getResNo() + i));
2719
Bill Wendling4533cac2010-01-28 21:51:40 +00002720 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2721 DAG.getVTList(&ValueVTs[0], NumValues),
2722 &Values[0], NumValues));
Bill Wendling49fcff82009-12-21 22:30:11 +00002723}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002724
Dan Gohman46510a72010-04-15 01:51:59 +00002725void SelectionDAGBuilder::visitTrunc(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002726 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2727 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002728 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002729 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002730}
2731
Dan Gohman46510a72010-04-15 01:51:59 +00002732void SelectionDAGBuilder::visitZExt(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002733 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2734 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2735 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002736 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002737 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002738}
2739
Dan Gohman46510a72010-04-15 01:51:59 +00002740void SelectionDAGBuilder::visitSExt(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002741 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2742 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2743 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002744 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002745 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002746}
2747
Dan Gohman46510a72010-04-15 01:51:59 +00002748void SelectionDAGBuilder::visitFPTrunc(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002749 // FPTrunc is never a no-op cast, no need to check
2750 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002751 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002752 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
Pete Cooperf57e1c22012-01-17 01:54:07 +00002753 DestVT, N,
2754 DAG.getTargetConstant(0, TLI.getPointerTy())));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002755}
2756
Dan Gohman46510a72010-04-15 01:51:59 +00002757void SelectionDAGBuilder::visitFPExt(const User &I){
Hal Finkel46bb70c2011-10-18 03:51:57 +00002758 // FPExt is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002759 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002760 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002761 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002762}
2763
Dan Gohman46510a72010-04-15 01:51:59 +00002764void SelectionDAGBuilder::visitFPToUI(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002765 // FPToUI is never a no-op cast, no need to check
2766 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002767 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002768 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002769}
2770
Dan Gohman46510a72010-04-15 01:51:59 +00002771void SelectionDAGBuilder::visitFPToSI(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002772 // FPToSI is never a no-op cast, no need to check
2773 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002774 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002775 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002776}
2777
Dan Gohman46510a72010-04-15 01:51:59 +00002778void SelectionDAGBuilder::visitUIToFP(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002779 // UIToFP is never a no-op cast, no need to check
2780 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002781 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002782 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002783}
2784
Dan Gohman46510a72010-04-15 01:51:59 +00002785void SelectionDAGBuilder::visitSIToFP(const User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002786 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002787 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002788 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002789 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002790}
2791
Dan Gohman46510a72010-04-15 01:51:59 +00002792void SelectionDAGBuilder::visitPtrToInt(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002793 // What to do depends on the size of the integer and the size of the pointer.
2794 // We can either truncate, zero extend, or no-op, accordingly.
2795 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002796 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002797 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002798}
2799
Dan Gohman46510a72010-04-15 01:51:59 +00002800void SelectionDAGBuilder::visitIntToPtr(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002801 // What to do depends on the size of the integer and the size of the pointer.
2802 // We can either truncate, zero extend, or no-op, accordingly.
2803 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002804 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002805 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002806}
2807
Dan Gohman46510a72010-04-15 01:51:59 +00002808void SelectionDAGBuilder::visitBitCast(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002809 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002810 EVT DestVT = TLI.getValueType(I.getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002811
Bill Wendling49fcff82009-12-21 22:30:11 +00002812 // BitCast assures us that source and destination are the same size so this is
Wesley Peckbf17cfa2010-11-23 03:31:01 +00002813 // either a BITCAST or a no-op.
Bill Wendling4533cac2010-01-28 21:51:40 +00002814 if (DestVT != N.getValueType())
Wesley Peckbf17cfa2010-11-23 03:31:01 +00002815 setValue(&I, DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
Bill Wendling4533cac2010-01-28 21:51:40 +00002816 DestVT, N)); // convert types.
2817 else
Bill Wendling49fcff82009-12-21 22:30:11 +00002818 setValue(&I, N); // noop cast.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002819}
2820
Dan Gohman46510a72010-04-15 01:51:59 +00002821void SelectionDAGBuilder::visitInsertElement(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002822 SDValue InVec = getValue(I.getOperand(0));
2823 SDValue InVal = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002824 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00002825 TLI.getPointerTy(),
2826 getValue(I.getOperand(2)));
Bill Wendling4533cac2010-01-28 21:51:40 +00002827 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2828 TLI.getValueType(I.getType()),
2829 InVec, InVal, InIdx));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002830}
2831
Dan Gohman46510a72010-04-15 01:51:59 +00002832void SelectionDAGBuilder::visitExtractElement(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002833 SDValue InVec = getValue(I.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00002834 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00002835 TLI.getPointerTy(),
2836 getValue(I.getOperand(1)));
Bill Wendling4533cac2010-01-28 21:51:40 +00002837 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2838 TLI.getValueType(I.getType()), InVec, InIdx));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002839}
2840
Craig Topper51578342012-01-04 09:23:09 +00002841// Utility for visitShuffleVector - Return true if every element in Mask,
Benjamin Kramerd9b0b022012-06-02 10:20:22 +00002842// beginning from position Pos and ending in Pos+Size, falls within the
Craig Topper51578342012-01-04 09:23:09 +00002843// specified sequential range [L, L+Pos). or is undef.
2844static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
Craig Topper23de31b2012-04-11 03:06:35 +00002845 unsigned Pos, unsigned Size, int Low) {
2846 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
Craig Topper51578342012-01-04 09:23:09 +00002847 if (Mask[i] >= 0 && Mask[i] != Low)
Nate Begeman9008ca62009-04-27 18:41:29 +00002848 return false;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002849 return true;
2850}
2851
Dan Gohman46510a72010-04-15 01:51:59 +00002852void SelectionDAGBuilder::visitShuffleVector(const User &I) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002853 SDValue Src1 = getValue(I.getOperand(0));
2854 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002855
Chris Lattner56243b82012-01-26 02:51:13 +00002856 SmallVector<int, 8> Mask;
2857 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
2858 unsigned MaskNumElts = Mask.size();
2859
Owen Andersone50ed302009-08-10 22:56:29 +00002860 EVT VT = TLI.getValueType(I.getType());
2861 EVT SrcVT = Src1.getValueType();
Nate Begeman5a5ca152009-04-29 05:20:52 +00002862 unsigned SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002863
Mon P Wangc7849c22008-11-16 05:06:27 +00002864 if (SrcNumElts == MaskNumElts) {
Bill Wendling4533cac2010-01-28 21:51:40 +00002865 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2866 &Mask[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002867 return;
2868 }
2869
2870 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002871 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2872 // Mask is longer than the source vectors and is a multiple of the source
2873 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002874 // lengths match.
Craig Topper51578342012-01-04 09:23:09 +00002875 if (SrcNumElts*2 == MaskNumElts) {
2876 // First check for Src1 in low and Src2 in high
2877 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
2878 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
2879 // The shuffle is concatenating two vectors together.
2880 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2881 VT, Src1, Src2));
2882 return;
2883 }
2884 // Then check for Src2 in low and Src1 in high
2885 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
2886 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
2887 // The shuffle is concatenating two vectors together.
2888 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2889 VT, Src2, Src1));
2890 return;
2891 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002892 }
2893
Mon P Wangc7849c22008-11-16 05:06:27 +00002894 // Pad both vectors with undefs to make them the same length as the mask.
2895 unsigned NumConcat = MaskNumElts / SrcNumElts;
Nate Begeman9008ca62009-04-27 18:41:29 +00002896 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2897 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
Dale Johannesene8d72302009-02-06 23:05:02 +00002898 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002899
Nate Begeman9008ca62009-04-27 18:41:29 +00002900 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2901 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002902 MOps1[0] = Src1;
2903 MOps2[0] = Src2;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002904
2905 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2906 getCurDebugLoc(), VT,
Nate Begeman9008ca62009-04-27 18:41:29 +00002907 &MOps1[0], NumConcat);
2908 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002909 getCurDebugLoc(), VT,
Nate Begeman9008ca62009-04-27 18:41:29 +00002910 &MOps2[0], NumConcat);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002911
Mon P Wangaeb06d22008-11-10 04:46:22 +00002912 // Readjust mask for new input vector length.
Nate Begeman9008ca62009-04-27 18:41:29 +00002913 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002914 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002915 int Idx = Mask[i];
Craig Topper23de31b2012-04-11 03:06:35 +00002916 if (Idx >= (int)SrcNumElts)
2917 Idx -= SrcNumElts - MaskNumElts;
2918 MappedOps.push_back(Idx);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002919 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002920
Bill Wendling4533cac2010-01-28 21:51:40 +00002921 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2922 &MappedOps[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002923 return;
2924 }
2925
Mon P Wangc7849c22008-11-16 05:06:27 +00002926 if (SrcNumElts > MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002927 // Analyze the access pattern of the vector to see if we can extract
2928 // two subvectors and do the shuffle. The analysis is done by calculating
2929 // the range of elements the mask access on both vectors.
Craig Topper10612dc2012-04-08 23:15:04 +00002930 int MinRange[2] = { static_cast<int>(SrcNumElts),
2931 static_cast<int>(SrcNumElts)};
Mon P Wangc7849c22008-11-16 05:06:27 +00002932 int MaxRange[2] = {-1, -1};
2933
Nate Begeman5a5ca152009-04-29 05:20:52 +00002934 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002935 int Idx = Mask[i];
Craig Topper10612dc2012-04-08 23:15:04 +00002936 unsigned Input = 0;
Nate Begeman9008ca62009-04-27 18:41:29 +00002937 if (Idx < 0)
2938 continue;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002939
Nate Begeman5a5ca152009-04-29 05:20:52 +00002940 if (Idx >= (int)SrcNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002941 Input = 1;
2942 Idx -= SrcNumElts;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002943 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002944 if (Idx > MaxRange[Input])
2945 MaxRange[Input] = Idx;
2946 if (Idx < MinRange[Input])
2947 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002948 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002949
Mon P Wangc7849c22008-11-16 05:06:27 +00002950 // Check if the access is smaller than the vector size and can we find
2951 // a reasonable extract index.
Craig Topper10612dc2012-04-08 23:15:04 +00002952 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
2953 // Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002954 int StartIdx[2]; // StartIdx to extract from
Craig Topper10612dc2012-04-08 23:15:04 +00002955 for (unsigned Input = 0; Input < 2; ++Input) {
2956 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002957 RangeUse[Input] = 0; // Unused
2958 StartIdx[Input] = 0;
Craig Topperf873dde2012-04-08 17:53:33 +00002959 continue;
Mon P Wang230e4fa2008-11-21 04:25:21 +00002960 }
Craig Topperf873dde2012-04-08 17:53:33 +00002961
2962 // Find a good start index that is a multiple of the mask length. Then
2963 // see if the rest of the elements are in range.
2964 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2965 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2966 StartIdx[Input] + MaskNumElts <= SrcNumElts)
2967 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002968 }
2969
Bill Wendling636e2582009-08-21 18:16:06 +00002970 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
Bill Wendling4533cac2010-01-28 21:51:40 +00002971 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wangc7849c22008-11-16 05:06:27 +00002972 return;
2973 }
Craig Topper10612dc2012-04-08 23:15:04 +00002974 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002975 // Extract appropriate subvector and generate a vector shuffle
Craig Topper10612dc2012-04-08 23:15:04 +00002976 for (unsigned Input = 0; Input < 2; ++Input) {
Bill Wendling87710f02009-12-21 23:47:40 +00002977 SDValue &Src = Input == 0 ? Src1 : Src2;
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002978 if (RangeUse[Input] == 0)
Dale Johannesene8d72302009-02-06 23:05:02 +00002979 Src = DAG.getUNDEF(VT);
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002980 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00002981 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002982 Src, DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002983 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002984
Mon P Wangc7849c22008-11-16 05:06:27 +00002985 // Calculate new mask.
Nate Begeman9008ca62009-04-27 18:41:29 +00002986 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002987 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002988 int Idx = Mask[i];
Craig Topper23de31b2012-04-11 03:06:35 +00002989 if (Idx >= 0) {
2990 if (Idx < (int)SrcNumElts)
2991 Idx -= StartIdx[0];
2992 else
2993 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
2994 }
2995 MappedOps.push_back(Idx);
Mon P Wangc7849c22008-11-16 05:06:27 +00002996 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002997
Bill Wendling4533cac2010-01-28 21:51:40 +00002998 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2999 &MappedOps[0]));
Mon P Wangc7849c22008-11-16 05:06:27 +00003000 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00003001 }
3002 }
3003
Mon P Wangc7849c22008-11-16 05:06:27 +00003004 // We can't use either concat vectors or extract subvectors so fall back to
3005 // replacing the shuffle with extract and build vector.
3006 // to insert and build vector.
Owen Andersone50ed302009-08-10 22:56:29 +00003007 EVT EltVT = VT.getVectorElementType();
3008 EVT PtrVT = TLI.getPointerTy();
Mon P Wangaeb06d22008-11-10 04:46:22 +00003009 SmallVector<SDValue,8> Ops;
Nate Begeman5a5ca152009-04-29 05:20:52 +00003010 for (unsigned i = 0; i != MaskNumElts; ++i) {
Craig Topper23de31b2012-04-11 03:06:35 +00003011 int Idx = Mask[i];
3012 SDValue Res;
3013
3014 if (Idx < 0) {
3015 Res = DAG.getUNDEF(EltVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00003016 } else {
Craig Topper23de31b2012-04-11 03:06:35 +00003017 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3018 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
Bill Wendlingb85b6e82009-12-21 22:42:14 +00003019
Craig Topper23de31b2012-04-11 03:06:35 +00003020 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
3021 EltVT, Src, DAG.getConstant(Idx, PtrVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00003022 }
Craig Topper23de31b2012-04-11 03:06:35 +00003023
3024 Ops.push_back(Res);
Mon P Wangaeb06d22008-11-10 04:46:22 +00003025 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00003026
Bill Wendling4533cac2010-01-28 21:51:40 +00003027 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
3028 VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003029}
3030
Dan Gohman46510a72010-04-15 01:51:59 +00003031void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003032 const Value *Op0 = I.getOperand(0);
3033 const Value *Op1 = I.getOperand(1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003034 Type *AggTy = I.getType();
3035 Type *ValTy = Op1->getType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003036 bool IntoUndef = isa<UndefValue>(Op0);
3037 bool FromUndef = isa<UndefValue>(Op1);
3038
Jay Foadfc6d3a42011-07-13 10:26:04 +00003039 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003040
Owen Andersone50ed302009-08-10 22:56:29 +00003041 SmallVector<EVT, 4> AggValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003042 ComputeValueVTs(TLI, AggTy, AggValueVTs);
Owen Andersone50ed302009-08-10 22:56:29 +00003043 SmallVector<EVT, 4> ValValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003044 ComputeValueVTs(TLI, ValTy, ValValueVTs);
3045
3046 unsigned NumAggValues = AggValueVTs.size();
3047 unsigned NumValValues = ValValueVTs.size();
3048 SmallVector<SDValue, 4> Values(NumAggValues);
3049
3050 SDValue Agg = getValue(Op0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003051 unsigned i = 0;
3052 // Copy the beginning value(s) from the original aggregate.
3053 for (; i != LinearIndex; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00003054 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003055 SDValue(Agg.getNode(), Agg.getResNo() + i);
3056 // Copy values from the inserted value(s).
Rafael Espindola3fa82832011-05-13 15:18:06 +00003057 if (NumValValues) {
3058 SDValue Val = getValue(Op1);
3059 for (; i != LinearIndex + NumValValues; ++i)
3060 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3061 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3062 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003063 // Copy remaining value(s) from the original aggregate.
3064 for (; i != NumAggValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00003065 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003066 SDValue(Agg.getNode(), Agg.getResNo() + i);
3067
Bill Wendling4533cac2010-01-28 21:51:40 +00003068 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
3069 DAG.getVTList(&AggValueVTs[0], NumAggValues),
3070 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003071}
3072
Dan Gohman46510a72010-04-15 01:51:59 +00003073void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003074 const Value *Op0 = I.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003075 Type *AggTy = Op0->getType();
3076 Type *ValTy = I.getType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003077 bool OutOfUndef = isa<UndefValue>(Op0);
3078
Jay Foadfc6d3a42011-07-13 10:26:04 +00003079 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003080
Owen Andersone50ed302009-08-10 22:56:29 +00003081 SmallVector<EVT, 4> ValValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003082 ComputeValueVTs(TLI, ValTy, ValValueVTs);
3083
3084 unsigned NumValValues = ValValueVTs.size();
Rafael Espindola3fa82832011-05-13 15:18:06 +00003085
3086 // Ignore a extractvalue that produces an empty object
3087 if (!NumValValues) {
3088 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3089 return;
3090 }
3091
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003092 SmallVector<SDValue, 4> Values(NumValValues);
3093
3094 SDValue Agg = getValue(Op0);
3095 // Copy out the selected value(s).
3096 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3097 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00003098 OutOfUndef ?
Dale Johannesene8d72302009-02-06 23:05:02 +00003099 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00003100 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003101
Bill Wendling4533cac2010-01-28 21:51:40 +00003102 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
3103 DAG.getVTList(&ValValueVTs[0], NumValValues),
3104 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003105}
3106
Dan Gohman46510a72010-04-15 01:51:59 +00003107void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003108 SDValue N = getValue(I.getOperand(0));
Nadav Rotem1c239202012-02-28 14:13:19 +00003109 // Note that the pointer operand may be a vector of pointers. Take the scalar
3110 // element which holds a pointer.
3111 Type *Ty = I.getOperand(0)->getType()->getScalarType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003112
Dan Gohman46510a72010-04-15 01:51:59 +00003113 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003114 OI != E; ++OI) {
Dan Gohman46510a72010-04-15 01:51:59 +00003115 const Value *Idx = *OI;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003116 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003117 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
3118 if (Field) {
3119 // N = N + Offset
3120 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003121 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003122 DAG.getIntPtrConstant(Offset));
3123 }
Bill Wendlinge1a90422009-12-21 23:10:19 +00003124
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003125 Ty = StTy->getElementType(Field);
3126 } else {
3127 Ty = cast<SequentialType>(Ty)->getElementType();
3128
3129 // If this is a constant subscript, handle it quickly.
Dan Gohman46510a72010-04-15 01:51:59 +00003130 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Dan Gohmane368b462010-06-18 14:22:04 +00003131 if (CI->isZero()) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003132 uint64_t Offs =
Duncan Sands777d2302009-05-09 07:06:46 +00003133 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Cheng65b52df2009-02-09 21:01:06 +00003134 SDValue OffsVal;
Owen Andersone50ed302009-08-10 22:56:29 +00003135 EVT PTy = TLI.getPointerTy();
Owen Anderson77547be2009-08-10 18:56:59 +00003136 unsigned PtrBits = PTy.getSizeInBits();
Bill Wendlinge1a90422009-12-21 23:10:19 +00003137 if (PtrBits < 64)
Evan Cheng65b52df2009-02-09 21:01:06 +00003138 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
3139 TLI.getPointerTy(),
Owen Anderson825b72b2009-08-11 20:47:22 +00003140 DAG.getConstant(Offs, MVT::i64));
Bill Wendlinge1a90422009-12-21 23:10:19 +00003141 else
Evan Chengb1032a82009-02-09 20:54:38 +00003142 OffsVal = DAG.getIntPtrConstant(Offs);
Bill Wendlinge1a90422009-12-21 23:10:19 +00003143
Dale Johannesen66978ee2009-01-31 02:22:37 +00003144 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Evan Chengb1032a82009-02-09 20:54:38 +00003145 OffsVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003146 continue;
3147 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003148
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003149 // N = N + Idx * ElementSize;
Dan Gohman7abbd042009-10-23 17:57:43 +00003150 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
3151 TD->getTypeAllocSize(Ty));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003152 SDValue IdxN = getValue(Idx);
3153
3154 // If the index is smaller or larger than intptr_t, truncate or extend
3155 // it.
Duncan Sands3a66a682009-10-13 21:04:12 +00003156 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003157
3158 // If this is a multiply by a power of two, turn it into a shl
3159 // immediately. This is a very common case.
3160 if (ElementSize != 1) {
Dan Gohman7abbd042009-10-23 17:57:43 +00003161 if (ElementSize.isPowerOf2()) {
3162 unsigned Amt = ElementSize.logBase2();
Scott Michelfdc40a02009-02-17 22:15:04 +00003163 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003164 N.getValueType(), IdxN,
Nadav Rotem16087692011-12-05 06:29:09 +00003165 DAG.getConstant(Amt, IdxN.getValueType()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003166 } else {
Dan Gohman7abbd042009-10-23 17:57:43 +00003167 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00003168 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003169 N.getValueType(), IdxN, Scale);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003170 }
3171 }
3172
Scott Michelfdc40a02009-02-17 22:15:04 +00003173 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003174 N.getValueType(), N, IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003175 }
3176 }
Bill Wendlinge1a90422009-12-21 23:10:19 +00003177
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003178 setValue(&I, N);
3179}
3180
Dan Gohman46510a72010-04-15 01:51:59 +00003181void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003182 // If this is a fixed sized alloca in the entry block of the function,
3183 // allocate it statically on the stack.
3184 if (FuncInfo.StaticAllocaMap.count(&I))
3185 return; // getValue will auto-populate this.
3186
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003187 Type *Ty = I.getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00003188 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003189 unsigned Align =
3190 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
3191 I.getAlignment());
3192
3193 SDValue AllocSize = getValue(I.getArraySize());
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003194
Owen Andersone50ed302009-08-10 22:56:29 +00003195 EVT IntPtr = TLI.getPointerTy();
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003196 if (AllocSize.getValueType() != IntPtr)
3197 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
3198
3199 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), IntPtr,
3200 AllocSize,
3201 DAG.getConstant(TySize, IntPtr));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003202
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003203 // Handle alignment. If the requested alignment is less than or equal to
3204 // the stack alignment, ignore it. If the size is greater than or equal to
3205 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00003206 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003207 if (Align <= StackAlign)
3208 Align = 0;
3209
3210 // Round the size of the allocation up to the stack alignment size
3211 // by add SA-1 to the size.
Scott Michelfdc40a02009-02-17 22:15:04 +00003212 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003213 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003214 DAG.getIntPtrConstant(StackAlign-1));
Bill Wendling856ff412009-12-22 00:12:37 +00003215
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003216 // Mask out the low bits for alignment purposes.
Scott Michelfdc40a02009-02-17 22:15:04 +00003217 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003218 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003219 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
3220
3221 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Owen Anderson825b72b2009-08-11 20:47:22 +00003222 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
Scott Michelfdc40a02009-02-17 22:15:04 +00003223 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003224 VTs, Ops, 3);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003225 setValue(&I, DSA);
3226 DAG.setRoot(DSA.getValue(1));
Bill Wendling856ff412009-12-22 00:12:37 +00003227
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003228 // Inform the Frame Information that we have just allocated a variable-sized
3229 // object.
Eric Christopher2b8271e2010-07-17 00:28:22 +00003230 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003231}
3232
Dan Gohman46510a72010-04-15 01:51:59 +00003233void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
Eli Friedman327236c2011-08-24 20:50:09 +00003234 if (I.isAtomic())
3235 return visitAtomicLoad(I);
3236
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003237 const Value *SV = I.getOperand(0);
3238 SDValue Ptr = getValue(SV);
3239
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003240 Type *Ty = I.getType();
David Greene1e559442010-02-15 17:00:31 +00003241
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003242 bool isVolatile = I.isVolatile();
David Greene1e559442010-02-15 17:00:31 +00003243 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
Pete Cooperd752e0f2011-11-08 18:42:53 +00003244 bool isInvariant = I.getMetadata("invariant.load") != 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003245 unsigned Alignment = I.getAlignment();
Dan Gohmanf96e4bd2010-10-20 00:31:05 +00003246 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
Rafael Espindola95d594c2012-03-31 18:14:00 +00003247 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003248
Owen Andersone50ed302009-08-10 22:56:29 +00003249 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003250 SmallVector<uint64_t, 4> Offsets;
3251 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
3252 unsigned NumValues = ValueVTs.size();
3253 if (NumValues == 0)
3254 return;
3255
3256 SDValue Root;
3257 bool ConstantMemory = false;
Andrew Trickde91f3c2010-11-12 17:50:46 +00003258 if (I.isVolatile() || NumValues > MaxParallelChains)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003259 // Serialize volatile loads with other side effects.
3260 Root = getRoot();
Dan Gohmanf96e4bd2010-10-20 00:31:05 +00003261 else if (AA->pointsToConstantMemory(
3262 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), TBAAInfo))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003263 // Do not serialize (non-volatile) loads of constant memory with anything.
3264 Root = DAG.getEntryNode();
3265 ConstantMemory = true;
3266 } else {
3267 // Do not serialize non-volatile loads against each other.
3268 Root = DAG.getRoot();
3269 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003270
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003271 SmallVector<SDValue, 4> Values(NumValues);
Andrew Trickde91f3c2010-11-12 17:50:46 +00003272 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3273 NumValues));
Owen Andersone50ed302009-08-10 22:56:29 +00003274 EVT PtrVT = Ptr.getValueType();
Andrew Trickde91f3c2010-11-12 17:50:46 +00003275 unsigned ChainI = 0;
3276 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3277 // Serializing loads here may result in excessive register pressure, and
3278 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3279 // could recover a bit by hoisting nodes upward in the chain by recognizing
3280 // they are side-effect free or do not alias. The optimizer should really
3281 // avoid this case by converting large object/array copies to llvm.memcpy
3282 // (MaxParallelChains should always remain as failsafe).
3283 if (ChainI == MaxParallelChains) {
3284 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3285 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3286 MVT::Other, &Chains[0], ChainI);
3287 Root = Chain;
3288 ChainI = 0;
3289 }
Bill Wendling856ff412009-12-22 00:12:37 +00003290 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
3291 PtrVT, Ptr,
3292 DAG.getConstant(Offsets[i], PtrVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003293 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
Michael J. Spencere70c5262010-10-16 08:25:21 +00003294 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
Rafael Espindola95d594c2012-03-31 18:14:00 +00003295 isNonTemporal, isInvariant, Alignment, TBAAInfo,
3296 Ranges);
Bill Wendling856ff412009-12-22 00:12:37 +00003297
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003298 Values[i] = L;
Andrew Trickde91f3c2010-11-12 17:50:46 +00003299 Chains[ChainI] = L.getValue(1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003300 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003301
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003302 if (!ConstantMemory) {
Scott Michelfdc40a02009-02-17 22:15:04 +00003303 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Andrew Trickde91f3c2010-11-12 17:50:46 +00003304 MVT::Other, &Chains[0], ChainI);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003305 if (isVolatile)
3306 DAG.setRoot(Chain);
3307 else
3308 PendingLoads.push_back(Chain);
3309 }
3310
Bill Wendling4533cac2010-01-28 21:51:40 +00003311 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
3312 DAG.getVTList(&ValueVTs[0], NumValues),
3313 &Values[0], NumValues));
Bill Wendling856ff412009-12-22 00:12:37 +00003314}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003315
Dan Gohman46510a72010-04-15 01:51:59 +00003316void SelectionDAGBuilder::visitStore(const StoreInst &I) {
Eli Friedman327236c2011-08-24 20:50:09 +00003317 if (I.isAtomic())
3318 return visitAtomicStore(I);
3319
Dan Gohman46510a72010-04-15 01:51:59 +00003320 const Value *SrcV = I.getOperand(0);
3321 const Value *PtrV = I.getOperand(1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003322
Owen Andersone50ed302009-08-10 22:56:29 +00003323 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003324 SmallVector<uint64_t, 4> Offsets;
3325 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
3326 unsigned NumValues = ValueVTs.size();
3327 if (NumValues == 0)
3328 return;
3329
3330 // Get the lowered operands. Note that we do this after
3331 // checking if NumResults is zero, because with zero results
3332 // the operands won't have values in the map.
3333 SDValue Src = getValue(SrcV);
3334 SDValue Ptr = getValue(PtrV);
3335
3336 SDValue Root = getRoot();
Andrew Trickde91f3c2010-11-12 17:50:46 +00003337 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3338 NumValues));
Owen Andersone50ed302009-08-10 22:56:29 +00003339 EVT PtrVT = Ptr.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003340 bool isVolatile = I.isVolatile();
David Greene1e559442010-02-15 17:00:31 +00003341 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003342 unsigned Alignment = I.getAlignment();
Dan Gohmanf96e4bd2010-10-20 00:31:05 +00003343 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
Bill Wendling856ff412009-12-22 00:12:37 +00003344
Andrew Trickde91f3c2010-11-12 17:50:46 +00003345 unsigned ChainI = 0;
3346 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3347 // See visitLoad comments.
3348 if (ChainI == MaxParallelChains) {
3349 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3350 MVT::Other, &Chains[0], ChainI);
3351 Root = Chain;
3352 ChainI = 0;
3353 }
Bill Wendling856ff412009-12-22 00:12:37 +00003354 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
3355 DAG.getConstant(Offsets[i], PtrVT));
Andrew Trickde91f3c2010-11-12 17:50:46 +00003356 SDValue St = DAG.getStore(Root, getCurDebugLoc(),
3357 SDValue(Src.getNode(), Src.getResNo() + i),
3358 Add, MachinePointerInfo(PtrV, Offsets[i]),
3359 isVolatile, isNonTemporal, Alignment, TBAAInfo);
3360 Chains[ChainI] = St;
Bill Wendling856ff412009-12-22 00:12:37 +00003361 }
3362
Devang Patel7e13efa2010-10-26 22:14:52 +00003363 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Andrew Trickde91f3c2010-11-12 17:50:46 +00003364 MVT::Other, &Chains[0], ChainI);
Devang Patel7e13efa2010-10-26 22:14:52 +00003365 ++SDNodeOrder;
3366 AssignOrderingToNode(StoreNode.getNode());
3367 DAG.setRoot(StoreNode);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003368}
3369
Eli Friedman26689ac2011-08-03 21:06:02 +00003370static SDValue InsertFenceForAtomic(SDValue Chain, AtomicOrdering Order,
Eli Friedman327236c2011-08-24 20:50:09 +00003371 SynchronizationScope Scope,
Eli Friedman26689ac2011-08-03 21:06:02 +00003372 bool Before, DebugLoc dl,
3373 SelectionDAG &DAG,
3374 const TargetLowering &TLI) {
3375 // Fence, if necessary
3376 if (Before) {
Eli Friedman069e2ed2011-08-26 02:59:24 +00003377 if (Order == AcquireRelease || Order == SequentiallyConsistent)
Eli Friedman26689ac2011-08-03 21:06:02 +00003378 Order = Release;
3379 else if (Order == Acquire || Order == Monotonic)
3380 return Chain;
3381 } else {
3382 if (Order == AcquireRelease)
3383 Order = Acquire;
3384 else if (Order == Release || Order == Monotonic)
3385 return Chain;
3386 }
3387 SDValue Ops[3];
3388 Ops[0] = Chain;
Eli Friedman327236c2011-08-24 20:50:09 +00003389 Ops[1] = DAG.getConstant(Order, TLI.getPointerTy());
3390 Ops[2] = DAG.getConstant(Scope, TLI.getPointerTy());
Eli Friedman26689ac2011-08-03 21:06:02 +00003391 return DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3);
3392}
3393
Eli Friedmanff030482011-07-28 21:48:00 +00003394void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
Eli Friedman26689ac2011-08-03 21:06:02 +00003395 DebugLoc dl = getCurDebugLoc();
3396 AtomicOrdering Order = I.getOrdering();
Eli Friedman327236c2011-08-24 20:50:09 +00003397 SynchronizationScope Scope = I.getSynchScope();
Eli Friedman26689ac2011-08-03 21:06:02 +00003398
3399 SDValue InChain = getRoot();
3400
3401 if (TLI.getInsertFencesForAtomic())
Eli Friedman327236c2011-08-24 20:50:09 +00003402 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3403 DAG, TLI);
Eli Friedman26689ac2011-08-03 21:06:02 +00003404
Eli Friedman55ba8162011-07-29 03:05:32 +00003405 SDValue L =
Eli Friedman26689ac2011-08-03 21:06:02 +00003406 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl,
Eli Friedman55ba8162011-07-29 03:05:32 +00003407 getValue(I.getCompareOperand()).getValueType().getSimpleVT(),
Eli Friedman26689ac2011-08-03 21:06:02 +00003408 InChain,
Eli Friedman55ba8162011-07-29 03:05:32 +00003409 getValue(I.getPointerOperand()),
3410 getValue(I.getCompareOperand()),
3411 getValue(I.getNewValOperand()),
3412 MachinePointerInfo(I.getPointerOperand()), 0 /* Alignment */,
Eli Friedman327236c2011-08-24 20:50:09 +00003413 TLI.getInsertFencesForAtomic() ? Monotonic : Order,
3414 Scope);
Eli Friedman26689ac2011-08-03 21:06:02 +00003415
3416 SDValue OutChain = L.getValue(1);
3417
3418 if (TLI.getInsertFencesForAtomic())
Eli Friedman327236c2011-08-24 20:50:09 +00003419 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3420 DAG, TLI);
Eli Friedman26689ac2011-08-03 21:06:02 +00003421
Eli Friedman55ba8162011-07-29 03:05:32 +00003422 setValue(&I, L);
Eli Friedman26689ac2011-08-03 21:06:02 +00003423 DAG.setRoot(OutChain);
Eli Friedmanff030482011-07-28 21:48:00 +00003424}
3425
3426void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
Eli Friedman26689ac2011-08-03 21:06:02 +00003427 DebugLoc dl = getCurDebugLoc();
Eli Friedman55ba8162011-07-29 03:05:32 +00003428 ISD::NodeType NT;
3429 switch (I.getOperation()) {
David Blaikie4d6ccb52012-01-20 21:51:11 +00003430 default: llvm_unreachable("Unknown atomicrmw operation");
Eli Friedman55ba8162011-07-29 03:05:32 +00003431 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3432 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
3433 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
3434 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
3435 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3436 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
3437 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
3438 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
3439 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
3440 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3441 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3442 }
Eli Friedman26689ac2011-08-03 21:06:02 +00003443 AtomicOrdering Order = I.getOrdering();
Eli Friedman327236c2011-08-24 20:50:09 +00003444 SynchronizationScope Scope = I.getSynchScope();
Eli Friedman26689ac2011-08-03 21:06:02 +00003445
3446 SDValue InChain = getRoot();
3447
3448 if (TLI.getInsertFencesForAtomic())
Eli Friedman327236c2011-08-24 20:50:09 +00003449 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3450 DAG, TLI);
Eli Friedman26689ac2011-08-03 21:06:02 +00003451
Eli Friedman55ba8162011-07-29 03:05:32 +00003452 SDValue L =
Eli Friedman26689ac2011-08-03 21:06:02 +00003453 DAG.getAtomic(NT, dl,
Eli Friedman55ba8162011-07-29 03:05:32 +00003454 getValue(I.getValOperand()).getValueType().getSimpleVT(),
Eli Friedman26689ac2011-08-03 21:06:02 +00003455 InChain,
Eli Friedman55ba8162011-07-29 03:05:32 +00003456 getValue(I.getPointerOperand()),
3457 getValue(I.getValOperand()),
3458 I.getPointerOperand(), 0 /* Alignment */,
Eli Friedman26689ac2011-08-03 21:06:02 +00003459 TLI.getInsertFencesForAtomic() ? Monotonic : Order,
Eli Friedman327236c2011-08-24 20:50:09 +00003460 Scope);
Eli Friedman26689ac2011-08-03 21:06:02 +00003461
3462 SDValue OutChain = L.getValue(1);
3463
3464 if (TLI.getInsertFencesForAtomic())
Eli Friedman327236c2011-08-24 20:50:09 +00003465 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3466 DAG, TLI);
Eli Friedman26689ac2011-08-03 21:06:02 +00003467
Eli Friedman55ba8162011-07-29 03:05:32 +00003468 setValue(&I, L);
Eli Friedman26689ac2011-08-03 21:06:02 +00003469 DAG.setRoot(OutChain);
Eli Friedmanff030482011-07-28 21:48:00 +00003470}
3471
Eli Friedman47f35132011-07-25 23:16:38 +00003472void SelectionDAGBuilder::visitFence(const FenceInst &I) {
Eli Friedman14648462011-07-27 22:21:52 +00003473 DebugLoc dl = getCurDebugLoc();
3474 SDValue Ops[3];
3475 Ops[0] = getRoot();
3476 Ops[1] = DAG.getConstant(I.getOrdering(), TLI.getPointerTy());
3477 Ops[2] = DAG.getConstant(I.getSynchScope(), TLI.getPointerTy());
3478 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3));
Eli Friedman47f35132011-07-25 23:16:38 +00003479}
3480
Eli Friedman327236c2011-08-24 20:50:09 +00003481void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
3482 DebugLoc dl = getCurDebugLoc();
3483 AtomicOrdering Order = I.getOrdering();
3484 SynchronizationScope Scope = I.getSynchScope();
3485
3486 SDValue InChain = getRoot();
3487
Eli Friedmanfd45fa12012-08-17 23:24:29 +00003488 EVT VT = TLI.getValueType(I.getType());
Eli Friedman327236c2011-08-24 20:50:09 +00003489
Eli Friedman596f4472011-09-13 22:19:59 +00003490 if (I.getAlignment() * 8 < VT.getSizeInBits())
Eli Friedmanfe731212011-09-13 20:50:54 +00003491 report_fatal_error("Cannot generate unaligned atomic load");
3492
Eli Friedman327236c2011-08-24 20:50:09 +00003493 SDValue L =
3494 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3495 getValue(I.getPointerOperand()),
3496 I.getPointerOperand(), I.getAlignment(),
3497 TLI.getInsertFencesForAtomic() ? Monotonic : Order,
3498 Scope);
3499
3500 SDValue OutChain = L.getValue(1);
3501
3502 if (TLI.getInsertFencesForAtomic())
3503 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3504 DAG, TLI);
3505
3506 setValue(&I, L);
3507 DAG.setRoot(OutChain);
3508}
3509
3510void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
3511 DebugLoc dl = getCurDebugLoc();
3512
3513 AtomicOrdering Order = I.getOrdering();
3514 SynchronizationScope Scope = I.getSynchScope();
3515
3516 SDValue InChain = getRoot();
3517
Eli Friedmanfd45fa12012-08-17 23:24:29 +00003518 EVT VT = TLI.getValueType(I.getValueOperand()->getType());
Eli Friedmanfe731212011-09-13 20:50:54 +00003519
Eli Friedman596f4472011-09-13 22:19:59 +00003520 if (I.getAlignment() * 8 < VT.getSizeInBits())
Eli Friedmanfe731212011-09-13 20:50:54 +00003521 report_fatal_error("Cannot generate unaligned atomic store");
3522
Eli Friedman327236c2011-08-24 20:50:09 +00003523 if (TLI.getInsertFencesForAtomic())
3524 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3525 DAG, TLI);
3526
3527 SDValue OutChain =
Eli Friedmanfe731212011-09-13 20:50:54 +00003528 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
Eli Friedman327236c2011-08-24 20:50:09 +00003529 InChain,
3530 getValue(I.getPointerOperand()),
3531 getValue(I.getValueOperand()),
3532 I.getPointerOperand(), I.getAlignment(),
3533 TLI.getInsertFencesForAtomic() ? Monotonic : Order,
3534 Scope);
3535
3536 if (TLI.getInsertFencesForAtomic())
3537 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3538 DAG, TLI);
3539
3540 DAG.setRoot(OutChain);
3541}
3542
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003543/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3544/// node.
Dan Gohman46510a72010-04-15 01:51:59 +00003545void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
Dan Gohman2048b852009-11-23 18:04:58 +00003546 unsigned Intrinsic) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003547 bool HasChain = !I.doesNotAccessMemory();
3548 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3549
3550 // Build the operand list.
3551 SmallVector<SDValue, 8> Ops;
3552 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3553 if (OnlyLoad) {
3554 // We don't need to serialize loads against other loads.
3555 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003556 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003557 Ops.push_back(getRoot());
3558 }
3559 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00003560
3561 // Info is set by getTgtMemInstrinsic
3562 TargetLowering::IntrinsicInfo Info;
3563 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3564
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003565 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Bob Wilson65ffec42010-09-21 17:56:22 +00003566 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3567 Info.opc == ISD::INTRINSIC_W_CHAIN)
Pete Cooperbf421392012-01-16 04:08:12 +00003568 Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003569
3570 // Add all operands of the call to the operand list.
Gabor Greif0635f352010-06-25 09:38:13 +00003571 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3572 SDValue Op = getValue(I.getArgOperand(i));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003573 Ops.push_back(Op);
3574 }
3575
Owen Andersone50ed302009-08-10 22:56:29 +00003576 SmallVector<EVT, 4> ValueVTs;
Bob Wilson8d919552009-07-31 22:41:21 +00003577 ComputeValueVTs(TLI, I.getType(), ValueVTs);
Bill Wendling856ff412009-12-22 00:12:37 +00003578
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003579 if (HasChain)
Owen Anderson825b72b2009-08-11 20:47:22 +00003580 ValueVTs.push_back(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003581
Bob Wilson8d919552009-07-31 22:41:21 +00003582 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003583
3584 // Create the node.
3585 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00003586 if (IsTgtIntrinsic) {
3587 // This is target intrinsic that touches memory
Dale Johannesen66978ee2009-01-31 02:22:37 +00003588 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003589 VTs, &Ops[0], Ops.size(),
Chris Lattnere9ba5dd2010-09-21 04:57:15 +00003590 Info.memVT,
3591 MachinePointerInfo(Info.ptrVal, Info.offset),
Mon P Wang3efcd4a2008-11-01 20:24:53 +00003592 Info.align, Info.vol,
3593 Info.readMem, Info.writeMem);
Bill Wendling856ff412009-12-22 00:12:37 +00003594 } else if (!HasChain) {
Scott Michelfdc40a02009-02-17 22:15:04 +00003595 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003596 VTs, &Ops[0], Ops.size());
Benjamin Kramerf0127052010-01-05 13:12:22 +00003597 } else if (!I.getType()->isVoidTy()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00003598 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003599 VTs, &Ops[0], Ops.size());
Bill Wendling856ff412009-12-22 00:12:37 +00003600 } else {
Scott Michelfdc40a02009-02-17 22:15:04 +00003601 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003602 VTs, &Ops[0], Ops.size());
Bill Wendling856ff412009-12-22 00:12:37 +00003603 }
3604
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003605 if (HasChain) {
3606 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3607 if (OnlyLoad)
3608 PendingLoads.push_back(Chain);
3609 else
3610 DAG.setRoot(Chain);
3611 }
Bill Wendling856ff412009-12-22 00:12:37 +00003612
Benjamin Kramerf0127052010-01-05 13:12:22 +00003613 if (!I.getType()->isVoidTy()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003614 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Owen Andersone50ed302009-08-10 22:56:29 +00003615 EVT VT = TLI.getValueType(PTy);
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003616 Result = DAG.getNode(ISD::BITCAST, getCurDebugLoc(), VT, Result);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003617 }
Bill Wendling856ff412009-12-22 00:12:37 +00003618
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003619 setValue(&I, Result);
Evan Cheng5aef7952012-03-22 19:29:09 +00003620 } else {
3621 // Assign order to result here. If the intrinsic does not produce a result,
3622 // it won't be mapped to a SDNode and visit() will not assign it an order
3623 // number.
3624 ++SDNodeOrder;
3625 AssignOrderingToNode(Result.getNode());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003626 }
3627}
3628
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003629/// GetSignificand - Get the significand and build it into a floating-point
3630/// number with exponent of 1:
3631///
3632/// Op = (Op & 0x007fffff) | 0x3f800000;
3633///
3634/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003635static SDValue
Bill Wendling46ada192010-03-02 01:55:18 +00003636GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
Owen Anderson825b72b2009-08-11 20:47:22 +00003637 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3638 DAG.getConstant(0x007fffff, MVT::i32));
3639 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3640 DAG.getConstant(0x3f800000, MVT::i32));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003641 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003642}
3643
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003644/// GetExponent - Get the exponent:
3645///
Bill Wendlinge9a72862009-01-20 21:17:57 +00003646/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003647///
3648/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003649static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003650GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
Bill Wendling46ada192010-03-02 01:55:18 +00003651 DebugLoc dl) {
Owen Anderson825b72b2009-08-11 20:47:22 +00003652 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3653 DAG.getConstant(0x7f800000, MVT::i32));
3654 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands92abc622009-01-31 15:50:11 +00003655 DAG.getConstant(23, TLI.getPointerTy()));
Owen Anderson825b72b2009-08-11 20:47:22 +00003656 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3657 DAG.getConstant(127, MVT::i32));
Bill Wendling4533cac2010-01-28 21:51:40 +00003658 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003659}
3660
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003661/// getF32Constant - Get 32-bit floating point constant.
3662static SDValue
3663getF32Constant(SelectionDAG &DAG, unsigned Flt) {
Owen Anderson825b72b2009-08-11 20:47:22 +00003664 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003665}
3666
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003667/// visitExp - Lower an exp intrinsic. Handles the special sequences for
3668/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003669void
Dan Gohman46510a72010-04-15 01:51:59 +00003670SelectionDAGBuilder::visitExp(const CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00003671 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003672 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003673
Gabor Greif0635f352010-06-25 09:38:13 +00003674 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003675 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Gabor Greif0635f352010-06-25 09:38:13 +00003676 SDValue Op = getValue(I.getArgOperand(0));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003677
3678 // Put the exponent in the right bit position for later addition to the
3679 // final result:
3680 //
3681 // #define LOG2OFe 1.4426950f
3682 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Owen Anderson825b72b2009-08-11 20:47:22 +00003683 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003684 getF32Constant(DAG, 0x3fb8aa3b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003685 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003686
3687 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003688 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3689 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003690
3691 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003692 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003693 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendling856ff412009-12-22 00:12:37 +00003694
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003695 if (LimitFloatPrecision <= 6) {
3696 // For floating-point precision of 6:
3697 //
3698 // TwoToFractionalPartOfX =
3699 // 0.997535578f +
3700 // (0.735607626f + 0.252464424f * x) * x;
3701 //
3702 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003703 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003704 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00003705 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003706 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003707 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3708 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003709 getF32Constant(DAG, 0x3f7f5e7e));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003710 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t5);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003711
3712 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003713 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003714 TwoToFracPartOfX, IntegerPartOfX);
3715
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003716 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t6);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003717 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3718 // For floating-point precision of 12:
3719 //
3720 // TwoToFractionalPartOfX =
3721 // 0.999892986f +
3722 // (0.696457318f +
3723 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3724 //
3725 // 0.000107046256 error, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003726 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003727 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003728 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003729 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003730 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3731 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003732 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003733 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3734 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003735 getF32Constant(DAG, 0x3f7ff8fd));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003736 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t7);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003737
3738 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003739 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003740 TwoToFracPartOfX, IntegerPartOfX);
3741
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003742 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t8);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003743 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3744 // For floating-point precision of 18:
3745 //
3746 // TwoToFractionalPartOfX =
3747 // 0.999999982f +
3748 // (0.693148872f +
3749 // (0.240227044f +
3750 // (0.554906021e-1f +
3751 // (0.961591928e-2f +
3752 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3753 //
3754 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003755 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003756 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003757 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003758 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003759 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3760 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003761 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003762 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3763 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003764 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003765 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3766 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003767 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003768 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3769 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003770 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003771 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3772 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003773 getF32Constant(DAG, 0x3f800000));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003774 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003775 MVT::i32, t13);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003776
3777 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003778 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003779 TwoToFracPartOfX, IntegerPartOfX);
3780
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003781 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t14);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003782 }
3783 } else {
3784 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003785 result = DAG.getNode(ISD::FEXP, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00003786 getValue(I.getArgOperand(0)).getValueType(),
3787 getValue(I.getArgOperand(0)));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003788 }
3789
Dale Johannesen59e577f2008-09-05 18:38:42 +00003790 setValue(&I, result);
3791}
3792
Bill Wendling39150252008-09-09 20:39:27 +00003793/// visitLog - Lower a log intrinsic. Handles the special sequences for
3794/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003795void
Dan Gohman46510a72010-04-15 01:51:59 +00003796SelectionDAGBuilder::visitLog(const CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00003797 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003798 DebugLoc dl = getCurDebugLoc();
Bill Wendling39150252008-09-09 20:39:27 +00003799
Gabor Greif0635f352010-06-25 09:38:13 +00003800 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
Bill Wendling39150252008-09-09 20:39:27 +00003801 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Gabor Greif0635f352010-06-25 09:38:13 +00003802 SDValue Op = getValue(I.getArgOperand(0));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003803 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendling39150252008-09-09 20:39:27 +00003804
3805 // Scale the exponent by log(2) [0.69314718f].
Bill Wendling46ada192010-03-02 01:55:18 +00003806 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson825b72b2009-08-11 20:47:22 +00003807 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003808 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003809
3810 // Get the significand and build it into a floating-point number with
3811 // exponent of 1.
Bill Wendling46ada192010-03-02 01:55:18 +00003812 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling39150252008-09-09 20:39:27 +00003813
3814 if (LimitFloatPrecision <= 6) {
3815 // For floating-point precision of 6:
3816 //
3817 // LogofMantissa =
3818 // -1.1609546f +
3819 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003820 //
Bill Wendling39150252008-09-09 20:39:27 +00003821 // error 0.0034276066, which is better than 8 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003822 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003823 getF32Constant(DAG, 0xbe74c456));
Owen Anderson825b72b2009-08-11 20:47:22 +00003824 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003825 getF32Constant(DAG, 0x3fb3a2b1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003826 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3827 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003828 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003829
Scott Michelfdc40a02009-02-17 22:15:04 +00003830 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003831 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003832 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3833 // For floating-point precision of 12:
3834 //
3835 // LogOfMantissa =
3836 // -1.7417939f +
3837 // (2.8212026f +
3838 // (-1.4699568f +
3839 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3840 //
3841 // error 0.000061011436, which is 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003842 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003843 getF32Constant(DAG, 0xbd67b6d6));
Owen Anderson825b72b2009-08-11 20:47:22 +00003844 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003845 getF32Constant(DAG, 0x3ee4f4b8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003846 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3847 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003848 getF32Constant(DAG, 0x3fbc278b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003849 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3850 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003851 getF32Constant(DAG, 0x40348e95));
Owen Anderson825b72b2009-08-11 20:47:22 +00003852 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3853 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003854 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003855
Scott Michelfdc40a02009-02-17 22:15:04 +00003856 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003857 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003858 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3859 // For floating-point precision of 18:
3860 //
3861 // LogOfMantissa =
3862 // -2.1072184f +
3863 // (4.2372794f +
3864 // (-3.7029485f +
3865 // (2.2781945f +
3866 // (-0.87823314f +
3867 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3868 //
3869 // error 0.0000023660568, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003870 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003871 getF32Constant(DAG, 0xbc91e5ac));
Owen Anderson825b72b2009-08-11 20:47:22 +00003872 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003873 getF32Constant(DAG, 0x3e4350aa));
Owen Anderson825b72b2009-08-11 20:47:22 +00003874 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3875 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003876 getF32Constant(DAG, 0x3f60d3e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003877 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3878 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003879 getF32Constant(DAG, 0x4011cdf0));
Owen Anderson825b72b2009-08-11 20:47:22 +00003880 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3881 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003882 getF32Constant(DAG, 0x406cfd1c));
Owen Anderson825b72b2009-08-11 20:47:22 +00003883 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3884 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003885 getF32Constant(DAG, 0x408797cb));
Owen Anderson825b72b2009-08-11 20:47:22 +00003886 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3887 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003888 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003889
Scott Michelfdc40a02009-02-17 22:15:04 +00003890 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003891 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003892 }
3893 } else {
3894 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003895 result = DAG.getNode(ISD::FLOG, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00003896 getValue(I.getArgOperand(0)).getValueType(),
3897 getValue(I.getArgOperand(0)));
Bill Wendling39150252008-09-09 20:39:27 +00003898 }
3899
Dale Johannesen59e577f2008-09-05 18:38:42 +00003900 setValue(&I, result);
3901}
3902
Bill Wendling3eb59402008-09-09 00:28:24 +00003903/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3904/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003905void
Dan Gohman46510a72010-04-15 01:51:59 +00003906SelectionDAGBuilder::visitLog2(const CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00003907 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003908 DebugLoc dl = getCurDebugLoc();
Bill Wendling3eb59402008-09-09 00:28:24 +00003909
Gabor Greif0635f352010-06-25 09:38:13 +00003910 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003911 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Gabor Greif0635f352010-06-25 09:38:13 +00003912 SDValue Op = getValue(I.getArgOperand(0));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003913 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003914
Bill Wendling39150252008-09-09 20:39:27 +00003915 // Get the exponent.
Bill Wendling46ada192010-03-02 01:55:18 +00003916 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
Bill Wendling856ff412009-12-22 00:12:37 +00003917
Bill Wendling3eb59402008-09-09 00:28:24 +00003918 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003919 // exponent of 1.
Bill Wendling46ada192010-03-02 01:55:18 +00003920 SDValue X = GetSignificand(DAG, Op1, dl);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003921
Bill Wendling3eb59402008-09-09 00:28:24 +00003922 // Different possible minimax approximations of significand in
3923 // floating-point for various degrees of accuracy over [1,2].
3924 if (LimitFloatPrecision <= 6) {
3925 // For floating-point precision of 6:
3926 //
3927 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3928 //
3929 // error 0.0049451742, which is more than 7 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003930 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003931 getF32Constant(DAG, 0xbeb08fe0));
Owen Anderson825b72b2009-08-11 20:47:22 +00003932 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003933 getF32Constant(DAG, 0x40019463));
Owen Anderson825b72b2009-08-11 20:47:22 +00003934 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3935 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003936 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003937
Scott Michelfdc40a02009-02-17 22:15:04 +00003938 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003939 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003940 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3941 // For floating-point precision of 12:
3942 //
3943 // Log2ofMantissa =
3944 // -2.51285454f +
3945 // (4.07009056f +
3946 // (-2.12067489f +
3947 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003948 //
Bill Wendling3eb59402008-09-09 00:28:24 +00003949 // error 0.0000876136000, which is better than 13 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003950 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003951 getF32Constant(DAG, 0xbda7262e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003952 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003953 getF32Constant(DAG, 0x3f25280b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003954 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3955 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003956 getF32Constant(DAG, 0x4007b923));
Owen Anderson825b72b2009-08-11 20:47:22 +00003957 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3958 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003959 getF32Constant(DAG, 0x40823e2f));
Owen Anderson825b72b2009-08-11 20:47:22 +00003960 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3961 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003962 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003963
Scott Michelfdc40a02009-02-17 22:15:04 +00003964 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003965 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003966 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3967 // For floating-point precision of 18:
3968 //
3969 // Log2ofMantissa =
3970 // -3.0400495f +
3971 // (6.1129976f +
3972 // (-5.3420409f +
3973 // (3.2865683f +
3974 // (-1.2669343f +
3975 // (0.27515199f -
3976 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3977 //
3978 // error 0.0000018516, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003979 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003980 getF32Constant(DAG, 0xbcd2769e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003981 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003982 getF32Constant(DAG, 0x3e8ce0b9));
Owen Anderson825b72b2009-08-11 20:47:22 +00003983 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3984 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003985 getF32Constant(DAG, 0x3fa22ae7));
Owen Anderson825b72b2009-08-11 20:47:22 +00003986 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3987 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003988 getF32Constant(DAG, 0x40525723));
Owen Anderson825b72b2009-08-11 20:47:22 +00003989 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3990 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003991 getF32Constant(DAG, 0x40aaf200));
Owen Anderson825b72b2009-08-11 20:47:22 +00003992 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3993 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003994 getF32Constant(DAG, 0x40c39dad));
Owen Anderson825b72b2009-08-11 20:47:22 +00003995 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3996 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003997 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003998
Scott Michelfdc40a02009-02-17 22:15:04 +00003999 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004000 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00004001 }
Dale Johannesen853244f2008-09-05 23:49:37 +00004002 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00004003 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004004 result = DAG.getNode(ISD::FLOG2, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00004005 getValue(I.getArgOperand(0)).getValueType(),
4006 getValue(I.getArgOperand(0)));
Dale Johannesen853244f2008-09-05 23:49:37 +00004007 }
Bill Wendling3eb59402008-09-09 00:28:24 +00004008
Dale Johannesen59e577f2008-09-05 18:38:42 +00004009 setValue(&I, result);
4010}
4011
Bill Wendling3eb59402008-09-09 00:28:24 +00004012/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
4013/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00004014void
Dan Gohman46510a72010-04-15 01:51:59 +00004015SelectionDAGBuilder::visitLog10(const CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00004016 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00004017 DebugLoc dl = getCurDebugLoc();
Bill Wendling181b6272008-10-19 20:34:04 +00004018
Gabor Greif0635f352010-06-25 09:38:13 +00004019 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00004020 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Gabor Greif0635f352010-06-25 09:38:13 +00004021 SDValue Op = getValue(I.getArgOperand(0));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004022 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00004023
Bill Wendling39150252008-09-09 20:39:27 +00004024 // Scale the exponent by log10(2) [0.30102999f].
Bill Wendling46ada192010-03-02 01:55:18 +00004025 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson825b72b2009-08-11 20:47:22 +00004026 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004027 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00004028
4029 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00004030 // exponent of 1.
Bill Wendling46ada192010-03-02 01:55:18 +00004031 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00004032
4033 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00004034 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004035 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00004036 // Log10ofMantissa =
4037 // -0.50419619f +
4038 // (0.60948995f - 0.10380950f * x) * x;
4039 //
4040 // error 0.0014886165, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004041 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004042 getF32Constant(DAG, 0xbdd49a13));
Owen Anderson825b72b2009-08-11 20:47:22 +00004043 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004044 getF32Constant(DAG, 0x3f1c0789));
Owen Anderson825b72b2009-08-11 20:47:22 +00004045 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4046 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004047 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00004048
Scott Michelfdc40a02009-02-17 22:15:04 +00004049 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004050 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00004051 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
4052 // For floating-point precision of 12:
4053 //
4054 // Log10ofMantissa =
4055 // -0.64831180f +
4056 // (0.91751397f +
4057 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4058 //
4059 // error 0.00019228036, which is better than 12 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004060 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004061 getF32Constant(DAG, 0x3d431f31));
Owen Anderson825b72b2009-08-11 20:47:22 +00004062 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004063 getF32Constant(DAG, 0x3ea21fb2));
Owen Anderson825b72b2009-08-11 20:47:22 +00004064 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4065 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004066 getF32Constant(DAG, 0x3f6ae232));
Owen Anderson825b72b2009-08-11 20:47:22 +00004067 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4068 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004069 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00004070
Scott Michelfdc40a02009-02-17 22:15:04 +00004071 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004072 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00004073 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00004074 // For floating-point precision of 18:
4075 //
4076 // Log10ofMantissa =
4077 // -0.84299375f +
4078 // (1.5327582f +
4079 // (-1.0688956f +
4080 // (0.49102474f +
4081 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4082 //
4083 // error 0.0000037995730, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004084 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004085 getF32Constant(DAG, 0x3c5d51ce));
Owen Anderson825b72b2009-08-11 20:47:22 +00004086 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004087 getF32Constant(DAG, 0x3e00685a));
Owen Anderson825b72b2009-08-11 20:47:22 +00004088 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4089 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004090 getF32Constant(DAG, 0x3efb6798));
Owen Anderson825b72b2009-08-11 20:47:22 +00004091 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4092 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004093 getF32Constant(DAG, 0x3f88d192));
Owen Anderson825b72b2009-08-11 20:47:22 +00004094 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4095 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004096 getF32Constant(DAG, 0x3fc4316c));
Owen Anderson825b72b2009-08-11 20:47:22 +00004097 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4098 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004099 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00004100
Scott Michelfdc40a02009-02-17 22:15:04 +00004101 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004102 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00004103 }
Dale Johannesen852680a2008-09-05 21:27:19 +00004104 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00004105 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004106 result = DAG.getNode(ISD::FLOG10, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00004107 getValue(I.getArgOperand(0)).getValueType(),
4108 getValue(I.getArgOperand(0)));
Dale Johannesen852680a2008-09-05 21:27:19 +00004109 }
Bill Wendling3eb59402008-09-09 00:28:24 +00004110
Dale Johannesen59e577f2008-09-05 18:38:42 +00004111 setValue(&I, result);
4112}
4113
Bill Wendlinge10c8142008-09-09 22:39:21 +00004114/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4115/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00004116void
Dan Gohman46510a72010-04-15 01:51:59 +00004117SelectionDAGBuilder::visitExp2(const CallInst &I) {
Dale Johannesen601d3c02008-09-05 01:48:15 +00004118 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00004119 DebugLoc dl = getCurDebugLoc();
Bill Wendlinge10c8142008-09-09 22:39:21 +00004120
Gabor Greif0635f352010-06-25 09:38:13 +00004121 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00004122 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Gabor Greif0635f352010-06-25 09:38:13 +00004123 SDValue Op = getValue(I.getArgOperand(0));
Bill Wendlinge10c8142008-09-09 22:39:21 +00004124
Owen Anderson825b72b2009-08-11 20:47:22 +00004125 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004126
4127 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00004128 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4129 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004130
4131 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00004132 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00004133 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00004134
4135 if (LimitFloatPrecision <= 6) {
4136 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004137 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00004138 // TwoToFractionalPartOfX =
4139 // 0.997535578f +
4140 // (0.735607626f + 0.252464424f * x) * x;
4141 //
4142 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004143 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004144 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00004145 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004146 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00004147 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4148 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004149 getF32Constant(DAG, 0x3f7f5e7e));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004150 SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004151 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00004152 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004153
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004154 result = DAG.getNode(ISD::BITCAST, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004155 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004156 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
4157 // For floating-point precision of 12:
4158 //
4159 // TwoToFractionalPartOfX =
4160 // 0.999892986f +
4161 // (0.696457318f +
4162 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4163 //
4164 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004165 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004166 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00004167 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004168 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00004169 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4170 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004171 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00004172 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4173 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004174 getF32Constant(DAG, 0x3f7ff8fd));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004175 SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004176 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00004177 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004178
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004179 result = DAG.getNode(ISD::BITCAST, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004180 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004181 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
4182 // For floating-point precision of 18:
4183 //
4184 // TwoToFractionalPartOfX =
4185 // 0.999999982f +
4186 // (0.693148872f +
4187 // (0.240227044f +
4188 // (0.554906021e-1f +
4189 // (0.961591928e-2f +
4190 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4191 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004192 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004193 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00004194 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004195 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00004196 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4197 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004198 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00004199 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4200 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004201 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00004202 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4203 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004204 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00004205 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4206 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004207 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00004208 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4209 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004210 getF32Constant(DAG, 0x3f800000));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004211 SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004212 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00004213 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004214
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004215 result = DAG.getNode(ISD::BITCAST, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004216 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004217 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00004218 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00004219 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004220 result = DAG.getNode(ISD::FEXP2, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00004221 getValue(I.getArgOperand(0)).getValueType(),
4222 getValue(I.getArgOperand(0)));
Dale Johannesen601d3c02008-09-05 01:48:15 +00004223 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00004224
Dale Johannesen601d3c02008-09-05 01:48:15 +00004225 setValue(&I, result);
4226}
4227
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004228/// visitPow - Lower a pow intrinsic. Handles the special sequences for
4229/// limited-precision mode with x == 10.0f.
4230void
Dan Gohman46510a72010-04-15 01:51:59 +00004231SelectionDAGBuilder::visitPow(const CallInst &I) {
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004232 SDValue result;
Gabor Greif0635f352010-06-25 09:38:13 +00004233 const Value *Val = I.getArgOperand(0);
Dale Johannesen66978ee2009-01-31 02:22:37 +00004234 DebugLoc dl = getCurDebugLoc();
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004235 bool IsExp10 = false;
4236
Owen Anderson825b72b2009-08-11 20:47:22 +00004237 if (getValue(Val).getValueType() == MVT::f32 &&
Gabor Greif0635f352010-06-25 09:38:13 +00004238 getValue(I.getArgOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004239 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4240 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
4241 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
4242 APFloat Ten(10.0f);
4243 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
4244 }
4245 }
4246 }
4247
4248 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Gabor Greif0635f352010-06-25 09:38:13 +00004249 SDValue Op = getValue(I.getArgOperand(1));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004250
4251 // Put the exponent in the right bit position for later addition to the
4252 // final result:
4253 //
4254 // #define LOG2OF10 3.3219281f
4255 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Owen Anderson825b72b2009-08-11 20:47:22 +00004256 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004257 getF32Constant(DAG, 0x40549a78));
Owen Anderson825b72b2009-08-11 20:47:22 +00004258 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004259
4260 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00004261 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4262 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004263
4264 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00004265 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00004266 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004267
4268 if (LimitFloatPrecision <= 6) {
4269 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004270 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004271 // twoToFractionalPartOfX =
4272 // 0.997535578f +
4273 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004274 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004275 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004276 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004277 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00004278 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004279 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00004280 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4281 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004282 getF32Constant(DAG, 0x3f7f5e7e));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004283 SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004284 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00004285 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004286
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004287 result = DAG.getNode(ISD::BITCAST, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004288 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004289 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
4290 // For floating-point precision of 12:
4291 //
4292 // TwoToFractionalPartOfX =
4293 // 0.999892986f +
4294 // (0.696457318f +
4295 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4296 //
4297 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004298 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004299 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00004300 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004301 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00004302 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4303 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004304 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00004305 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4306 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004307 getF32Constant(DAG, 0x3f7ff8fd));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004308 SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004309 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00004310 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004311
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004312 result = DAG.getNode(ISD::BITCAST, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004313 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004314 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
4315 // For floating-point precision of 18:
4316 //
4317 // TwoToFractionalPartOfX =
4318 // 0.999999982f +
4319 // (0.693148872f +
4320 // (0.240227044f +
4321 // (0.554906021e-1f +
4322 // (0.961591928e-2f +
4323 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4324 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004325 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004326 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00004327 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004328 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00004329 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4330 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004331 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00004332 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4333 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004334 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00004335 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4336 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004337 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00004338 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4339 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004340 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00004341 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4342 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004343 getF32Constant(DAG, 0x3f800000));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004344 SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004345 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00004346 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004347
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004348 result = DAG.getNode(ISD::BITCAST, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004349 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004350 }
4351 } else {
4352 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004353 result = DAG.getNode(ISD::FPOW, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00004354 getValue(I.getArgOperand(0)).getValueType(),
4355 getValue(I.getArgOperand(0)),
4356 getValue(I.getArgOperand(1)));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004357 }
4358
4359 setValue(&I, result);
4360}
4361
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004362
4363/// ExpandPowI - Expand a llvm.powi intrinsic.
4364static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
4365 SelectionDAG &DAG) {
4366 // If RHS is a constant, we can expand this out to a multiplication tree,
4367 // otherwise we end up lowering to a call to __powidf2 (for example). When
4368 // optimizing for size, we only want to do this if the expansion would produce
4369 // a small number of multiplies, otherwise we do the full expansion.
4370 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4371 // Get the exponent as a positive value.
4372 unsigned Val = RHSC->getSExtValue();
4373 if ((int)Val < 0) Val = -Val;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004374
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004375 // powi(x, 0) -> 1.0
4376 if (Val == 0)
4377 return DAG.getConstantFP(1.0, LHS.getValueType());
4378
Dan Gohmanae541aa2010-04-15 04:33:49 +00004379 const Function *F = DAG.getMachineFunction().getFunction();
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004380 if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
4381 // If optimizing for size, don't insert too many multiplies. This
4382 // inserts up to 5 multiplies.
4383 CountPopulation_32(Val)+Log2_32(Val) < 7) {
4384 // We use the simple binary decomposition method to generate the multiply
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004385 // sequence. There are more optimal ways to do this (for example,
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004386 // powi(x,15) generates one more multiply than it should), but this has
4387 // the benefit of being both really simple and much better than a libcall.
4388 SDValue Res; // Logically starts equal to 1.0
4389 SDValue CurSquare = LHS;
4390 while (Val) {
Mikhail Glushenkovbfdfea82010-01-01 04:41:36 +00004391 if (Val & 1) {
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004392 if (Res.getNode())
4393 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4394 else
4395 Res = CurSquare; // 1.0*CurSquare.
Mikhail Glushenkovbfdfea82010-01-01 04:41:36 +00004396 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004397
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004398 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4399 CurSquare, CurSquare);
4400 Val >>= 1;
4401 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004402
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004403 // If the original was negative, invert the result, producing 1/(x*x*x).
4404 if (RHSC->getSExtValue() < 0)
4405 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4406 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4407 return Res;
4408 }
4409 }
4410
4411 // Otherwise, expand to a libcall.
4412 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4413}
4414
Devang Patel227dfdb2011-05-16 21:24:05 +00004415// getTruncatedArgReg - Find underlying register used for an truncated
4416// argument.
4417static unsigned getTruncatedArgReg(const SDValue &N) {
4418 if (N.getOpcode() != ISD::TRUNCATE)
4419 return 0;
4420
4421 const SDValue &Ext = N.getOperand(0);
4422 if (Ext.getOpcode() == ISD::AssertZext || Ext.getOpcode() == ISD::AssertSext){
4423 const SDValue &CFR = Ext.getOperand(0);
4424 if (CFR.getOpcode() == ISD::CopyFromReg)
4425 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
Craig Topper7eb46d82012-04-11 04:55:51 +00004426 if (CFR.getOpcode() == ISD::TRUNCATE)
4427 return getTruncatedArgReg(CFR);
Devang Patel227dfdb2011-05-16 21:24:05 +00004428 }
4429 return 0;
4430}
4431
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004432/// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4433/// argument, create the corresponding DBG_VALUE machine instruction for it now.
4434/// At the end of instruction selection, they will be inserted to the entry BB.
Evan Cheng9e8a2b92010-04-29 01:40:30 +00004435bool
Devang Patel78a06e52010-08-25 20:39:26 +00004436SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
Michael J. Spencere70c5262010-10-16 08:25:21 +00004437 int64_t Offset,
Dan Gohman5d11ea32010-05-01 00:33:16 +00004438 const SDValue &N) {
Devang Patel0b48ead2010-08-31 22:22:42 +00004439 const Argument *Arg = dyn_cast<Argument>(V);
4440 if (!Arg)
Evan Cheng9e8a2b92010-04-29 01:40:30 +00004441 return false;
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004442
Devang Patel719f6a92010-04-29 20:40:36 +00004443 MachineFunction &MF = DAG.getMachineFunction();
Devang Patela90b3052010-11-02 17:01:30 +00004444 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo();
4445 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4446
Devang Patela83ce982010-04-29 18:50:36 +00004447 // Ignore inlined function arguments here.
4448 DIVariable DV(Variable);
Devang Patel719f6a92010-04-29 20:40:36 +00004449 if (DV.isInlinedFnArgument(MF.getFunction()))
Devang Patela83ce982010-04-29 18:50:36 +00004450 return false;
4451
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004452 unsigned Reg = 0;
Devang Patel9aee3352011-09-08 22:59:09 +00004453 // Some arguments' frame index is recorded during argument lowering.
4454 Offset = FuncInfo.getArgumentFrameIndex(Arg);
4455 if (Offset)
Craig Topper7eb46d82012-04-11 04:55:51 +00004456 Reg = TRI->getFrameRegister(MF);
Devang Patel0b48ead2010-08-31 22:22:42 +00004457
Devang Patel9aee3352011-09-08 22:59:09 +00004458 if (!Reg && N.getNode()) {
Devang Patel227dfdb2011-05-16 21:24:05 +00004459 if (N.getOpcode() == ISD::CopyFromReg)
4460 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4461 else
4462 Reg = getTruncatedArgReg(N);
4463 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004464 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4465 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4466 if (PR)
4467 Reg = PR;
4468 }
4469 }
4470
Evan Chenga36acad2010-04-29 06:33:38 +00004471 if (!Reg) {
Devang Patela90b3052010-11-02 17:01:30 +00004472 // Check if ValueMap has reg number.
Evan Chenga36acad2010-04-29 06:33:38 +00004473 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
Devang Patel8bc9ef72010-11-02 17:19:03 +00004474 if (VMI != FuncInfo.ValueMap.end())
4475 Reg = VMI->second;
Evan Chenga36acad2010-04-29 06:33:38 +00004476 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004477
Devang Patel8bc9ef72010-11-02 17:19:03 +00004478 if (!Reg && N.getNode()) {
Devang Patela90b3052010-11-02 17:01:30 +00004479 // Check if frame index is available.
4480 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004481 if (FrameIndexSDNode *FINode =
Devang Patela90b3052010-11-02 17:01:30 +00004482 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) {
4483 Reg = TRI->getFrameRegister(MF);
4484 Offset = FINode->getIndex();
4485 }
Devang Patel8bc9ef72010-11-02 17:19:03 +00004486 }
4487
4488 if (!Reg)
4489 return false;
Devang Patela90b3052010-11-02 17:01:30 +00004490
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004491 MachineInstrBuilder MIB = BuildMI(MF, getCurDebugLoc(),
4492 TII->get(TargetOpcode::DBG_VALUE))
Evan Chenga36acad2010-04-29 06:33:38 +00004493 .addReg(Reg, RegState::Debug).addImm(Offset).addMetadata(Variable);
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004494 FuncInfo.ArgDbgValues.push_back(&*MIB);
Evan Cheng9e8a2b92010-04-29 01:40:30 +00004495 return true;
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004496}
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004497
Douglas Gregor7d9663c2010-05-11 06:17:44 +00004498// VisualStudio defines setjmp as _setjmp
Michael J. Spencer1f409602010-09-24 19:48:47 +00004499#if defined(_MSC_VER) && defined(setjmp) && \
4500 !defined(setjmp_undefined_for_msvc)
4501# pragma push_macro("setjmp")
4502# undef setjmp
4503# define setjmp_undefined_for_msvc
Douglas Gregor7d9663c2010-05-11 06:17:44 +00004504#endif
4505
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004506/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4507/// we want to emit this as a call to a named external function, return the name
4508/// otherwise lower it and return null.
4509const char *
Dan Gohman46510a72010-04-15 01:51:59 +00004510SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004511 DebugLoc dl = getCurDebugLoc();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004512 SDValue Res;
4513
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004514 switch (Intrinsic) {
4515 default:
4516 // By default, turn this into a target intrinsic node.
4517 visitTargetIntrinsic(I, Intrinsic);
4518 return 0;
4519 case Intrinsic::vastart: visitVAStart(I); return 0;
4520 case Intrinsic::vaend: visitVAEnd(I); return 0;
4521 case Intrinsic::vacopy: visitVACopy(I); return 0;
4522 case Intrinsic::returnaddress:
Bill Wendling4533cac2010-01-28 21:51:40 +00004523 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
Gabor Greif0635f352010-06-25 09:38:13 +00004524 getValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004525 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00004526 case Intrinsic::frameaddress:
Bill Wendling4533cac2010-01-28 21:51:40 +00004527 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
Gabor Greif0635f352010-06-25 09:38:13 +00004528 getValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004529 return 0;
4530 case Intrinsic::setjmp:
Bill Wendlingc27facc2012-03-05 19:29:36 +00004531 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004532 case Intrinsic::longjmp:
Bill Wendlingc27facc2012-03-05 19:29:36 +00004533 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
Chris Lattner824b9582008-11-21 16:42:48 +00004534 case Intrinsic::memcpy: {
Mon P Wang20adc9d2010-04-04 03:10:48 +00004535 // Assert for address < 256 since we support only user defined address
4536 // spaces.
Gabor Greif0635f352010-06-25 09:38:13 +00004537 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wang20adc9d2010-04-04 03:10:48 +00004538 < 256 &&
Gabor Greif0635f352010-06-25 09:38:13 +00004539 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
Mon P Wang20adc9d2010-04-04 03:10:48 +00004540 < 256 &&
4541 "Unknown address space");
Gabor Greif0635f352010-06-25 09:38:13 +00004542 SDValue Op1 = getValue(I.getArgOperand(0));
4543 SDValue Op2 = getValue(I.getArgOperand(1));
4544 SDValue Op3 = getValue(I.getArgOperand(2));
4545 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4546 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Mon P Wang20adc9d2010-04-04 03:10:48 +00004547 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol, false,
Chris Lattnere72f2022010-09-21 05:40:29 +00004548 MachinePointerInfo(I.getArgOperand(0)),
4549 MachinePointerInfo(I.getArgOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004550 return 0;
4551 }
Chris Lattner824b9582008-11-21 16:42:48 +00004552 case Intrinsic::memset: {
Mon P Wang20adc9d2010-04-04 03:10:48 +00004553 // Assert for address < 256 since we support only user defined address
4554 // spaces.
Gabor Greif0635f352010-06-25 09:38:13 +00004555 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wang20adc9d2010-04-04 03:10:48 +00004556 < 256 &&
4557 "Unknown address space");
Gabor Greif0635f352010-06-25 09:38:13 +00004558 SDValue Op1 = getValue(I.getArgOperand(0));
4559 SDValue Op2 = getValue(I.getArgOperand(1));
4560 SDValue Op3 = getValue(I.getArgOperand(2));
4561 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4562 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Mon P Wang20adc9d2010-04-04 03:10:48 +00004563 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
Chris Lattnere72f2022010-09-21 05:40:29 +00004564 MachinePointerInfo(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004565 return 0;
4566 }
Chris Lattner824b9582008-11-21 16:42:48 +00004567 case Intrinsic::memmove: {
Mon P Wang20adc9d2010-04-04 03:10:48 +00004568 // Assert for address < 256 since we support only user defined address
4569 // spaces.
Gabor Greif0635f352010-06-25 09:38:13 +00004570 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wang20adc9d2010-04-04 03:10:48 +00004571 < 256 &&
Gabor Greif0635f352010-06-25 09:38:13 +00004572 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
Mon P Wang20adc9d2010-04-04 03:10:48 +00004573 < 256 &&
4574 "Unknown address space");
Gabor Greif0635f352010-06-25 09:38:13 +00004575 SDValue Op1 = getValue(I.getArgOperand(0));
4576 SDValue Op2 = getValue(I.getArgOperand(1));
4577 SDValue Op3 = getValue(I.getArgOperand(2));
4578 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4579 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Mon P Wang20adc9d2010-04-04 03:10:48 +00004580 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
Chris Lattnere72f2022010-09-21 05:40:29 +00004581 MachinePointerInfo(I.getArgOperand(0)),
4582 MachinePointerInfo(I.getArgOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004583 return 0;
4584 }
Bill Wendling92c1e122009-02-13 02:16:35 +00004585 case Intrinsic::dbg_declare: {
Dan Gohman46510a72010-04-15 01:51:59 +00004586 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Devang Patelac1ceb32009-10-09 22:42:28 +00004587 MDNode *Variable = DI.getVariable();
Dan Gohman46510a72010-04-15 01:51:59 +00004588 const Value *Address = DI.getAddress();
Eric Christopher8f2a88d2012-03-15 21:33:41 +00004589 if (!Address || !DIVariable(Variable).Verify()) {
4590 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Dale Johannesen8ac38f22010-02-08 21:53:27 +00004591 return 0;
Eric Christopher8f2a88d2012-03-15 21:33:41 +00004592 }
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004593
4594 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4595 // but do not always have a corresponding SDNode built. The SDNodeOrder
4596 // absolute, but not relative, values are different depending on whether
4597 // debug info exists.
4598 ++SDNodeOrder;
Devang Patel3f74a112010-09-02 21:29:42 +00004599
4600 // Check if address has undef value.
4601 if (isa<UndefValue>(Address) ||
4602 (Address->use_empty() && !isa<Argument>(Address))) {
Eric Christopher24413672012-02-23 03:39:39 +00004603 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Devang Patel3f74a112010-09-02 21:29:42 +00004604 return 0;
4605 }
4606
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004607 SDValue &N = NodeMap[Address];
Devang Patel0b48ead2010-08-31 22:22:42 +00004608 if (!N.getNode() && isa<Argument>(Address))
4609 // Check unused arguments map.
4610 N = UnusedArgNodeMap[Address];
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004611 SDDbgValue *SDV;
4612 if (N.getNode()) {
Devang Patel8e741ed2010-09-02 21:02:27 +00004613 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4614 Address = BCI->getOperand(0);
Eric Christopher178606d2012-02-24 01:59:08 +00004615 // Parameters are handled specially.
4616 bool isParameter =
4617 (DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable ||
4618 isa<Argument>(Address));
4619
Devang Patel8e741ed2010-09-02 21:02:27 +00004620 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4621
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004622 if (isParameter && !AI) {
4623 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4624 if (FINode)
4625 // Byval parameter. We have a frame index at this point.
4626 SDV = DAG.getDbgValue(Variable, FINode->getIndex(),
4627 0, dl, SDNodeOrder);
Devang Patelafeaae72010-12-06 22:39:26 +00004628 else {
Devang Patel227dfdb2011-05-16 21:24:05 +00004629 // Address is an argument, so try to emit its dbg value using
4630 // virtual register info from the FuncInfo.ValueMap.
4631 EmitFuncArgumentDbgValue(Address, Variable, 0, N);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004632 return 0;
Devang Patelafeaae72010-12-06 22:39:26 +00004633 }
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004634 } else if (AI)
4635 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
4636 0, dl, SDNodeOrder);
Devang Patelafeaae72010-12-06 22:39:26 +00004637 else {
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004638 // Can't do anything with other non-AI cases yet.
Eric Christopher24413672012-02-23 03:39:39 +00004639 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Eric Christopher178606d2012-02-24 01:59:08 +00004640 DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
4641 DEBUG(Address->dump());
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004642 return 0;
Devang Patelafeaae72010-12-06 22:39:26 +00004643 }
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004644 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4645 } else {
Gabor Greiffb4032f2010-10-01 10:32:19 +00004646 // If Address is an argument then try to emit its dbg value using
Michael J. Spencere70c5262010-10-16 08:25:21 +00004647 // virtual register info from the FuncInfo.ValueMap.
Devang Patel6cd467b2010-08-26 22:53:27 +00004648 if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) {
Devang Patel1397fdc2010-09-15 14:48:53 +00004649 // If variable is pinned by a alloca in dominating bb then
4650 // use StaticAllocaMap.
4651 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
Devang Patel27ede1b2010-09-15 18:13:55 +00004652 if (AI->getParent() != DI.getParent()) {
4653 DenseMap<const AllocaInst*, int>::iterator SI =
4654 FuncInfo.StaticAllocaMap.find(AI);
4655 if (SI != FuncInfo.StaticAllocaMap.end()) {
4656 SDV = DAG.getDbgValue(Variable, SI->second,
4657 0, dl, SDNodeOrder);
4658 DAG.AddDbgValue(SDV, 0, false);
4659 return 0;
4660 }
Devang Patel1397fdc2010-09-15 14:48:53 +00004661 }
4662 }
Eric Christopher0822e012012-02-23 03:39:43 +00004663 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Devang Patel6cd467b2010-08-26 22:53:27 +00004664 }
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004665 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004666 return 0;
Bill Wendling92c1e122009-02-13 02:16:35 +00004667 }
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004668 case Intrinsic::dbg_value: {
Dan Gohman46510a72010-04-15 01:51:59 +00004669 const DbgValueInst &DI = cast<DbgValueInst>(I);
Devang Patel02f0dbd2010-05-07 22:04:20 +00004670 if (!DIVariable(DI.getVariable()).Verify())
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004671 return 0;
4672
4673 MDNode *Variable = DI.getVariable();
Devang Patel00190342010-03-15 19:15:44 +00004674 uint64_t Offset = DI.getOffset();
Dan Gohman46510a72010-04-15 01:51:59 +00004675 const Value *V = DI.getValue();
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004676 if (!V)
4677 return 0;
Devang Patel00190342010-03-15 19:15:44 +00004678
4679 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4680 // but do not always have a corresponding SDNode built. The SDNodeOrder
4681 // absolute, but not relative, values are different depending on whether
4682 // debug info exists.
4683 ++SDNodeOrder;
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004684 SDDbgValue *SDV;
Devang Patel57871242011-08-03 23:13:55 +00004685 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004686 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder);
4687 DAG.AddDbgValue(SDV, 0, false);
Devang Patel00190342010-03-15 19:15:44 +00004688 } else {
Dale Johannesenbdc09d92010-07-16 00:02:08 +00004689 // Do not use getValue() in here; we don't want to generate code at
4690 // this point if it hasn't been done yet.
Devang Patel9126c0d2010-06-01 19:59:01 +00004691 SDValue N = NodeMap[V];
4692 if (!N.getNode() && isa<Argument>(V))
4693 // Check unused arguments map.
4694 N = UnusedArgNodeMap[V];
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004695 if (N.getNode()) {
Devang Patel78a06e52010-08-25 20:39:26 +00004696 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) {
Evan Cheng9e8a2b92010-04-29 01:40:30 +00004697 SDV = DAG.getDbgValue(Variable, N.getNode(),
4698 N.getResNo(), Offset, dl, SDNodeOrder);
4699 DAG.AddDbgValue(SDV, N.getNode(), false);
4700 }
Devang Patela778f5c2011-02-18 22:43:42 +00004701 } else if (!V->use_empty() ) {
Dale Johannesenbdc09d92010-07-16 00:02:08 +00004702 // Do not call getValue(V) yet, as we don't want to generate code.
4703 // Remember it for later.
4704 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4705 DanglingDebugInfoMap[V] = DDI;
Devang Patel0991dfb2010-08-27 22:25:51 +00004706 } else {
Devang Patel00190342010-03-15 19:15:44 +00004707 // We may expand this to cover more cases. One case where we have no
Devang Patelafeaae72010-12-06 22:39:26 +00004708 // data available is an unreferenced parameter.
Eric Christopher0822e012012-02-23 03:39:43 +00004709 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004710 }
Devang Patel00190342010-03-15 19:15:44 +00004711 }
4712
4713 // Build a debug info table entry.
Dan Gohman46510a72010-04-15 01:51:59 +00004714 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004715 V = BCI->getOperand(0);
Dan Gohman46510a72010-04-15 01:51:59 +00004716 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004717 // Don't handle byval struct arguments or VLAs, for example.
Eric Christopher7e1e18f2012-03-26 06:10:32 +00004718 if (!AI) {
Eric Christopher9fc5c832012-03-28 07:34:36 +00004719 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
4720 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004721 return 0;
Eric Christopher7e1e18f2012-03-26 06:10:32 +00004722 }
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004723 DenseMap<const AllocaInst*, int>::iterator SI =
4724 FuncInfo.StaticAllocaMap.find(AI);
4725 if (SI == FuncInfo.StaticAllocaMap.end())
4726 return 0; // VLAs.
4727 int FI = SI->second;
Michael J. Spencere70c5262010-10-16 08:25:21 +00004728
Chris Lattner512063d2010-04-05 06:19:28 +00004729 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4730 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
4731 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004732 return 0;
4733 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004734
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00004735 case Intrinsic::eh_typeid_for: {
Chris Lattner512063d2010-04-05 06:19:28 +00004736 // Find the type id for the given typeinfo.
Gabor Greif0635f352010-06-25 09:38:13 +00004737 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
Chris Lattner512063d2010-04-05 06:19:28 +00004738 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4739 Res = DAG.getConstant(TypeID, MVT::i32);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004740 setValue(&I, Res);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004741 return 0;
4742 }
4743
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004744 case Intrinsic::eh_return_i32:
4745 case Intrinsic::eh_return_i64:
Chris Lattner512063d2010-04-05 06:19:28 +00004746 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4747 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
4748 MVT::Other,
4749 getControlRoot(),
Gabor Greif0635f352010-06-25 09:38:13 +00004750 getValue(I.getArgOperand(0)),
4751 getValue(I.getArgOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004752 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004753 case Intrinsic::eh_unwind_init:
Chris Lattner512063d2010-04-05 06:19:28 +00004754 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004755 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004756 case Intrinsic::eh_dwarf_cfa: {
Gabor Greif0635f352010-06-25 09:38:13 +00004757 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), dl,
Duncan Sands3a66a682009-10-13 21:04:12 +00004758 TLI.getPointerTy());
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004759 SDValue Offset = DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004760 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004761 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004762 TLI.getPointerTy()),
4763 CfaArg);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004764 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004765 TLI.getPointerTy(),
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004766 DAG.getConstant(0, TLI.getPointerTy()));
Bill Wendling4533cac2010-01-28 21:51:40 +00004767 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
4768 FA, Offset));
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004769 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004770 }
Jim Grosbachca752c92010-01-28 01:45:32 +00004771 case Intrinsic::eh_sjlj_callsite: {
Chris Lattner512063d2010-04-05 06:19:28 +00004772 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Gabor Greif0635f352010-06-25 09:38:13 +00004773 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
Jim Grosbachca752c92010-01-28 01:45:32 +00004774 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
Chris Lattner512063d2010-04-05 06:19:28 +00004775 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
Jim Grosbachca752c92010-01-28 01:45:32 +00004776
Chris Lattner512063d2010-04-05 06:19:28 +00004777 MMI.setCurrentCallSite(CI->getZExtValue());
Jim Grosbachca752c92010-01-28 01:45:32 +00004778 return 0;
4779 }
Bill Wendling6ef94172011-09-28 03:36:43 +00004780 case Intrinsic::eh_sjlj_functioncontext: {
4781 // Get and store the index of the function context.
4782 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
Bill Wendlingadbf7b22011-09-28 03:52:41 +00004783 AllocaInst *FnCtx =
4784 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
Bill Wendling6ef94172011-09-28 03:36:43 +00004785 int FI = FuncInfo.StaticAllocaMap[FnCtx];
4786 MFI->setFunctionContextIndex(FI);
4787 return 0;
4788 }
Jim Grosbach23ff7cf2010-05-26 20:22:18 +00004789 case Intrinsic::eh_sjlj_setjmp: {
Bill Wendlingce370cf2011-10-07 21:25:38 +00004790 SDValue Ops[2];
4791 Ops[0] = getRoot();
4792 Ops[1] = getValue(I.getArgOperand(0));
4793 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, dl,
4794 DAG.getVTList(MVT::i32, MVT::Other),
4795 Ops, 2);
4796 setValue(&I, Op.getValue(0));
4797 DAG.setRoot(Op.getValue(1));
Jim Grosbach23ff7cf2010-05-26 20:22:18 +00004798 return 0;
4799 }
Jim Grosbach5eb19512010-05-22 01:06:18 +00004800 case Intrinsic::eh_sjlj_longjmp: {
Jim Grosbach23ff7cf2010-05-26 20:22:18 +00004801 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, dl, MVT::Other,
Jim Grosbache4ad3872010-10-19 23:27:08 +00004802 getRoot(), getValue(I.getArgOperand(0))));
4803 return 0;
4804 }
Jim Grosbachca752c92010-01-28 01:45:32 +00004805
Dale Johannesen0488fb62010-09-30 23:57:10 +00004806 case Intrinsic::x86_mmx_pslli_w:
4807 case Intrinsic::x86_mmx_pslli_d:
4808 case Intrinsic::x86_mmx_pslli_q:
4809 case Intrinsic::x86_mmx_psrli_w:
4810 case Intrinsic::x86_mmx_psrli_d:
4811 case Intrinsic::x86_mmx_psrli_q:
4812 case Intrinsic::x86_mmx_psrai_w:
4813 case Intrinsic::x86_mmx_psrai_d: {
4814 SDValue ShAmt = getValue(I.getArgOperand(1));
4815 if (isa<ConstantSDNode>(ShAmt)) {
4816 visitTargetIntrinsic(I, Intrinsic);
4817 return 0;
4818 }
4819 unsigned NewIntrinsic = 0;
4820 EVT ShAmtVT = MVT::v2i32;
4821 switch (Intrinsic) {
4822 case Intrinsic::x86_mmx_pslli_w:
4823 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4824 break;
4825 case Intrinsic::x86_mmx_pslli_d:
4826 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4827 break;
4828 case Intrinsic::x86_mmx_pslli_q:
4829 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4830 break;
4831 case Intrinsic::x86_mmx_psrli_w:
4832 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4833 break;
4834 case Intrinsic::x86_mmx_psrli_d:
4835 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4836 break;
4837 case Intrinsic::x86_mmx_psrli_q:
4838 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4839 break;
4840 case Intrinsic::x86_mmx_psrai_w:
4841 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4842 break;
4843 case Intrinsic::x86_mmx_psrai_d:
4844 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4845 break;
4846 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4847 }
4848
4849 // The vector shift intrinsics with scalars uses 32b shift amounts but
4850 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4851 // to be zero.
4852 // We must do this early because v2i32 is not a legal type.
4853 DebugLoc dl = getCurDebugLoc();
4854 SDValue ShOps[2];
4855 ShOps[0] = ShAmt;
4856 ShOps[1] = DAG.getConstant(0, MVT::i32);
4857 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
4858 EVT DestVT = TLI.getValueType(I.getType());
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004859 ShAmt = DAG.getNode(ISD::BITCAST, dl, DestVT, ShAmt);
Dale Johannesen0488fb62010-09-30 23:57:10 +00004860 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
4861 DAG.getConstant(NewIntrinsic, MVT::i32),
4862 getValue(I.getArgOperand(0)), ShAmt);
4863 setValue(&I, Res);
4864 return 0;
4865 }
Pete Cooperd18134f2012-02-24 03:51:49 +00004866 case Intrinsic::x86_avx_vinsertf128_pd_256:
4867 case Intrinsic::x86_avx_vinsertf128_ps_256:
Craig Topperb45c9692012-04-07 22:32:29 +00004868 case Intrinsic::x86_avx_vinsertf128_si_256:
4869 case Intrinsic::x86_avx2_vinserti128: {
Pete Cooperd18134f2012-02-24 03:51:49 +00004870 DebugLoc dl = getCurDebugLoc();
4871 EVT DestVT = TLI.getValueType(I.getType());
4872 EVT ElVT = TLI.getValueType(I.getArgOperand(1)->getType());
4873 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue() & 1) *
4874 ElVT.getVectorNumElements();
4875 Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, DestVT,
4876 getValue(I.getArgOperand(0)),
4877 getValue(I.getArgOperand(1)),
Craig Topperf6dc7922012-09-05 05:48:09 +00004878 DAG.getIntPtrConstant(Idx));
4879 setValue(&I, Res);
4880 return 0;
4881 }
4882 case Intrinsic::x86_avx_vextractf128_pd_256:
4883 case Intrinsic::x86_avx_vextractf128_ps_256:
4884 case Intrinsic::x86_avx_vextractf128_si_256:
4885 case Intrinsic::x86_avx2_vextracti128: {
4886 DebugLoc dl = getCurDebugLoc();
4887 EVT DestVT = TLI.getValueType(I.getType());
4888 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(1))->getZExtValue() & 1) *
4889 DestVT.getVectorNumElements();
4890 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT,
4891 getValue(I.getArgOperand(0)),
4892 DAG.getIntPtrConstant(Idx));
Pete Cooperd18134f2012-02-24 03:51:49 +00004893 setValue(&I, Res);
4894 return 0;
4895 }
Mon P Wang77cdf302008-11-10 20:54:11 +00004896 case Intrinsic::convertff:
4897 case Intrinsic::convertfsi:
4898 case Intrinsic::convertfui:
4899 case Intrinsic::convertsif:
4900 case Intrinsic::convertuif:
4901 case Intrinsic::convertss:
4902 case Intrinsic::convertsu:
4903 case Intrinsic::convertus:
4904 case Intrinsic::convertuu: {
4905 ISD::CvtCode Code = ISD::CVT_INVALID;
4906 switch (Intrinsic) {
Craig Topperc42e6402012-04-11 04:34:11 +00004907 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
Mon P Wang77cdf302008-11-10 20:54:11 +00004908 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4909 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4910 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4911 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4912 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4913 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4914 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4915 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4916 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4917 }
Owen Andersone50ed302009-08-10 22:56:29 +00004918 EVT DestVT = TLI.getValueType(I.getType());
Gabor Greif0635f352010-06-25 09:38:13 +00004919 const Value *Op1 = I.getArgOperand(0);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004920 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4921 DAG.getValueType(DestVT),
4922 DAG.getValueType(getValue(Op1).getValueType()),
Gabor Greif0635f352010-06-25 09:38:13 +00004923 getValue(I.getArgOperand(1)),
4924 getValue(I.getArgOperand(2)),
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004925 Code);
4926 setValue(&I, Res);
Mon P Wang77cdf302008-11-10 20:54:11 +00004927 return 0;
4928 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004929 case Intrinsic::sqrt:
Bill Wendling4533cac2010-01-28 21:51:40 +00004930 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00004931 getValue(I.getArgOperand(0)).getValueType(),
4932 getValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004933 return 0;
4934 case Intrinsic::powi:
Gabor Greif0635f352010-06-25 09:38:13 +00004935 setValue(&I, ExpandPowI(dl, getValue(I.getArgOperand(0)),
4936 getValue(I.getArgOperand(1)), DAG));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004937 return 0;
4938 case Intrinsic::sin:
Bill Wendling4533cac2010-01-28 21:51:40 +00004939 setValue(&I, DAG.getNode(ISD::FSIN, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00004940 getValue(I.getArgOperand(0)).getValueType(),
4941 getValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004942 return 0;
4943 case Intrinsic::cos:
Bill Wendling4533cac2010-01-28 21:51:40 +00004944 setValue(&I, DAG.getNode(ISD::FCOS, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00004945 getValue(I.getArgOperand(0)).getValueType(),
4946 getValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004947 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004948 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004949 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004950 return 0;
4951 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004952 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004953 return 0;
4954 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004955 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004956 return 0;
4957 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004958 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004959 return 0;
4960 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00004961 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004962 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004963 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004964 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004965 return 0;
Peter Collingbourneb34d3aa2012-05-28 21:48:37 +00004966 case Intrinsic::fabs:
4967 setValue(&I, DAG.getNode(ISD::FABS, dl,
4968 getValue(I.getArgOperand(0)).getValueType(),
4969 getValue(I.getArgOperand(0))));
4970 return 0;
Dan Gohman27db99f2012-07-26 17:43:27 +00004971 case Intrinsic::floor:
4972 setValue(&I, DAG.getNode(ISD::FFLOOR, dl,
4973 getValue(I.getArgOperand(0)).getValueType(),
4974 getValue(I.getArgOperand(0))));
4975 return 0;
Cameron Zwarich33390842011-07-08 21:39:21 +00004976 case Intrinsic::fma:
4977 setValue(&I, DAG.getNode(ISD::FMA, dl,
4978 getValue(I.getArgOperand(0)).getValueType(),
4979 getValue(I.getArgOperand(0)),
4980 getValue(I.getArgOperand(1)),
4981 getValue(I.getArgOperand(2))));
4982 return 0;
Lang Hames5afba6f2012-06-05 19:07:46 +00004983 case Intrinsic::fmuladd: {
4984 EVT VT = TLI.getValueType(I.getType());
Lang Hamese0231412012-06-22 01:09:09 +00004985 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
4986 TLI.isOperationLegal(ISD::FMA, VT) &&
4987 TLI.isFMAFasterThanMulAndAdd(VT)){
Lang Hames5afba6f2012-06-05 19:07:46 +00004988 setValue(&I, DAG.getNode(ISD::FMA, dl,
4989 getValue(I.getArgOperand(0)).getValueType(),
4990 getValue(I.getArgOperand(0)),
4991 getValue(I.getArgOperand(1)),
4992 getValue(I.getArgOperand(2))));
4993 } else {
4994 SDValue Mul = DAG.getNode(ISD::FMUL, dl,
4995 getValue(I.getArgOperand(0)).getValueType(),
4996 getValue(I.getArgOperand(0)),
4997 getValue(I.getArgOperand(1)));
4998 SDValue Add = DAG.getNode(ISD::FADD, dl,
4999 getValue(I.getArgOperand(0)).getValueType(),
5000 Mul,
5001 getValue(I.getArgOperand(2)));
5002 setValue(&I, Add);
5003 }
5004 return 0;
5005 }
Anton Korobeynikovbe5b0322010-03-14 18:42:15 +00005006 case Intrinsic::convert_to_fp16:
5007 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00005008 MVT::i16, getValue(I.getArgOperand(0))));
Anton Korobeynikovbe5b0322010-03-14 18:42:15 +00005009 return 0;
5010 case Intrinsic::convert_from_fp16:
5011 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00005012 MVT::f32, getValue(I.getArgOperand(0))));
Anton Korobeynikovbe5b0322010-03-14 18:42:15 +00005013 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005014 case Intrinsic::pcmarker: {
Gabor Greif0635f352010-06-25 09:38:13 +00005015 SDValue Tmp = getValue(I.getArgOperand(0));
Bill Wendling4533cac2010-01-28 21:51:40 +00005016 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005017 return 0;
5018 }
5019 case Intrinsic::readcyclecounter: {
5020 SDValue Op = getRoot();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005021 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
5022 DAG.getVTList(MVT::i64, MVT::Other),
5023 &Op, 1);
5024 setValue(&I, Res);
5025 DAG.setRoot(Res.getValue(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005026 return 0;
5027 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005028 case Intrinsic::bswap:
Bill Wendling4533cac2010-01-28 21:51:40 +00005029 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00005030 getValue(I.getArgOperand(0)).getValueType(),
5031 getValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005032 return 0;
5033 case Intrinsic::cttz: {
Gabor Greif0635f352010-06-25 09:38:13 +00005034 SDValue Arg = getValue(I.getArgOperand(0));
Chandler Carruth63974b22011-12-13 01:56:10 +00005035 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00005036 EVT Ty = Arg.getValueType();
Chandler Carruth63974b22011-12-13 01:56:10 +00005037 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5038 dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005039 return 0;
5040 }
5041 case Intrinsic::ctlz: {
Gabor Greif0635f352010-06-25 09:38:13 +00005042 SDValue Arg = getValue(I.getArgOperand(0));
Chandler Carruth63974b22011-12-13 01:56:10 +00005043 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00005044 EVT Ty = Arg.getValueType();
Chandler Carruth63974b22011-12-13 01:56:10 +00005045 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5046 dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005047 return 0;
5048 }
5049 case Intrinsic::ctpop: {
Gabor Greif0635f352010-06-25 09:38:13 +00005050 SDValue Arg = getValue(I.getArgOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00005051 EVT Ty = Arg.getValueType();
Bill Wendling4533cac2010-01-28 21:51:40 +00005052 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005053 return 0;
5054 }
5055 case Intrinsic::stacksave: {
5056 SDValue Op = getRoot();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005057 Res = DAG.getNode(ISD::STACKSAVE, dl,
5058 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
5059 setValue(&I, Res);
5060 DAG.setRoot(Res.getValue(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005061 return 0;
5062 }
5063 case Intrinsic::stackrestore: {
Gabor Greif0635f352010-06-25 09:38:13 +00005064 Res = getValue(I.getArgOperand(0));
Bill Wendling4533cac2010-01-28 21:51:40 +00005065 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005066 return 0;
5067 }
Bill Wendling57344502008-11-18 11:01:33 +00005068 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00005069 // Emit code into the DAG to store the stack guard onto the stack.
5070 MachineFunction &MF = DAG.getMachineFunction();
5071 MachineFrameInfo *MFI = MF.getFrameInfo();
Owen Andersone50ed302009-08-10 22:56:29 +00005072 EVT PtrTy = TLI.getPointerTy();
Bill Wendlingb2a42982008-11-06 02:29:10 +00005073
Gabor Greif0635f352010-06-25 09:38:13 +00005074 SDValue Src = getValue(I.getArgOperand(0)); // The guard's value.
5075 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
Bill Wendlingb2a42982008-11-06 02:29:10 +00005076
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00005077 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00005078 MFI->setStackProtectorIndex(FI);
5079
5080 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5081
5082 // Store the stack protector onto the stack.
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005083 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
Chris Lattner84bd98a2010-09-21 18:58:22 +00005084 MachinePointerInfo::getFixedStack(FI),
5085 true, false, 0);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005086 setValue(&I, Res);
5087 DAG.setRoot(Res);
Bill Wendlingb2a42982008-11-06 02:29:10 +00005088 return 0;
5089 }
Eric Christopher7b5e6172009-10-27 00:52:25 +00005090 case Intrinsic::objectsize: {
5091 // If we don't know by now, we're never going to know.
Gabor Greif0635f352010-06-25 09:38:13 +00005092 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
Eric Christopher7b5e6172009-10-27 00:52:25 +00005093
5094 assert(CI && "Non-constant type in __builtin_object_size?");
5095
Gabor Greif0635f352010-06-25 09:38:13 +00005096 SDValue Arg = getValue(I.getCalledValue());
Eric Christopher7e5d2ff2009-10-28 21:32:16 +00005097 EVT Ty = Arg.getValueType();
5098
Dan Gohmane368b462010-06-18 14:22:04 +00005099 if (CI->isZero())
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005100 Res = DAG.getConstant(-1ULL, Ty);
Eric Christopher7b5e6172009-10-27 00:52:25 +00005101 else
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005102 Res = DAG.getConstant(0, Ty);
5103
5104 setValue(&I, Res);
Eric Christopher7b5e6172009-10-27 00:52:25 +00005105 return 0;
5106 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005107 case Intrinsic::var_annotation:
5108 // Discard annotate attributes
5109 return 0;
5110
5111 case Intrinsic::init_trampoline: {
Gabor Greif0635f352010-06-25 09:38:13 +00005112 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005113
5114 SDValue Ops[6];
5115 Ops[0] = getRoot();
Gabor Greif0635f352010-06-25 09:38:13 +00005116 Ops[1] = getValue(I.getArgOperand(0));
5117 Ops[2] = getValue(I.getArgOperand(1));
5118 Ops[3] = getValue(I.getArgOperand(2));
5119 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005120 Ops[5] = DAG.getSrcValue(F);
5121
Duncan Sands4a544a72011-09-06 13:37:06 +00005122 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, dl, MVT::Other, Ops, 6);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005123
Duncan Sands4a544a72011-09-06 13:37:06 +00005124 DAG.setRoot(Res);
5125 return 0;
5126 }
5127 case Intrinsic::adjust_trampoline: {
5128 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, dl,
5129 TLI.getPointerTy(),
5130 getValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005131 return 0;
5132 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005133 case Intrinsic::gcroot:
5134 if (GFI) {
Bill Wendling95dd4422012-05-01 22:50:45 +00005135 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
Gabor Greif0635f352010-06-25 09:38:13 +00005136 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005137
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005138 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5139 GFI->addStackRoot(FI->getIndex(), TypeMap);
5140 }
5141 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005142 case Intrinsic::gcread:
5143 case Intrinsic::gcwrite:
Torok Edwinc23197a2009-07-14 16:55:14 +00005144 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005145 case Intrinsic::flt_rounds:
Bill Wendling4533cac2010-01-28 21:51:40 +00005146 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005147 return 0;
Jakub Staszak9da99342011-07-06 18:22:43 +00005148
5149 case Intrinsic::expect: {
5150 // Just replace __builtin_expect(exp, c) with EXP.
5151 setValue(&I, getValue(I.getArgOperand(0)));
5152 return 0;
5153 }
5154
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005155 case Intrinsic::trap: {
Nick Lewycky8a8d4792011-12-02 22:16:29 +00005156 StringRef TrapFuncName = TM.Options.getTrapFunctionName();
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005157 if (TrapFuncName.empty()) {
5158 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
5159 return 0;
5160 }
5161 TargetLowering::ArgListTy Args;
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00005162 TargetLowering::
5163 CallLoweringInfo CLI(getRoot(), I.getType(),
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005164 false, false, false, false, 0, CallingConv::C,
Evan Cheng4bfcd4a2012-02-28 18:51:51 +00005165 /*isTailCall=*/false,
5166 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005167 DAG.getExternalSymbol(TrapFuncName.data(), TLI.getPointerTy()),
5168 Args, DAG, getCurDebugLoc());
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00005169 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005170 DAG.setRoot(Result.second);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005171 return 0;
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005172 }
Dan Gohmana6063c62012-05-14 18:58:10 +00005173 case Intrinsic::debugtrap: {
5174 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, dl,MVT::Other, getRoot()));
Dan Gohmand4347e12012-05-11 00:19:32 +00005175 return 0;
5176 }
Bill Wendlingef375462008-11-21 02:38:44 +00005177 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00005178 case Intrinsic::sadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00005179 case Intrinsic::usub_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00005180 case Intrinsic::ssub_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00005181 case Intrinsic::umul_with_overflow:
Craig Topperc42e6402012-04-11 04:34:11 +00005182 case Intrinsic::smul_with_overflow: {
5183 ISD::NodeType Op;
5184 switch (Intrinsic) {
5185 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5186 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5187 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5188 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5189 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5190 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5191 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5192 }
5193 SDValue Op1 = getValue(I.getArgOperand(0));
5194 SDValue Op2 = getValue(I.getArgOperand(1));
Bill Wendling7cdc3c82008-11-21 02:03:52 +00005195
Craig Topperc42e6402012-04-11 04:34:11 +00005196 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5197 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
5198 return 0;
5199 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005200 case Intrinsic::prefetch: {
Bruno Cardoso Lopes9a767332011-06-14 04:58:37 +00005201 SDValue Ops[5];
Dale Johannesen1de4aa92010-10-26 23:11:10 +00005202 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005203 Ops[0] = getRoot();
Gabor Greif0635f352010-06-25 09:38:13 +00005204 Ops[1] = getValue(I.getArgOperand(0));
5205 Ops[2] = getValue(I.getArgOperand(1));
5206 Ops[3] = getValue(I.getArgOperand(2));
Bruno Cardoso Lopes9a767332011-06-14 04:58:37 +00005207 Ops[4] = getValue(I.getArgOperand(3));
Dale Johannesen1de4aa92010-10-26 23:11:10 +00005208 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, dl,
5209 DAG.getVTList(MVT::Other),
Bruno Cardoso Lopes9a767332011-06-14 04:58:37 +00005210 &Ops[0], 5,
Dale Johannesen1de4aa92010-10-26 23:11:10 +00005211 EVT::getIntegerVT(*Context, 8),
5212 MachinePointerInfo(I.getArgOperand(0)),
5213 0, /* align */
5214 false, /* volatile */
5215 rw==0, /* read */
5216 rw==1)); /* write */
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005217 return 0;
5218 }
Duncan Sandsf07c9492009-11-10 09:08:09 +00005219 case Intrinsic::lifetime_start:
Nadav Rotemc05d3062012-09-06 09:17:37 +00005220 case Intrinsic::lifetime_end: {
5221 SDValue Ops[2];
5222 AllocaInst *LifetimeObject =dyn_cast_or_null<AllocaInst>(
5223 GetUnderlyingObject(I.getArgOperand(1), TD));
5224 // Could not find an Alloca.
5225 if (!LifetimeObject)
5226 return 0;
5227
5228 int FI = FuncInfo.StaticAllocaMap[LifetimeObject];
5229 Ops[0] = getRoot();
5230 Ops[1] = DAG.getFrameIndex(FI, TLI.getPointerTy(), true);
5231 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5232 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5233
5234 Res = DAG.getNode(Opcode, dl, MVT::Other, Ops, 2);
5235 DAG.setRoot(Res);
5236 return 0;
5237 }
5238 case Intrinsic::invariant_start:
Duncan Sandsf07c9492009-11-10 09:08:09 +00005239 // Discard region information.
Bill Wendling4533cac2010-01-28 21:51:40 +00005240 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
Duncan Sandsf07c9492009-11-10 09:08:09 +00005241 return 0;
5242 case Intrinsic::invariant_end:
Duncan Sandsf07c9492009-11-10 09:08:09 +00005243 // Discard region information.
5244 return 0;
Nuno Lopes85b40892012-06-28 22:30:12 +00005245 case Intrinsic::donothing:
5246 // ignore
5247 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005248 }
5249}
5250
Dan Gohman46510a72010-04-15 01:51:59 +00005251void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
Dan Gohman2048b852009-11-23 18:04:58 +00005252 bool isTailCall,
5253 MachineBasicBlock *LandingPad) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005254 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
5255 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
5256 Type *RetTy = FTy->getReturnType();
Chris Lattner512063d2010-04-05 06:19:28 +00005257 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Chris Lattner16112732010-03-14 01:41:15 +00005258 MCSymbol *BeginLabel = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005259
5260 TargetLowering::ArgListTy Args;
5261 TargetLowering::ArgListEntry Entry;
5262 Args.reserve(CS.arg_size());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005263
5264 // Check whether the function can return without sret-demotion.
Dan Gohman84023e02010-07-10 09:00:22 +00005265 SmallVector<ISD::OutputArg, 4> Outs;
Dan Gohman84023e02010-07-10 09:00:22 +00005266 GetReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
Eli Friedman2db0e9e2012-05-25 00:09:29 +00005267 Outs, TLI);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005268
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005269 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
Bill Wendling96cb1122012-07-19 00:04:14 +00005270 DAG.getMachineFunction(),
5271 FTy->isVarArg(), Outs,
5272 FTy->getContext());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005273
5274 SDValue DemoteStackSlot;
Chris Lattnerecf42c42010-09-21 16:36:31 +00005275 int DemoteStackIdx = -100;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005276
5277 if (!CanLowerReturn) {
5278 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
5279 FTy->getReturnType());
5280 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
5281 FTy->getReturnType());
5282 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerecf42c42010-09-21 16:36:31 +00005283 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005284 Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005285
Chris Lattnerecf42c42010-09-21 16:36:31 +00005286 DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI.getPointerTy());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005287 Entry.Node = DemoteStackSlot;
5288 Entry.Ty = StackSlotPtrType;
5289 Entry.isSExt = false;
5290 Entry.isZExt = false;
5291 Entry.isInReg = false;
5292 Entry.isSRet = true;
5293 Entry.isNest = false;
5294 Entry.isByVal = false;
5295 Entry.Alignment = Align;
5296 Args.push_back(Entry);
5297 RetTy = Type::getVoidTy(FTy->getContext());
5298 }
5299
Dan Gohman46510a72010-04-15 01:51:59 +00005300 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005301 i != e; ++i) {
Rafael Espindola3fa82832011-05-13 15:18:06 +00005302 const Value *V = *i;
5303
5304 // Skip empty types
5305 if (V->getType()->isEmptyTy())
5306 continue;
5307
5308 SDValue ArgNode = getValue(V);
5309 Entry.Node = ArgNode; Entry.Ty = V->getType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005310
5311 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00005312 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
5313 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
5314 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
5315 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
5316 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
5317 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005318 Entry.Alignment = CS.getParamAlignment(attrInd);
5319 Args.push_back(Entry);
5320 }
5321
Chris Lattner512063d2010-04-05 06:19:28 +00005322 if (LandingPad) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005323 // Insert a label before the invoke call to mark the try range. This can be
5324 // used to detect deletion of the invoke via the MachineModuleInfo.
Chris Lattner512063d2010-04-05 06:19:28 +00005325 BeginLabel = MMI.getContext().CreateTempSymbol();
Jim Grosbach1b747ad2009-08-11 00:09:57 +00005326
Jim Grosbachca752c92010-01-28 01:45:32 +00005327 // For SjLj, keep track of which landing pads go with which invokes
5328 // so as to maintain the ordering of pads in the LSDA.
Chris Lattner512063d2010-04-05 06:19:28 +00005329 unsigned CallSiteIndex = MMI.getCurrentCallSite();
Jim Grosbachca752c92010-01-28 01:45:32 +00005330 if (CallSiteIndex) {
Chris Lattner512063d2010-04-05 06:19:28 +00005331 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
Bill Wendling30e67402011-10-05 22:24:35 +00005332 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
Bill Wendlinga8512ed2011-10-04 22:00:35 +00005333
Jim Grosbachca752c92010-01-28 01:45:32 +00005334 // Now that the call site is handled, stop tracking it.
Chris Lattner512063d2010-04-05 06:19:28 +00005335 MMI.setCurrentCallSite(0);
Jim Grosbachca752c92010-01-28 01:45:32 +00005336 }
5337
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005338 // Both PendingLoads and PendingExports must be flushed here;
5339 // this call might not return.
5340 (void)getRoot();
Chris Lattner7561d482010-03-14 02:33:54 +00005341 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getControlRoot(), BeginLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005342 }
5343
Dan Gohman98ca4f22009-08-05 01:29:28 +00005344 // Check if target-independent constraints permit a tail call here.
5345 // Target-dependent constraints are checked within TLI.LowerCallTo.
5346 if (isTailCall &&
Evan Cheng86809cc2010-02-03 03:28:02 +00005347 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
Dan Gohman98ca4f22009-08-05 01:29:28 +00005348 isTailCall = false;
5349
Dan Gohmanbadcda42010-08-28 00:51:03 +00005350 // If there's a possibility that fast-isel has already selected some amount
5351 // of the current basic block, don't emit a tail call.
Nick Lewycky8a8d4792011-12-02 22:16:29 +00005352 if (isTailCall && TM.Options.EnableFastISel)
Dan Gohmanbadcda42010-08-28 00:51:03 +00005353 isTailCall = false;
5354
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00005355 TargetLowering::
5356 CallLoweringInfo CLI(getRoot(), RetTy, FTy, isTailCall, Callee, Args, DAG,
5357 getCurDebugLoc(), CS);
5358 std::pair<SDValue,SDValue> Result = TLI.LowerCallTo(CLI);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005359 assert((isTailCall || Result.second.getNode()) &&
5360 "Non-null chain expected with non-tail call!");
5361 assert((Result.second.getNode() || !Result.first.getNode()) &&
5362 "Null value expected with tail call!");
Bill Wendlinge80ae832009-12-22 00:50:32 +00005363 if (Result.first.getNode()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005364 setValue(CS.getInstruction(), Result.first);
Bill Wendlinge80ae832009-12-22 00:50:32 +00005365 } else if (!CanLowerReturn && Result.second.getNode()) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005366 // The instruction result is the result of loading from the
5367 // hidden sret parameter.
5368 SmallVector<EVT, 1> PVTs;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005369 Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005370
5371 ComputeValueVTs(TLI, PtrRetTy, PVTs);
5372 assert(PVTs.size() == 1 && "Pointers should fit in one register");
5373 EVT PtrVT = PVTs[0];
Eli Friedman2db0e9e2012-05-25 00:09:29 +00005374
5375 SmallVector<EVT, 4> RetTys;
5376 SmallVector<uint64_t, 4> Offsets;
5377 RetTy = FTy->getReturnType();
5378 ComputeValueVTs(TLI, RetTy, RetTys, &Offsets);
5379
5380 unsigned NumValues = RetTys.size();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005381 SmallVector<SDValue, 4> Values(NumValues);
5382 SmallVector<SDValue, 4> Chains(NumValues);
5383
5384 for (unsigned i = 0; i < NumValues; ++i) {
Bill Wendlinge80ae832009-12-22 00:50:32 +00005385 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
5386 DemoteStackSlot,
5387 DAG.getConstant(Offsets[i], PtrVT));
Eli Friedman2db0e9e2012-05-25 00:09:29 +00005388 SDValue L = DAG.getLoad(RetTys[i], getCurDebugLoc(), Result.second, Add,
Chris Lattnerecf42c42010-09-21 16:36:31 +00005389 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]),
Pete Cooperd752e0f2011-11-08 18:42:53 +00005390 false, false, false, 1);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005391 Values[i] = L;
5392 Chains[i] = L.getValue(1);
5393 }
Bill Wendlinge80ae832009-12-22 00:50:32 +00005394
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005395 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
5396 MVT::Other, &Chains[0], NumValues);
5397 PendingLoads.push_back(Chain);
Michael J. Spencere70c5262010-10-16 08:25:21 +00005398
Bill Wendling4533cac2010-01-28 21:51:40 +00005399 setValue(CS.getInstruction(),
5400 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
5401 DAG.getVTList(&RetTys[0], RetTys.size()),
Eli Friedman2db0e9e2012-05-25 00:09:29 +00005402 &Values[0], Values.size()));
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005403 }
Bill Wendlinge80ae832009-12-22 00:50:32 +00005404
Evan Chengc249e482011-04-01 19:57:01 +00005405 // Assign order to nodes here. If the call does not produce a result, it won't
5406 // be mapped to a SDNode and visit() will not assign it an order number.
Evan Cheng8380c032011-04-01 19:42:22 +00005407 if (!Result.second.getNode()) {
Evan Chengc249e482011-04-01 19:57:01 +00005408 // As a special case, a null chain means that a tail call has been emitted and
5409 // the DAG root is already updated.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005410 HasTailCall = true;
Evan Cheng8380c032011-04-01 19:42:22 +00005411 ++SDNodeOrder;
5412 AssignOrderingToNode(DAG.getRoot().getNode());
5413 } else {
5414 DAG.setRoot(Result.second);
5415 ++SDNodeOrder;
5416 AssignOrderingToNode(Result.second.getNode());
5417 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005418
Chris Lattner512063d2010-04-05 06:19:28 +00005419 if (LandingPad) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005420 // Insert a label at the end of the invoke call to mark the try range. This
5421 // can be used to detect deletion of the invoke via the MachineModuleInfo.
Chris Lattner512063d2010-04-05 06:19:28 +00005422 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
Chris Lattner7561d482010-03-14 02:33:54 +00005423 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getRoot(), EndLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005424
5425 // Inform MachineModuleInfo of range.
Chris Lattner512063d2010-04-05 06:19:28 +00005426 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005427 }
5428}
5429
Chris Lattner8047d9a2009-12-24 00:37:38 +00005430/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5431/// value is equal or not-equal to zero.
Dan Gohman46510a72010-04-15 01:51:59 +00005432static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5433 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Chris Lattner8047d9a2009-12-24 00:37:38 +00005434 UI != E; ++UI) {
Dan Gohman46510a72010-04-15 01:51:59 +00005435 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
Chris Lattner8047d9a2009-12-24 00:37:38 +00005436 if (IC->isEquality())
Dan Gohman46510a72010-04-15 01:51:59 +00005437 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
Chris Lattner8047d9a2009-12-24 00:37:38 +00005438 if (C->isNullValue())
5439 continue;
5440 // Unknown instruction.
5441 return false;
5442 }
5443 return true;
5444}
5445
Dan Gohman46510a72010-04-15 01:51:59 +00005446static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005447 Type *LoadTy,
Chris Lattner8047d9a2009-12-24 00:37:38 +00005448 SelectionDAGBuilder &Builder) {
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005449
Chris Lattner8047d9a2009-12-24 00:37:38 +00005450 // Check to see if this load can be trivially constant folded, e.g. if the
5451 // input is from a string literal.
Dan Gohman46510a72010-04-15 01:51:59 +00005452 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
Chris Lattner8047d9a2009-12-24 00:37:38 +00005453 // Cast pointer to the type we really want to load.
Dan Gohman46510a72010-04-15 01:51:59 +00005454 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
Chris Lattner8047d9a2009-12-24 00:37:38 +00005455 PointerType::getUnqual(LoadTy));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005456
Dan Gohman46510a72010-04-15 01:51:59 +00005457 if (const Constant *LoadCst =
5458 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
5459 Builder.TD))
Chris Lattner8047d9a2009-12-24 00:37:38 +00005460 return Builder.getValue(LoadCst);
5461 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005462
Chris Lattner8047d9a2009-12-24 00:37:38 +00005463 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5464 // still constant memory, the input chain can be the entry node.
5465 SDValue Root;
5466 bool ConstantMemory = false;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005467
Chris Lattner8047d9a2009-12-24 00:37:38 +00005468 // Do not serialize (non-volatile) loads of constant memory with anything.
5469 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5470 Root = Builder.DAG.getEntryNode();
5471 ConstantMemory = true;
5472 } else {
5473 // Do not serialize non-volatile loads against each other.
5474 Root = Builder.DAG.getRoot();
5475 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005476
Chris Lattner8047d9a2009-12-24 00:37:38 +00005477 SDValue Ptr = Builder.getValue(PtrVal);
5478 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
Chris Lattnerecf42c42010-09-21 16:36:31 +00005479 Ptr, MachinePointerInfo(PtrVal),
David Greene1e559442010-02-15 17:00:31 +00005480 false /*volatile*/,
Pete Cooperd752e0f2011-11-08 18:42:53 +00005481 false /*nontemporal*/,
5482 false /*isinvariant*/, 1 /* align=1 */);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005483
Chris Lattner8047d9a2009-12-24 00:37:38 +00005484 if (!ConstantMemory)
5485 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5486 return LoadVal;
5487}
5488
5489
5490/// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5491/// If so, return true and lower it, otherwise return false and it will be
5492/// lowered like a normal call.
Dan Gohman46510a72010-04-15 01:51:59 +00005493bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
Chris Lattner8047d9a2009-12-24 00:37:38 +00005494 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
Gabor Greif37387d52010-06-30 12:55:46 +00005495 if (I.getNumArgOperands() != 3)
Chris Lattner8047d9a2009-12-24 00:37:38 +00005496 return false;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005497
Gabor Greif0635f352010-06-25 09:38:13 +00005498 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
Duncan Sands1df98592010-02-16 11:11:14 +00005499 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
Gabor Greif0635f352010-06-25 09:38:13 +00005500 !I.getArgOperand(2)->getType()->isIntegerTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00005501 !I.getType()->isIntegerTy())
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005502 return false;
5503
Gabor Greif0635f352010-06-25 09:38:13 +00005504 const ConstantInt *Size = dyn_cast<ConstantInt>(I.getArgOperand(2));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005505
Chris Lattner8047d9a2009-12-24 00:37:38 +00005506 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5507 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
Chris Lattner04b091a2009-12-24 01:07:17 +00005508 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
5509 bool ActuallyDoIt = true;
5510 MVT LoadVT;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005511 Type *LoadTy;
Chris Lattner04b091a2009-12-24 01:07:17 +00005512 switch (Size->getZExtValue()) {
5513 default:
5514 LoadVT = MVT::Other;
5515 LoadTy = 0;
5516 ActuallyDoIt = false;
5517 break;
5518 case 2:
5519 LoadVT = MVT::i16;
5520 LoadTy = Type::getInt16Ty(Size->getContext());
5521 break;
5522 case 4:
5523 LoadVT = MVT::i32;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005524 LoadTy = Type::getInt32Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00005525 break;
5526 case 8:
5527 LoadVT = MVT::i64;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005528 LoadTy = Type::getInt64Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00005529 break;
5530 /*
5531 case 16:
5532 LoadVT = MVT::v4i32;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005533 LoadTy = Type::getInt32Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00005534 LoadTy = VectorType::get(LoadTy, 4);
5535 break;
5536 */
5537 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005538
Chris Lattner04b091a2009-12-24 01:07:17 +00005539 // This turns into unaligned loads. We only do this if the target natively
5540 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5541 // we'll only produce a small number of byte loads.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005542
Chris Lattner04b091a2009-12-24 01:07:17 +00005543 // Require that we can find a legal MVT, and only do this if the target
5544 // supports unaligned loads of that type. Expanding into byte loads would
5545 // bloat the code.
5546 if (ActuallyDoIt && Size->getZExtValue() > 4) {
5547 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5548 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5549 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
5550 ActuallyDoIt = false;
5551 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005552
Chris Lattner04b091a2009-12-24 01:07:17 +00005553 if (ActuallyDoIt) {
5554 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5555 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005556
Chris Lattner04b091a2009-12-24 01:07:17 +00005557 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
5558 ISD::SETNE);
5559 EVT CallVT = TLI.getValueType(I.getType(), true);
5560 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
5561 return true;
5562 }
Chris Lattner8047d9a2009-12-24 00:37:38 +00005563 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005564
5565
Chris Lattner8047d9a2009-12-24 00:37:38 +00005566 return false;
5567}
5568
Bob Wilson53624a22012-08-03 23:29:17 +00005569/// visitUnaryFloatCall - If a call instruction is a unary floating-point
5570/// operation (as expected), translate it to an SDNode with the specified opcode
5571/// and return true.
5572bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
5573 unsigned Opcode) {
5574 // Sanity check that it really is a unary floating-point call.
5575 if (I.getNumArgOperands() != 1 ||
5576 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5577 I.getType() != I.getArgOperand(0)->getType() ||
5578 !I.onlyReadsMemory())
5579 return false;
5580
5581 SDValue Tmp = getValue(I.getArgOperand(0));
5582 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(), Tmp.getValueType(), Tmp));
5583 return true;
5584}
Chris Lattner8047d9a2009-12-24 00:37:38 +00005585
Dan Gohman46510a72010-04-15 01:51:59 +00005586void SelectionDAGBuilder::visitCall(const CallInst &I) {
Chris Lattner598751e2010-07-05 05:36:21 +00005587 // Handle inline assembly differently.
5588 if (isa<InlineAsm>(I.getCalledValue())) {
5589 visitInlineAsm(&I);
5590 return;
5591 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00005592
Michael J. Spencer391b43b2010-10-21 20:49:23 +00005593 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Michael J. Spencerc9c137b2012-02-22 19:06:13 +00005594 ComputeUsesVAFloatArgument(I, &MMI);
Michael J. Spencer391b43b2010-10-21 20:49:23 +00005595
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005596 const char *RenameFn = 0;
5597 if (Function *F = I.getCalledFunction()) {
5598 if (F->isDeclaration()) {
Chris Lattner598751e2010-07-05 05:36:21 +00005599 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
Dale Johannesen49de9822009-02-05 01:49:45 +00005600 if (unsigned IID = II->getIntrinsicID(F)) {
5601 RenameFn = visitIntrinsicCall(I, IID);
5602 if (!RenameFn)
5603 return;
5604 }
5605 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005606 if (unsigned IID = F->getIntrinsicID()) {
5607 RenameFn = visitIntrinsicCall(I, IID);
5608 if (!RenameFn)
5609 return;
5610 }
5611 }
5612
5613 // Check for well-known libc/libm calls. If the function is internal, it
5614 // can't be a library call.
Bob Wilson982dc842012-08-03 21:26:24 +00005615 LibFunc::Func Func;
5616 if (!F->hasLocalLinkage() && F->hasName() &&
5617 LibInfo->getLibFunc(F->getName(), Func) &&
5618 LibInfo->hasOptimizedCodeGen(Func)) {
5619 switch (Func) {
5620 default: break;
5621 case LibFunc::copysign:
5622 case LibFunc::copysignf:
5623 case LibFunc::copysignl:
Gabor Greif37387d52010-06-30 12:55:46 +00005624 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
Gabor Greif0635f352010-06-25 09:38:13 +00005625 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5626 I.getType() == I.getArgOperand(0)->getType() &&
Bob Wilson53624a22012-08-03 23:29:17 +00005627 I.getType() == I.getArgOperand(1)->getType() &&
5628 I.onlyReadsMemory()) {
Gabor Greif0635f352010-06-25 09:38:13 +00005629 SDValue LHS = getValue(I.getArgOperand(0));
5630 SDValue RHS = getValue(I.getArgOperand(1));
Bill Wendling0d580132009-12-23 01:28:19 +00005631 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
5632 LHS.getValueType(), LHS, RHS));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005633 return;
5634 }
Bob Wilson982dc842012-08-03 21:26:24 +00005635 break;
5636 case LibFunc::fabs:
5637 case LibFunc::fabsf:
5638 case LibFunc::fabsl:
Bob Wilson53624a22012-08-03 23:29:17 +00005639 if (visitUnaryFloatCall(I, ISD::FABS))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005640 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005641 break;
5642 case LibFunc::sin:
5643 case LibFunc::sinf:
5644 case LibFunc::sinl:
Bob Wilson53624a22012-08-03 23:29:17 +00005645 if (visitUnaryFloatCall(I, ISD::FSIN))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005646 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005647 break;
5648 case LibFunc::cos:
5649 case LibFunc::cosf:
5650 case LibFunc::cosl:
Bob Wilson53624a22012-08-03 23:29:17 +00005651 if (visitUnaryFloatCall(I, ISD::FCOS))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005652 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005653 break;
5654 case LibFunc::sqrt:
5655 case LibFunc::sqrtf:
5656 case LibFunc::sqrtl:
Bob Wilson53624a22012-08-03 23:29:17 +00005657 if (visitUnaryFloatCall(I, ISD::FSQRT))
Dale Johannesen52fb79b2009-09-25 17:23:22 +00005658 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005659 break;
5660 case LibFunc::floor:
5661 case LibFunc::floorf:
5662 case LibFunc::floorl:
Bob Wilson53624a22012-08-03 23:29:17 +00005663 if (visitUnaryFloatCall(I, ISD::FFLOOR))
Owen Anderson4a4fdf32011-12-08 19:32:14 +00005664 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005665 break;
5666 case LibFunc::nearbyint:
5667 case LibFunc::nearbyintf:
5668 case LibFunc::nearbyintl:
Bob Wilson53624a22012-08-03 23:29:17 +00005669 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
Owen Anderson4a4fdf32011-12-08 19:32:14 +00005670 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005671 break;
5672 case LibFunc::ceil:
5673 case LibFunc::ceilf:
5674 case LibFunc::ceill:
Bob Wilson53624a22012-08-03 23:29:17 +00005675 if (visitUnaryFloatCall(I, ISD::FCEIL))
Owen Anderson4a4fdf32011-12-08 19:32:14 +00005676 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005677 break;
5678 case LibFunc::rint:
5679 case LibFunc::rintf:
5680 case LibFunc::rintl:
Bob Wilson53624a22012-08-03 23:29:17 +00005681 if (visitUnaryFloatCall(I, ISD::FRINT))
Owen Anderson4a4fdf32011-12-08 19:32:14 +00005682 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005683 break;
5684 case LibFunc::trunc:
5685 case LibFunc::truncf:
5686 case LibFunc::truncl:
Bob Wilson53624a22012-08-03 23:29:17 +00005687 if (visitUnaryFloatCall(I, ISD::FTRUNC))
Owen Anderson4a4fdf32011-12-08 19:32:14 +00005688 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005689 break;
5690 case LibFunc::log2:
5691 case LibFunc::log2f:
5692 case LibFunc::log2l:
Bob Wilson53624a22012-08-03 23:29:17 +00005693 if (visitUnaryFloatCall(I, ISD::FLOG2))
Owen Anderson4e0adfa2011-12-15 00:54:12 +00005694 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005695 break;
5696 case LibFunc::exp2:
5697 case LibFunc::exp2f:
5698 case LibFunc::exp2l:
Bob Wilson53624a22012-08-03 23:29:17 +00005699 if (visitUnaryFloatCall(I, ISD::FEXP2))
Owen Anderson4e0adfa2011-12-15 00:54:12 +00005700 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005701 break;
5702 case LibFunc::memcmp:
Chris Lattner8047d9a2009-12-24 00:37:38 +00005703 if (visitMemCmpCall(I))
5704 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005705 break;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005706 }
5707 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005708 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00005709
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005710 SDValue Callee;
5711 if (!RenameFn)
Gabor Greif0635f352010-06-25 09:38:13 +00005712 Callee = getValue(I.getCalledValue());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005713 else
Bill Wendling056292f2008-09-16 21:48:12 +00005714 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005715
Bill Wendling0d580132009-12-23 01:28:19 +00005716 // Check if we can potentially perform a tail call. More detailed checking is
5717 // be done within LowerCallTo, after more information about the call is known.
Evan Cheng11e67932010-01-26 23:13:04 +00005718 LowerCallTo(&I, Callee, I.isTailCall());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005719}
5720
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005721namespace {
Dan Gohman462f6b52010-05-29 17:53:24 +00005722
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005723/// AsmOperandInfo - This contains information for each constraint that we are
5724/// lowering.
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005725class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
Cedric Venetaff9c272009-02-14 16:06:42 +00005726public:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005727 /// CallOperand - If this is the result output operand or a clobber
5728 /// this is null, otherwise it is the incoming operand to the CallInst.
5729 /// This gets modified as the asm is processed.
5730 SDValue CallOperand;
5731
5732 /// AssignedRegs - If this is a register or register class operand, this
5733 /// contains the set of register corresponding to the operand.
5734 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005735
John Thompsoneac6e1d2010-09-13 18:15:37 +00005736 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005737 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
5738 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005739
Owen Andersone50ed302009-08-10 22:56:29 +00005740 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
Chris Lattner81249c92008-10-17 17:05:25 +00005741 /// corresponds to. If there is no Value* for this operand, it returns
Owen Anderson825b72b2009-08-11 20:47:22 +00005742 /// MVT::Other.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005743 EVT getCallOperandValEVT(LLVMContext &Context,
Owen Anderson1d0be152009-08-13 21:58:54 +00005744 const TargetLowering &TLI,
Chris Lattner81249c92008-10-17 17:05:25 +00005745 const TargetData *TD) const {
Owen Anderson825b72b2009-08-11 20:47:22 +00005746 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005747
Chris Lattner81249c92008-10-17 17:05:25 +00005748 if (isa<BasicBlock>(CallOperandVal))
5749 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005750
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005751 llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005752
Eric Christophercef81b72011-05-09 20:04:43 +00005753 // FIXME: code duplicated from TargetLowering::ParseConstraints().
Chris Lattner81249c92008-10-17 17:05:25 +00005754 // If this is an indirect operand, the operand is a pointer to the
5755 // accessed type.
Bob Wilsone261b0c2009-12-22 18:34:19 +00005756 if (isIndirect) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005757 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
Bob Wilsone261b0c2009-12-22 18:34:19 +00005758 if (!PtrTy)
Chris Lattner75361b62010-04-07 22:58:41 +00005759 report_fatal_error("Indirect operand for inline asm not a pointer!");
Bob Wilsone261b0c2009-12-22 18:34:19 +00005760 OpTy = PtrTy->getElementType();
5761 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005762
Eric Christophercef81b72011-05-09 20:04:43 +00005763 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005764 if (StructType *STy = dyn_cast<StructType>(OpTy))
Eric Christophercef81b72011-05-09 20:04:43 +00005765 if (STy->getNumElements() == 1)
5766 OpTy = STy->getElementType(0);
5767
Chris Lattner81249c92008-10-17 17:05:25 +00005768 // If OpTy is not a single value, it may be a struct/union that we
5769 // can tile with integers.
5770 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5771 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
5772 switch (BitSize) {
5773 default: break;
5774 case 1:
5775 case 8:
5776 case 16:
5777 case 32:
5778 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00005779 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00005780 OpTy = IntegerType::get(Context, BitSize);
Chris Lattner81249c92008-10-17 17:05:25 +00005781 break;
5782 }
5783 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005784
Chris Lattner81249c92008-10-17 17:05:25 +00005785 return TLI.getValueType(OpTy, true);
5786 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005787};
Dan Gohman462f6b52010-05-29 17:53:24 +00005788
John Thompson44ab89e2010-10-29 17:29:13 +00005789typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
5790
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005791} // end anonymous namespace
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005792
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005793/// GetRegistersForValue - Assign registers (virtual or physical) for the
5794/// specified operand. We prefer to assign virtual registers, to allow the
Bob Wilson266d9452009-12-17 05:07:36 +00005795/// register allocator to handle the assignment process. However, if the asm
5796/// uses features that we can't model on machineinstrs, we have SDISel do the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005797/// allocation. This produces generally horrible, but correct, code.
5798///
5799/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005800///
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005801static void GetRegistersForValue(SelectionDAG &DAG,
5802 const TargetLowering &TLI,
5803 DebugLoc DL,
Benjamin Kramer8b93ff22012-02-24 14:01:17 +00005804 SDISelAsmOperandInfo &OpInfo) {
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005805 LLVMContext &Context = *DAG.getContext();
Owen Anderson23b9b192009-08-12 00:36:31 +00005806
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005807 MachineFunction &MF = DAG.getMachineFunction();
5808 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005809
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005810 // If this is a constraint for a single physreg, or a constraint for a
5811 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005812 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005813 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5814 OpInfo.ConstraintVT);
5815
5816 unsigned NumRegs = 1;
Owen Anderson825b72b2009-08-11 20:47:22 +00005817 if (OpInfo.ConstraintVT != MVT::Other) {
Chris Lattner01426e12008-10-21 00:45:36 +00005818 // If this is a FP input in an integer register (or visa versa) insert a bit
5819 // cast of the input value. More generally, handle any case where the input
5820 // value disagrees with the register class we plan to stick this in.
5821 if (OpInfo.Type == InlineAsm::isInput &&
5822 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
Owen Andersone50ed302009-08-10 22:56:29 +00005823 // Try to convert to the first EVT that the reg class contains. If the
Chris Lattner01426e12008-10-21 00:45:36 +00005824 // types are identical size, use a bitcast to convert (e.g. two differing
5825 // vector types).
Owen Andersone50ed302009-08-10 22:56:29 +00005826 EVT RegVT = *PhysReg.second->vt_begin();
Chris Lattner01426e12008-10-21 00:45:36 +00005827 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005828 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005829 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00005830 OpInfo.ConstraintVT = RegVT;
5831 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5832 // If the input is a FP value and we want it in FP registers, do a
5833 // bitcast to the corresponding integer type. This turns an f64 value
5834 // into i64, which can be passed with two i32 values on a 32-bit
5835 // machine.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005836 RegVT = EVT::getIntegerVT(Context,
Owen Anderson23b9b192009-08-12 00:36:31 +00005837 OpInfo.ConstraintVT.getSizeInBits());
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005838 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005839 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00005840 OpInfo.ConstraintVT = RegVT;
5841 }
5842 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005843
Owen Anderson23b9b192009-08-12 00:36:31 +00005844 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00005845 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005846
Owen Andersone50ed302009-08-10 22:56:29 +00005847 EVT RegVT;
5848 EVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005849
5850 // If this is a constraint for a specific physical register, like {r17},
5851 // assign it now.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005852 if (unsigned AssignedReg = PhysReg.first) {
5853 const TargetRegisterClass *RC = PhysReg.second;
Owen Anderson825b72b2009-08-11 20:47:22 +00005854 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005855 ValueVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005856
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005857 // Get the actual register value type. This is important, because the user
5858 // may have asked for (e.g.) the AX register in i32 type. We need to
5859 // remember that AX is actually i16 to get the right extension.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005860 RegVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005861
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005862 // This is a explicit reference to a physical register.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005863 Regs.push_back(AssignedReg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005864
5865 // If this is an expanded reference, add the rest of the regs to Regs.
5866 if (NumRegs != 1) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005867 TargetRegisterClass::iterator I = RC->begin();
5868 for (; *I != AssignedReg; ++I)
5869 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005870
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005871 // Already added the first reg.
5872 --NumRegs; ++I;
5873 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005874 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005875 Regs.push_back(*I);
5876 }
5877 }
Bill Wendling651ad132009-12-22 01:25:10 +00005878
Dan Gohman7451d3e2010-05-29 17:03:36 +00005879 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005880 return;
5881 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005882
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005883 // Otherwise, if this was a reference to an LLVM register class, create vregs
5884 // for this reference.
Chris Lattnerb3b44842009-03-24 15:25:07 +00005885 if (const TargetRegisterClass *RC = PhysReg.second) {
5886 RegVT = *RC->vt_begin();
Owen Anderson825b72b2009-08-11 20:47:22 +00005887 if (OpInfo.ConstraintVT == MVT::Other)
Evan Chengfb112882009-03-23 08:01:15 +00005888 ValueVT = RegVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005889
Evan Chengfb112882009-03-23 08:01:15 +00005890 // Create the appropriate number of virtual registers.
5891 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5892 for (; NumRegs; --NumRegs)
Chris Lattnerb3b44842009-03-24 15:25:07 +00005893 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005894
Dan Gohman7451d3e2010-05-29 17:03:36 +00005895 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
Evan Chengfb112882009-03-23 08:01:15 +00005896 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005897 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005898
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005899 // Otherwise, we couldn't allocate enough registers for this.
5900}
5901
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005902/// visitInlineAsm - Handle a call to an InlineAsm object.
5903///
Dan Gohman46510a72010-04-15 01:51:59 +00005904void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
5905 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005906
5907 /// ConstraintOperands - Information about all of the constraints.
John Thompson44ab89e2010-10-29 17:29:13 +00005908 SDISelAsmOperandInfoVector ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005909
Evan Chengce1cdac2011-05-06 20:52:23 +00005910 TargetLowering::AsmOperandInfoVector
5911 TargetConstraints = TLI.ParseConstraints(CS);
5912
John Thompsoneac6e1d2010-09-13 18:15:37 +00005913 bool hasMemory = false;
Michael J. Spencere70c5262010-10-16 08:25:21 +00005914
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005915 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5916 unsigned ResNo = 0; // ResNo - The result number of the next output.
John Thompsoneac6e1d2010-09-13 18:15:37 +00005917 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
5918 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005919 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Michael J. Spencere70c5262010-10-16 08:25:21 +00005920
Owen Anderson825b72b2009-08-11 20:47:22 +00005921 EVT OpVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005922
5923 // Compute the value type for each operand.
5924 switch (OpInfo.Type) {
5925 case InlineAsm::isOutput:
5926 // Indirect outputs just consume an argument.
5927 if (OpInfo.isIndirect) {
Dan Gohman46510a72010-04-15 01:51:59 +00005928 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005929 break;
5930 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005931
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005932 // The return value of the call is this value. As such, there is no
5933 // corresponding argument.
Nick Lewycky8de34002011-09-30 22:19:53 +00005934 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005935 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005936 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5937 } else {
5938 assert(ResNo == 0 && "Asm only has one result!");
5939 OpVT = TLI.getValueType(CS.getType());
5940 }
5941 ++ResNo;
5942 break;
5943 case InlineAsm::isInput:
Dan Gohman46510a72010-04-15 01:51:59 +00005944 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005945 break;
5946 case InlineAsm::isClobber:
5947 // Nothing to do.
5948 break;
5949 }
5950
5951 // If this is an input or an indirect output, process the call argument.
5952 // BasicBlocks are labels, currently appearing only in asm's.
5953 if (OpInfo.CallOperandVal) {
Dan Gohman46510a72010-04-15 01:51:59 +00005954 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005955 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00005956 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005957 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005958 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005959
Owen Anderson1d0be152009-08-13 21:58:54 +00005960 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005961 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005962
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005963 OpInfo.ConstraintVT = OpVT;
Michael J. Spencere70c5262010-10-16 08:25:21 +00005964
John Thompsoneac6e1d2010-09-13 18:15:37 +00005965 // Indirect operand accesses access memory.
5966 if (OpInfo.isIndirect)
5967 hasMemory = true;
5968 else {
5969 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
Evan Chengce1cdac2011-05-06 20:52:23 +00005970 TargetLowering::ConstraintType
5971 CType = TLI.getConstraintType(OpInfo.Codes[j]);
John Thompsoneac6e1d2010-09-13 18:15:37 +00005972 if (CType == TargetLowering::C_Memory) {
5973 hasMemory = true;
5974 break;
5975 }
5976 }
5977 }
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005978 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005979
John Thompsoneac6e1d2010-09-13 18:15:37 +00005980 SDValue Chain, Flag;
5981
5982 // We won't need to flush pending loads if this asm doesn't touch
5983 // memory and is nonvolatile.
5984 if (hasMemory || IA->hasSideEffects())
5985 Chain = getRoot();
5986 else
5987 Chain = DAG.getRoot();
5988
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005989 // Second pass over the constraints: compute which constraint option to use
5990 // and assign registers to constraints that want a specific physreg.
John Thompsoneac6e1d2010-09-13 18:15:37 +00005991 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005992 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005993
John Thompson54584742010-09-24 22:24:05 +00005994 // If this is an output operand with a matching input operand, look up the
5995 // matching input. If their types mismatch, e.g. one is an integer, the
5996 // other is floating point, or their sizes are different, flag it as an
5997 // error.
5998 if (OpInfo.hasMatchingInput()) {
5999 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
Michael J. Spencere70c5262010-10-16 08:25:21 +00006000
John Thompson54584742010-09-24 22:24:05 +00006001 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Bill Wendling96cb1122012-07-19 00:04:14 +00006002 std::pair<unsigned, const TargetRegisterClass*> MatchRC =
6003 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
Evan Cheng1dafa702011-08-23 19:17:21 +00006004 OpInfo.ConstraintVT);
Bill Wendling96cb1122012-07-19 00:04:14 +00006005 std::pair<unsigned, const TargetRegisterClass*> InputRC =
6006 TLI.getRegForInlineAsmConstraint(Input.ConstraintCode,
Evan Cheng1dafa702011-08-23 19:17:21 +00006007 Input.ConstraintVT);
John Thompson54584742010-09-24 22:24:05 +00006008 if ((OpInfo.ConstraintVT.isInteger() !=
6009 Input.ConstraintVT.isInteger()) ||
Eric Christopher5427ede2011-07-14 20:13:52 +00006010 (MatchRC.second != InputRC.second)) {
John Thompson54584742010-09-24 22:24:05 +00006011 report_fatal_error("Unsupported asm: input constraint"
6012 " with a matching output constraint of"
6013 " incompatible type!");
6014 }
6015 Input.ConstraintVT = OpInfo.ConstraintVT;
6016 }
6017 }
6018
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006019 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +00006020 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006021
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006022 // If this is a memory input, and if the operand is not indirect, do what we
6023 // need to to provide an address for the memory input.
6024 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6025 !OpInfo.isIndirect) {
Evan Chengce1cdac2011-05-06 20:52:23 +00006026 assert((OpInfo.isMultipleAlternative ||
6027 (OpInfo.Type == InlineAsm::isInput)) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006028 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006029
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006030 // Memory operands really want the address of the value. If we don't have
6031 // an indirect input, put it in the constpool if we can, otherwise spill
6032 // it to a stack slot.
Eric Christophere0b42c02011-06-03 17:21:23 +00006033 // TODO: This isn't quite right. We need to handle these according to
6034 // the addressing mode that the constraint wants. Also, this may take
6035 // an additional register for the computation and we don't want that
6036 // either.
Eric Christopher471e4222011-06-08 23:55:35 +00006037
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006038 // If the operand is a float, integer, or vector constant, spill to a
6039 // constant pool entry to get its address.
Dan Gohman46510a72010-04-15 01:51:59 +00006040 const Value *OpVal = OpInfo.CallOperandVal;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006041 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
Chris Lattnera78fa8c2012-01-27 03:08:05 +00006042 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006043 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
6044 TLI.getPointerTy());
6045 } else {
6046 // Otherwise, create a stack slot and emit a store to it before the
6047 // asm.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00006048 Type *Ty = OpVal->getType();
Duncan Sands777d2302009-05-09 07:06:46 +00006049 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006050 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
6051 MachineFunction &MF = DAG.getMachineFunction();
David Greene3f2bf852009-11-12 20:49:22 +00006052 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006053 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Dale Johannesen66978ee2009-01-31 02:22:37 +00006054 Chain = DAG.getStore(Chain, getCurDebugLoc(),
Chris Lattnerecf42c42010-09-21 16:36:31 +00006055 OpInfo.CallOperand, StackSlot,
6056 MachinePointerInfo::getFixedStack(SSFI),
David Greene1e559442010-02-15 17:00:31 +00006057 false, false, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006058 OpInfo.CallOperand = StackSlot;
6059 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006060
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006061 // There is no longer a Value* corresponding to this operand.
6062 OpInfo.CallOperandVal = 0;
Bill Wendling651ad132009-12-22 01:25:10 +00006063
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006064 // It is now an indirect operand.
6065 OpInfo.isIndirect = true;
6066 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006067
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006068 // If this constraint is for a specific register, allocate it before
6069 // anything else.
6070 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Benjamin Kramer8b93ff22012-02-24 14:01:17 +00006071 GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006072 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006073
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006074 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00006075 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006076 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6077 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006078
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006079 // C_Register operands have already been allocated, Other/Memory don't need
6080 // to be.
6081 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Benjamin Kramer8b93ff22012-02-24 14:01:17 +00006082 GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006083 }
6084
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006085 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6086 std::vector<SDValue> AsmNodeOperands;
6087 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
6088 AsmNodeOperands.push_back(
Dan Gohmanf2d7fb32010-01-04 21:00:54 +00006089 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
6090 TLI.getPointerTy()));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006091
Chris Lattnerdecc2672010-04-07 05:20:54 +00006092 // If we have a !srcloc metadata node associated with it, we want to attach
6093 // this to the ultimately generated inline asm machineinstr. To do this, we
6094 // pass in the third operand as this (potentially null) inline asm MDNode.
6095 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6096 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006097
Chad Rosier576cd112012-09-05 21:00:58 +00006098 // Remember the HasSideEffect, AlignStack and AsmDialect bits as operand 3.
Evan Chengc36b7062011-01-07 23:50:32 +00006099 unsigned ExtraInfo = 0;
6100 if (IA->hasSideEffects())
6101 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6102 if (IA->isAlignStack())
6103 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
Chad Rosier77fffa62012-09-05 22:17:43 +00006104 // Set the asm dialect.
Chad Rosier2f1d8152012-09-05 22:40:13 +00006105 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
Evan Chengc36b7062011-01-07 23:50:32 +00006106 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
6107 TLI.getPointerTy()));
Dale Johannesenf1e309e2010-07-02 20:16:09 +00006108
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006109 // Loop over all of the inputs, copying the operand values into the
6110 // appropriate registers and processing the output regs.
6111 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006112
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006113 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6114 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006115
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006116 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6117 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6118
6119 switch (OpInfo.Type) {
6120 case InlineAsm::isOutput: {
6121 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6122 OpInfo.ConstraintType != TargetLowering::C_Register) {
6123 // Memory output, or 'other' output (e.g. 'X' constraint).
6124 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6125
6126 // Add information to the INLINEASM node to know about this output.
Chris Lattnerdecc2672010-04-07 05:20:54 +00006127 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6128 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006129 TLI.getPointerTy()));
6130 AsmNodeOperands.push_back(OpInfo.CallOperand);
6131 break;
6132 }
6133
6134 // Otherwise, this is a register or register class output.
6135
6136 // Copy the output from the appropriate register. Find a register that
6137 // we can use.
Chris Lattnerfcd70902012-01-03 23:51:01 +00006138 if (OpInfo.AssignedRegs.Regs.empty()) {
6139 LLVMContext &Ctx = *DAG.getContext();
6140 Ctx.emitError(CS.getInstruction(),
6141 "couldn't allocate output register for constraint '" +
6142 Twine(OpInfo.ConstraintCode) + "'");
6143 break;
6144 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006145
6146 // If this is an indirect operand, store through the pointer after the
6147 // asm.
6148 if (OpInfo.isIndirect) {
6149 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6150 OpInfo.CallOperandVal));
6151 } else {
6152 // This is the result value of the call.
Benjamin Kramerf0127052010-01-05 13:12:22 +00006153 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006154 // Concatenate this output onto the outputs list.
6155 RetValRegs.append(OpInfo.AssignedRegs);
6156 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006157
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006158 // Add information to the INLINEASM node to know that this register is
6159 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00006160 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
Chris Lattnerdecc2672010-04-07 05:20:54 +00006161 InlineAsm::Kind_RegDefEarlyClobber :
6162 InlineAsm::Kind_RegDef,
Evan Chengfb112882009-03-23 08:01:15 +00006163 false,
6164 0,
Bill Wendling46ada192010-03-02 01:55:18 +00006165 DAG,
Bill Wendling651ad132009-12-22 01:25:10 +00006166 AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006167 break;
6168 }
6169 case InlineAsm::isInput: {
6170 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006171
Chris Lattner6bdcda32008-10-17 16:47:46 +00006172 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006173 // If this is required to match an output register we have already set,
6174 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00006175 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006176
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006177 // Scan until we find the definition we already emitted of this operand.
6178 // When we find it, create a RegsForValue operand.
Chris Lattnerdecc2672010-04-07 05:20:54 +00006179 unsigned CurOp = InlineAsm::Op_FirstOperand;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006180 for (; OperandNo; --OperandNo) {
6181 // Advance to the next operand.
Evan Cheng697cbbf2009-03-20 18:03:34 +00006182 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00006183 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Chris Lattnerdecc2672010-04-07 05:20:54 +00006184 assert((InlineAsm::isRegDefKind(OpFlag) ||
6185 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6186 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
Evan Cheng697cbbf2009-03-20 18:03:34 +00006187 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006188 }
6189
Evan Cheng697cbbf2009-03-20 18:03:34 +00006190 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00006191 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Chris Lattnerdecc2672010-04-07 05:20:54 +00006192 if (InlineAsm::isRegDefKind(OpFlag) ||
6193 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
Evan Cheng697cbbf2009-03-20 18:03:34 +00006194 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Chris Lattner6129c372010-04-08 00:09:16 +00006195 if (OpInfo.isIndirect) {
6196 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
Dan Gohman99be8ae2010-04-19 22:41:47 +00006197 LLVMContext &Ctx = *DAG.getContext();
Chris Lattner6129c372010-04-08 00:09:16 +00006198 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6199 " don't know how to handle tied "
6200 "indirect register inputs");
6201 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00006202
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006203 RegsForValue MatchedRegs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006204 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Owen Andersone50ed302009-08-10 22:56:29 +00006205 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
Evan Chengfb112882009-03-23 08:01:15 +00006206 MatchedRegs.RegVTs.push_back(RegVT);
6207 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng697cbbf2009-03-20 18:03:34 +00006208 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Evan Chengfb112882009-03-23 08:01:15 +00006209 i != e; ++i)
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00006210 MatchedRegs.Regs.push_back
6211 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006212
6213 // Use the produced MatchedRegs object to
Dale Johannesen66978ee2009-01-31 02:22:37 +00006214 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
Bill Wendling46ada192010-03-02 01:55:18 +00006215 Chain, &Flag);
Chris Lattnerdecc2672010-04-07 05:20:54 +00006216 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
Evan Chengfb112882009-03-23 08:01:15 +00006217 true, OpInfo.getMatchedOperand(),
Bill Wendling46ada192010-03-02 01:55:18 +00006218 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006219 break;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006220 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00006221
Chris Lattnerdecc2672010-04-07 05:20:54 +00006222 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6223 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6224 "Unexpected number of operands");
6225 // Add information to the INLINEASM node to know about this input.
6226 // See InlineAsm.h isUseOperandTiedToDef.
6227 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6228 OpInfo.getMatchedOperand());
6229 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
6230 TLI.getPointerTy()));
6231 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6232 break;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006233 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006234
Dale Johannesenb5611a62010-07-13 20:17:05 +00006235 // Treat indirect 'X' constraint as memory.
Michael J. Spencere70c5262010-10-16 08:25:21 +00006236 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6237 OpInfo.isIndirect)
Dale Johannesenb5611a62010-07-13 20:17:05 +00006238 OpInfo.ConstraintType = TargetLowering::C_Memory;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006239
Dale Johannesenb5611a62010-07-13 20:17:05 +00006240 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006241 std::vector<SDValue> Ops;
Eric Christopher100c8332011-06-02 23:16:42 +00006242 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
Dale Johannesen1784d162010-06-25 21:55:36 +00006243 Ops, DAG);
Chris Lattnerfcd70902012-01-03 23:51:01 +00006244 if (Ops.empty()) {
6245 LLVMContext &Ctx = *DAG.getContext();
6246 Ctx.emitError(CS.getInstruction(),
6247 "invalid operand for inline asm constraint '" +
6248 Twine(OpInfo.ConstraintCode) + "'");
6249 break;
6250 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006251
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006252 // Add information to the INLINEASM node to know about this input.
Chris Lattnerdecc2672010-04-07 05:20:54 +00006253 unsigned ResOpType =
6254 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006255 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006256 TLI.getPointerTy()));
6257 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6258 break;
Chris Lattnerdecc2672010-04-07 05:20:54 +00006259 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00006260
Chris Lattnerdecc2672010-04-07 05:20:54 +00006261 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006262 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6263 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
6264 "Memory operands expect pointer values");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006265
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006266 // Add information to the INLINEASM node to know about this input.
Chris Lattnerdecc2672010-04-07 05:20:54 +00006267 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
Dale Johannesen86b49f82008-09-24 01:07:17 +00006268 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006269 TLI.getPointerTy()));
6270 AsmNodeOperands.push_back(InOperandVal);
6271 break;
6272 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006273
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006274 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6275 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6276 "Unknown constraint type!");
Eric Christopher9eb4f8a2012-07-02 21:16:43 +00006277
6278 // TODO: Support this.
6279 if (OpInfo.isIndirect) {
6280 LLVMContext &Ctx = *DAG.getContext();
6281 Ctx.emitError(CS.getInstruction(),
6282 "Don't know how to handle indirect register inputs yet "
6283 "for constraint '" + Twine(OpInfo.ConstraintCode) + "'");
6284 break;
6285 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006286
6287 // Copy the input into the appropriate registers.
Chris Lattnerfcd70902012-01-03 23:51:01 +00006288 if (OpInfo.AssignedRegs.Regs.empty()) {
6289 LLVMContext &Ctx = *DAG.getContext();
6290 Ctx.emitError(CS.getInstruction(),
6291 "couldn't allocate input reg for constraint '" +
6292 Twine(OpInfo.ConstraintCode) + "'");
6293 break;
6294 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006295
Dale Johannesen66978ee2009-01-31 02:22:37 +00006296 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
Bill Wendling46ada192010-03-02 01:55:18 +00006297 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006298
Chris Lattnerdecc2672010-04-07 05:20:54 +00006299 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
Bill Wendling46ada192010-03-02 01:55:18 +00006300 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006301 break;
6302 }
6303 case InlineAsm::isClobber: {
6304 // Add the clobbered value to the operand list, so that the register
6305 // allocator is aware that the physreg got clobbered.
6306 if (!OpInfo.AssignedRegs.Regs.empty())
Jakob Stoklund Olesenf792fa92011-06-27 04:08:33 +00006307 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
Bill Wendling46ada192010-03-02 01:55:18 +00006308 false, 0, DAG,
Bill Wendling651ad132009-12-22 01:25:10 +00006309 AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006310 break;
6311 }
6312 }
6313 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006314
Chris Lattnerdecc2672010-04-07 05:20:54 +00006315 // Finish up input operands. Set the input chain and add the flag last.
Dale Johannesenf1e309e2010-07-02 20:16:09 +00006316 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006317 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006318
Dale Johannesen66978ee2009-01-31 02:22:37 +00006319 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +00006320 DAG.getVTList(MVT::Other, MVT::Glue),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006321 &AsmNodeOperands[0], AsmNodeOperands.size());
6322 Flag = Chain.getValue(1);
6323
6324 // If this asm returns a register value, copy the result from that register
6325 // and set it as the value of the call.
6326 if (!RetValRegs.Regs.empty()) {
Dan Gohman7451d3e2010-05-29 17:03:36 +00006327 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
Bill Wendling46ada192010-03-02 01:55:18 +00006328 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006329
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006330 // FIXME: Why don't we do this for inline asms with MRVs?
6331 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
Owen Andersone50ed302009-08-10 22:56:29 +00006332 EVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006333
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006334 // If any of the results of the inline asm is a vector, it may have the
6335 // wrong width/num elts. This can happen for register classes that can
6336 // contain multiple different value types. The preg or vreg allocated may
6337 // not have the same VT as was expected. Convert it to the right type
6338 // with bit_convert.
6339 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006340 Val = DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00006341 ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00006342
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006343 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006344 ResultType.isInteger() && Val.getValueType().isInteger()) {
6345 // If a result value was tied to an input value, the computed result may
6346 // have a wider width than the expected result. Extract the relevant
6347 // portion.
Dale Johannesen66978ee2009-01-31 02:22:37 +00006348 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00006349 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006350
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006351 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00006352 }
Dan Gohman95915732008-10-18 01:03:45 +00006353
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006354 setValue(CS.getInstruction(), Val);
Dale Johannesenec65a7d2009-04-14 00:56:56 +00006355 // Don't need to use this as a chain in this case.
6356 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6357 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006358 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006359
Dan Gohman46510a72010-04-15 01:51:59 +00006360 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006361
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006362 // Process indirect outputs, first output all of the flagged copies out of
6363 // physregs.
6364 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6365 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Dan Gohman46510a72010-04-15 01:51:59 +00006366 const Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohman7451d3e2010-05-29 17:03:36 +00006367 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
Bill Wendling46ada192010-03-02 01:55:18 +00006368 Chain, &Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006369 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6370 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006371
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006372 // Emit the non-flagged stores from the physregs.
6373 SmallVector<SDValue, 8> OutChains;
Bill Wendling651ad132009-12-22 01:25:10 +00006374 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6375 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
6376 StoresToEmit[i].first,
6377 getValue(StoresToEmit[i].second),
Chris Lattner84bd98a2010-09-21 18:58:22 +00006378 MachinePointerInfo(StoresToEmit[i].second),
David Greene1e559442010-02-15 17:00:31 +00006379 false, false, 0);
Bill Wendling651ad132009-12-22 01:25:10 +00006380 OutChains.push_back(Val);
Bill Wendling651ad132009-12-22 01:25:10 +00006381 }
6382
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006383 if (!OutChains.empty())
Owen Anderson825b72b2009-08-11 20:47:22 +00006384 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006385 &OutChains[0], OutChains.size());
Bill Wendling651ad132009-12-22 01:25:10 +00006386
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006387 DAG.setRoot(Chain);
6388}
6389
Dan Gohman46510a72010-04-15 01:51:59 +00006390void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00006391 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
6392 MVT::Other, getRoot(),
Gabor Greif0635f352010-06-25 09:38:13 +00006393 getValue(I.getArgOperand(0)),
6394 DAG.getSrcValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006395}
6396
Dan Gohman46510a72010-04-15 01:51:59 +00006397void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
Rafael Espindola9d544d02010-07-12 18:11:17 +00006398 const TargetData &TD = *TLI.getTargetData();
Dale Johannesena04b7572009-02-03 23:04:43 +00006399 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
6400 getRoot(), getValue(I.getOperand(0)),
Rafael Espindolacbeeae22010-07-11 04:01:49 +00006401 DAG.getSrcValue(I.getOperand(0)),
Rafael Espindola9d544d02010-07-12 18:11:17 +00006402 TD.getABITypeAlignment(I.getType()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006403 setValue(&I, V);
6404 DAG.setRoot(V.getValue(1));
6405}
6406
Dan Gohman46510a72010-04-15 01:51:59 +00006407void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00006408 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
6409 MVT::Other, getRoot(),
Gabor Greif0635f352010-06-25 09:38:13 +00006410 getValue(I.getArgOperand(0)),
6411 DAG.getSrcValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006412}
6413
Dan Gohman46510a72010-04-15 01:51:59 +00006414void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00006415 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
6416 MVT::Other, getRoot(),
Gabor Greif0635f352010-06-25 09:38:13 +00006417 getValue(I.getArgOperand(0)),
6418 getValue(I.getArgOperand(1)),
6419 DAG.getSrcValue(I.getArgOperand(0)),
6420 DAG.getSrcValue(I.getArgOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006421}
6422
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006423/// TargetLowering::LowerCallTo - This is the default LowerCallTo
Dan Gohman98ca4f22009-08-05 01:29:28 +00006424/// implementation, which just calls LowerCall.
6425/// FIXME: When all targets are
6426/// migrated to using LowerCall, this hook should be integrated into SDISel.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006427std::pair<SDValue, SDValue>
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006428TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006429 // Handle all of the outgoing arguments.
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006430 CLI.Outs.clear();
6431 CLI.OutVals.clear();
6432 ArgListTy &Args = CLI.Args;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006433 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +00006434 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006435 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
6436 for (unsigned Value = 0, NumValues = ValueVTs.size();
6437 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00006438 EVT VT = ValueVTs[Value];
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006439 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006440 SDValue Op = SDValue(Args[i].Node.getNode(),
6441 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006442 ISD::ArgFlagsTy Flags;
6443 unsigned OriginalAlignment =
6444 getTargetData()->getABITypeAlignment(ArgTy);
6445
6446 if (Args[i].isZExt)
6447 Flags.setZExt();
6448 if (Args[i].isSExt)
6449 Flags.setSExt();
6450 if (Args[i].isInReg)
6451 Flags.setInReg();
6452 if (Args[i].isSRet)
6453 Flags.setSRet();
6454 if (Args[i].isByVal) {
6455 Flags.setByVal();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00006456 PointerType *Ty = cast<PointerType>(Args[i].Ty);
6457 Type *ElementTy = Ty->getElementType();
Chris Lattner9db20f32011-05-22 23:23:02 +00006458 Flags.setByValSize(getTargetData()->getTypeAllocSize(ElementTy));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006459 // For ByVal, alignment should come from FE. BE will guess if this
6460 // info is not there but there are cases it cannot get right.
Chris Lattner9db20f32011-05-22 23:23:02 +00006461 unsigned FrameAlign;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006462 if (Args[i].Alignment)
6463 FrameAlign = Args[i].Alignment;
Chris Lattner9db20f32011-05-22 23:23:02 +00006464 else
6465 FrameAlign = getByValTypeAlignment(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006466 Flags.setByValAlign(FrameAlign);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006467 }
6468 if (Args[i].isNest)
6469 Flags.setNest();
6470 Flags.setOrigAlign(OriginalAlignment);
6471
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006472 EVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
6473 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006474 SmallVector<SDValue, 4> Parts(NumParts);
6475 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
6476
6477 if (Args[i].isSExt)
6478 ExtendKind = ISD::SIGN_EXTEND;
6479 else if (Args[i].isZExt)
6480 ExtendKind = ISD::ZERO_EXTEND;
6481
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006482 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts,
Bill Wendling3ea3c242009-12-22 02:10:19 +00006483 PartVT, ExtendKind);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006484
Dan Gohman98ca4f22009-08-05 01:29:28 +00006485 for (unsigned j = 0; j != NumParts; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006486 // if it isn't first piece, alignment must be 1
Dan Gohmanc9403652010-07-07 15:54:55 +00006487 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(),
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006488 i < CLI.NumFixedArgs);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006489 if (NumParts > 1 && j == 0)
6490 MyFlags.Flags.setSplit();
6491 else if (j != 0)
6492 MyFlags.Flags.setOrigAlign(1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006493
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006494 CLI.Outs.push_back(MyFlags);
6495 CLI.OutVals.push_back(Parts[j]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006496 }
6497 }
6498 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006499
Dan Gohman98ca4f22009-08-05 01:29:28 +00006500 // Handle the incoming return values from the call.
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006501 CLI.Ins.clear();
Owen Andersone50ed302009-08-10 22:56:29 +00006502 SmallVector<EVT, 4> RetTys;
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006503 ComputeValueVTs(*this, CLI.RetTy, RetTys);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006504 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00006505 EVT VT = RetTys[I];
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006506 EVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
6507 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006508 for (unsigned i = 0; i != NumRegs; ++i) {
6509 ISD::InputArg MyFlags;
Duncan Sands1440e8b2010-11-03 11:35:31 +00006510 MyFlags.VT = RegisterVT.getSimpleVT();
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006511 MyFlags.Used = CLI.IsReturnValueUsed;
6512 if (CLI.RetSExt)
Dan Gohman98ca4f22009-08-05 01:29:28 +00006513 MyFlags.Flags.setSExt();
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006514 if (CLI.RetZExt)
Dan Gohman98ca4f22009-08-05 01:29:28 +00006515 MyFlags.Flags.setZExt();
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006516 if (CLI.IsInReg)
Dan Gohman98ca4f22009-08-05 01:29:28 +00006517 MyFlags.Flags.setInReg();
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006518 CLI.Ins.push_back(MyFlags);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006519 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006520 }
6521
Dan Gohman98ca4f22009-08-05 01:29:28 +00006522 SmallVector<SDValue, 4> InVals;
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006523 CLI.Chain = LowerCall(CLI, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00006524
6525 // Verify that the target's LowerCall behaved as expected.
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006526 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00006527 "LowerCall didn't return a valid chain!");
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006528 assert((!CLI.IsTailCall || InVals.empty()) &&
Dan Gohman5e866062009-08-06 15:37:27 +00006529 "LowerCall emitted a return value for a tail call!");
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006530 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
Dan Gohman5e866062009-08-06 15:37:27 +00006531 "LowerCall didn't emit the correct number of values!");
Dan Gohman98ca4f22009-08-05 01:29:28 +00006532
6533 // For a tail call, the return value is merely live-out and there aren't
6534 // any nodes in the DAG representing it. Return a special value to
6535 // indicate that a tail call has been emitted and no more Instructions
6536 // should be processed in the current block.
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006537 if (CLI.IsTailCall) {
6538 CLI.DAG.setRoot(CLI.Chain);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006539 return std::make_pair(SDValue(), SDValue());
6540 }
6541
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006542 DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
Evan Chengaf1871f2010-03-11 19:38:18 +00006543 assert(InVals[i].getNode() &&
6544 "LowerCall emitted a null value!");
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006545 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
Evan Chengaf1871f2010-03-11 19:38:18 +00006546 "LowerCall emitted a value with the wrong type!");
6547 });
6548
Dan Gohman98ca4f22009-08-05 01:29:28 +00006549 // Collect the legal value parts into potentially illegal values
6550 // that correspond to the original function's return values.
6551 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006552 if (CLI.RetSExt)
Dan Gohman98ca4f22009-08-05 01:29:28 +00006553 AssertOp = ISD::AssertSext;
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006554 else if (CLI.RetZExt)
Dan Gohman98ca4f22009-08-05 01:29:28 +00006555 AssertOp = ISD::AssertZext;
6556 SmallVector<SDValue, 4> ReturnValues;
6557 unsigned CurReg = 0;
6558 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00006559 EVT VT = RetTys[I];
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006560 EVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
6561 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006562
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006563 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
Bill Wendling4533cac2010-01-28 21:51:40 +00006564 NumRegs, RegisterVT, VT,
6565 AssertOp));
Dan Gohman98ca4f22009-08-05 01:29:28 +00006566 CurReg += NumRegs;
6567 }
6568
6569 // For a function returning void, there is no return value. We can't create
6570 // such a node, so we just return a null return value in that case. In
Chris Lattner7a2bdde2011-04-15 05:18:47 +00006571 // that case, nothing will actually look at the value.
Dan Gohman98ca4f22009-08-05 01:29:28 +00006572 if (ReturnValues.empty())
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006573 return std::make_pair(SDValue(), CLI.Chain);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006574
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006575 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
6576 CLI.DAG.getVTList(&RetTys[0], RetTys.size()),
Dan Gohman98ca4f22009-08-05 01:29:28 +00006577 &ReturnValues[0], ReturnValues.size());
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006578 return std::make_pair(Res, CLI.Chain);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006579}
6580
Duncan Sands9fbc7e22009-01-21 09:00:29 +00006581void TargetLowering::LowerOperationWrapper(SDNode *N,
6582 SmallVectorImpl<SDValue> &Results,
Dan Gohmand858e902010-04-17 15:26:15 +00006583 SelectionDAG &DAG) const {
Duncan Sands9fbc7e22009-01-21 09:00:29 +00006584 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00006585 if (Res.getNode())
6586 Results.push_back(Res);
6587}
6588
Dan Gohmand858e902010-04-17 15:26:15 +00006589SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
Torok Edwinc23197a2009-07-14 16:55:14 +00006590 llvm_unreachable("LowerOperation not implemented for this target!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006591}
6592
Dan Gohman46510a72010-04-15 01:51:59 +00006593void
6594SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
Dan Gohman28a17352010-07-01 01:59:43 +00006595 SDValue Op = getNonRegisterValue(V);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006596 assert((Op.getOpcode() != ISD::CopyFromReg ||
6597 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
6598 "Copy from a reg to the same reg!");
6599 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
6600
Owen Anderson23b9b192009-08-12 00:36:31 +00006601 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006602 SDValue Chain = DAG.getEntryNode();
Bill Wendling46ada192010-03-02 01:55:18 +00006603 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006604 PendingExports.push_back(Chain);
6605}
6606
6607#include "llvm/CodeGen/SelectionDAGISel.h"
6608
Eli Friedman23d32432011-05-05 16:53:34 +00006609/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
6610/// entry block, return true. This includes arguments used by switches, since
6611/// the switch may expand into multiple basic blocks.
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006612static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
Eli Friedman23d32432011-05-05 16:53:34 +00006613 // With FastISel active, we may be splitting blocks, so force creation
6614 // of virtual registers for all non-dead arguments.
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006615 if (FastISel)
Eli Friedman23d32432011-05-05 16:53:34 +00006616 return A->use_empty();
6617
6618 const BasicBlock *Entry = A->getParent()->begin();
6619 for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end();
6620 UI != E; ++UI) {
6621 const User *U = *UI;
6622 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
6623 return false; // Use not in entry block.
6624 }
6625 return true;
6626}
6627
Dan Gohman46510a72010-04-15 01:51:59 +00006628void SelectionDAGISel::LowerArguments(const BasicBlock *LLVMBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006629 // If this is the entry block, emit arguments.
Dan Gohman46510a72010-04-15 01:51:59 +00006630 const Function &F = *LLVMBB->getParent();
Dan Gohman2048b852009-11-23 18:04:58 +00006631 SelectionDAG &DAG = SDB->DAG;
Dan Gohman2048b852009-11-23 18:04:58 +00006632 DebugLoc dl = SDB->getCurDebugLoc();
Dan Gohman98ca4f22009-08-05 01:29:28 +00006633 const TargetData *TD = TLI.getTargetData();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006634 SmallVector<ISD::InputArg, 16> Ins;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006635
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +00006636 // Check whether the function can return without sret-demotion.
Dan Gohman84023e02010-07-10 09:00:22 +00006637 SmallVector<ISD::OutputArg, 4> Outs;
6638 GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
6639 Outs, TLI);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006640
Dan Gohman7451d3e2010-05-29 17:03:36 +00006641 if (!FuncInfo->CanLowerReturn) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006642 // Put in an sret pointer parameter before all the other parameters.
6643 SmallVector<EVT, 1> ValueVTs;
6644 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6645
6646 // NOTE: Assuming that a pointer will never break down to more than one VT
6647 // or one register.
6648 ISD::ArgFlagsTy Flags;
6649 Flags.setSRet();
Dan Gohmanf81eca02010-04-22 20:46:50 +00006650 EVT RegisterVT = TLI.getRegisterType(*DAG.getContext(), ValueVTs[0]);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006651 ISD::InputArg RetArg(Flags, RegisterVT, true);
6652 Ins.push_back(RetArg);
6653 }
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +00006654
Dan Gohman98ca4f22009-08-05 01:29:28 +00006655 // Set up the incoming argument description vector.
Dan Gohman98ca4f22009-08-05 01:29:28 +00006656 unsigned Idx = 1;
Dan Gohman46510a72010-04-15 01:51:59 +00006657 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
Dan Gohman98ca4f22009-08-05 01:29:28 +00006658 I != E; ++I, ++Idx) {
Owen Andersone50ed302009-08-10 22:56:29 +00006659 SmallVector<EVT, 4> ValueVTs;
Dan Gohman98ca4f22009-08-05 01:29:28 +00006660 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6661 bool isArgValueUsed = !I->use_empty();
6662 for (unsigned Value = 0, NumValues = ValueVTs.size();
6663 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00006664 EVT VT = ValueVTs[Value];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00006665 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Dan Gohman98ca4f22009-08-05 01:29:28 +00006666 ISD::ArgFlagsTy Flags;
6667 unsigned OriginalAlignment =
6668 TD->getABITypeAlignment(ArgTy);
6669
6670 if (F.paramHasAttr(Idx, Attribute::ZExt))
6671 Flags.setZExt();
6672 if (F.paramHasAttr(Idx, Attribute::SExt))
6673 Flags.setSExt();
6674 if (F.paramHasAttr(Idx, Attribute::InReg))
6675 Flags.setInReg();
6676 if (F.paramHasAttr(Idx, Attribute::StructRet))
6677 Flags.setSRet();
6678 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
6679 Flags.setByVal();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00006680 PointerType *Ty = cast<PointerType>(I->getType());
6681 Type *ElementTy = Ty->getElementType();
Chris Lattner9db20f32011-05-22 23:23:02 +00006682 Flags.setByValSize(TD->getTypeAllocSize(ElementTy));
Dan Gohman98ca4f22009-08-05 01:29:28 +00006683 // For ByVal, alignment should be passed from FE. BE will guess if
6684 // this info is not there but there are cases it cannot get right.
Chris Lattner9db20f32011-05-22 23:23:02 +00006685 unsigned FrameAlign;
Dan Gohman98ca4f22009-08-05 01:29:28 +00006686 if (F.getParamAlignment(Idx))
6687 FrameAlign = F.getParamAlignment(Idx);
Chris Lattner9db20f32011-05-22 23:23:02 +00006688 else
6689 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006690 Flags.setByValAlign(FrameAlign);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006691 }
6692 if (F.paramHasAttr(Idx, Attribute::Nest))
6693 Flags.setNest();
6694 Flags.setOrigAlign(OriginalAlignment);
6695
Owen Anderson23b9b192009-08-12 00:36:31 +00006696 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6697 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006698 for (unsigned i = 0; i != NumRegs; ++i) {
6699 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
6700 if (NumRegs > 1 && i == 0)
6701 MyFlags.Flags.setSplit();
6702 // if it isn't first piece, alignment must be 1
6703 else if (i > 0)
6704 MyFlags.Flags.setOrigAlign(1);
6705 Ins.push_back(MyFlags);
6706 }
6707 }
6708 }
6709
6710 // Call the target to set up the argument values.
6711 SmallVector<SDValue, 8> InVals;
6712 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
6713 F.isVarArg(), Ins,
6714 dl, DAG, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00006715
6716 // Verify that the target's LowerFormalArguments behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00006717 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00006718 "LowerFormalArguments didn't return a valid chain!");
6719 assert(InVals.size() == Ins.size() &&
6720 "LowerFormalArguments didn't emit the correct number of values!");
Bill Wendling3ea58b62009-12-22 21:35:02 +00006721 DEBUG({
6722 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6723 assert(InVals[i].getNode() &&
6724 "LowerFormalArguments emitted a null value!");
Duncan Sands1440e8b2010-11-03 11:35:31 +00006725 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
Bill Wendling3ea58b62009-12-22 21:35:02 +00006726 "LowerFormalArguments emitted a value with the wrong type!");
6727 }
6728 });
Bill Wendling3ea3c242009-12-22 02:10:19 +00006729
Dan Gohman5e866062009-08-06 15:37:27 +00006730 // Update the DAG with the new chain value resulting from argument lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +00006731 DAG.setRoot(NewRoot);
6732
6733 // Set up the argument values.
6734 unsigned i = 0;
6735 Idx = 1;
Dan Gohman7451d3e2010-05-29 17:03:36 +00006736 if (!FuncInfo->CanLowerReturn) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006737 // Create a virtual register for the sret pointer, and put in a copy
6738 // from the sret argument into it.
6739 SmallVector<EVT, 1> ValueVTs;
6740 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6741 EVT VT = ValueVTs[0];
6742 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6743 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Bill Wendling46ada192010-03-02 01:55:18 +00006744 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
Bill Wendling3ea3c242009-12-22 02:10:19 +00006745 RegVT, VT, AssertOp);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006746
Dan Gohman2048b852009-11-23 18:04:58 +00006747 MachineFunction& MF = SDB->DAG.getMachineFunction();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006748 MachineRegisterInfo& RegInfo = MF.getRegInfo();
6749 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
Dan Gohman7451d3e2010-05-29 17:03:36 +00006750 FuncInfo->DemoteRegister = SRetReg;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00006751 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
6752 SRetReg, ArgValue);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006753 DAG.setRoot(NewRoot);
Bill Wendling3ea3c242009-12-22 02:10:19 +00006754
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006755 // i indexes lowered arguments. Bump it past the hidden sret argument.
6756 // Idx indexes LLVM arguments. Don't touch it.
6757 ++i;
6758 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006759
Dan Gohman46510a72010-04-15 01:51:59 +00006760 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
Dan Gohman98ca4f22009-08-05 01:29:28 +00006761 ++I, ++Idx) {
6762 SmallVector<SDValue, 4> ArgValues;
Owen Andersone50ed302009-08-10 22:56:29 +00006763 SmallVector<EVT, 4> ValueVTs;
Dan Gohman98ca4f22009-08-05 01:29:28 +00006764 ComputeValueVTs(TLI, I->getType(), ValueVTs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006765 unsigned NumValues = ValueVTs.size();
Devang Patel9126c0d2010-06-01 19:59:01 +00006766
6767 // If this argument is unused then remember its value. It is used to generate
6768 // debugging information.
6769 if (I->use_empty() && NumValues)
6770 SDB->setUnusedArgValue(I, InVals[i]);
6771
Eli Friedman23d32432011-05-05 16:53:34 +00006772 for (unsigned Val = 0; Val != NumValues; ++Val) {
6773 EVT VT = ValueVTs[Val];
Owen Anderson23b9b192009-08-12 00:36:31 +00006774 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6775 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006776
6777 if (!I->use_empty()) {
6778 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6779 if (F.paramHasAttr(Idx, Attribute::SExt))
6780 AssertOp = ISD::AssertSext;
6781 else if (F.paramHasAttr(Idx, Attribute::ZExt))
6782 AssertOp = ISD::AssertZext;
6783
Bill Wendling46ada192010-03-02 01:55:18 +00006784 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
Bill Wendling3ea3c242009-12-22 02:10:19 +00006785 NumParts, PartVT, VT,
6786 AssertOp));
Dan Gohman98ca4f22009-08-05 01:29:28 +00006787 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006788
Dan Gohman98ca4f22009-08-05 01:29:28 +00006789 i += NumParts;
6790 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006791
Eli Friedman23d32432011-05-05 16:53:34 +00006792 // We don't need to do anything else for unused arguments.
6793 if (ArgValues.empty())
6794 continue;
6795
Devang Patel9aee3352011-09-08 22:59:09 +00006796 // Note down frame index.
6797 if (FrameIndexSDNode *FI =
Bill Wendling96cb1122012-07-19 00:04:14 +00006798 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
Devang Patel9aee3352011-09-08 22:59:09 +00006799 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
Devang Patel0b48ead2010-08-31 22:22:42 +00006800
Eli Friedman23d32432011-05-05 16:53:34 +00006801 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
6802 SDB->getCurDebugLoc());
Devang Patel9aee3352011-09-08 22:59:09 +00006803
Eli Friedman23d32432011-05-05 16:53:34 +00006804 SDB->setValue(I, Res);
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006805 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
Devang Patel9aee3352011-09-08 22:59:09 +00006806 if (LoadSDNode *LNode =
6807 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
6808 if (FrameIndexSDNode *FI =
6809 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6810 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
6811 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006812
Eli Friedman23d32432011-05-05 16:53:34 +00006813 // If this argument is live outside of the entry block, insert a copy from
6814 // wherever we got it to the vreg that other BB's will reference it as.
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006815 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
Eli Friedman23d32432011-05-05 16:53:34 +00006816 // If we can, though, try to skip creating an unnecessary vreg.
6817 // FIXME: This isn't very clean... it would be nice to make this more
Eli Friedman7f33d672011-05-10 21:50:58 +00006818 // general. It's also subtly incompatible with the hacks FastISel
6819 // uses with vregs.
Eli Friedman23d32432011-05-05 16:53:34 +00006820 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
6821 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
6822 FuncInfo->ValueMap[I] = Reg;
6823 continue;
6824 }
6825 }
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006826 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
Eli Friedman23d32432011-05-05 16:53:34 +00006827 FuncInfo->InitializeRegForValue(I);
Dan Gohman2048b852009-11-23 18:04:58 +00006828 SDB->CopyToExportRegsIfNeeded(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006829 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006830 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006831
Dan Gohman98ca4f22009-08-05 01:29:28 +00006832 assert(i == InVals.size() && "Argument register count mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006833
6834 // Finally, if the target has anything special to do, allow it to do so.
6835 // FIXME: this should insert code into the DAG!
Dan Gohman64652652010-04-14 20:17:22 +00006836 EmitFunctionEntryCode();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006837}
6838
6839/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6840/// ensure constants are generated when needed. Remember the virtual registers
6841/// that need to be added to the Machine PHI nodes as input. We cannot just
6842/// directly add them, because expansion might result in multiple MBB's for one
6843/// BB. As such, the start of the BB might correspond to a different MBB than
6844/// the end.
6845///
6846void
Dan Gohmanf81eca02010-04-22 20:46:50 +00006847SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
Dan Gohman46510a72010-04-15 01:51:59 +00006848 const TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006849
6850 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6851
6852 // Check successor nodes' PHI nodes that expect a constant to be available
6853 // from this block.
6854 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
Dan Gohman46510a72010-04-15 01:51:59 +00006855 const BasicBlock *SuccBB = TI->getSuccessor(succ);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006856 if (!isa<PHINode>(SuccBB->begin())) continue;
Dan Gohmanf81eca02010-04-22 20:46:50 +00006857 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006858
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006859 // If this terminator has multiple identical successors (common for
6860 // switches), only handle each succ once.
6861 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006862
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006863 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006864
6865 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6866 // nodes and Machine PHI nodes, but the incoming operands have not been
6867 // emitted yet.
Dan Gohman46510a72010-04-15 01:51:59 +00006868 for (BasicBlock::const_iterator I = SuccBB->begin();
6869 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006870 // Ignore dead phi's.
6871 if (PN->use_empty()) continue;
6872
Rafael Espindola3fa82832011-05-13 15:18:06 +00006873 // Skip empty types
6874 if (PN->getType()->isEmptyTy())
6875 continue;
6876
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006877 unsigned Reg;
Dan Gohman46510a72010-04-15 01:51:59 +00006878 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006879
Dan Gohman46510a72010-04-15 01:51:59 +00006880 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
Dan Gohmanf81eca02010-04-22 20:46:50 +00006881 unsigned &RegOut = ConstantsOut[C];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006882 if (RegOut == 0) {
Dan Gohman89496d02010-07-02 00:10:16 +00006883 RegOut = FuncInfo.CreateRegs(C->getType());
Dan Gohmanf81eca02010-04-22 20:46:50 +00006884 CopyValueToVirtualRegister(C, RegOut);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006885 }
6886 Reg = RegOut;
6887 } else {
Dan Gohmanc25ad632010-07-01 01:33:21 +00006888 DenseMap<const Value *, unsigned>::iterator I =
6889 FuncInfo.ValueMap.find(PHIOp);
6890 if (I != FuncInfo.ValueMap.end())
6891 Reg = I->second;
6892 else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006893 assert(isa<AllocaInst>(PHIOp) &&
Dan Gohmanf81eca02010-04-22 20:46:50 +00006894 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006895 "Didn't codegen value into a register!??");
Dan Gohman89496d02010-07-02 00:10:16 +00006896 Reg = FuncInfo.CreateRegs(PHIOp->getType());
Dan Gohmanf81eca02010-04-22 20:46:50 +00006897 CopyValueToVirtualRegister(PHIOp, Reg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006898 }
6899 }
6900
6901 // Remember that this register needs to added to the machine PHI node as
6902 // the input for this MBB.
Owen Andersone50ed302009-08-10 22:56:29 +00006903 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006904 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6905 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
Owen Andersone50ed302009-08-10 22:56:29 +00006906 EVT VT = ValueVTs[vti];
Dan Gohmanf81eca02010-04-22 20:46:50 +00006907 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006908 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Dan Gohmanf81eca02010-04-22 20:46:50 +00006909 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006910 Reg += NumRegisters;
6911 }
6912 }
6913 }
Dan Gohmanf81eca02010-04-22 20:46:50 +00006914 ConstantsOut.clear();
Dan Gohman3df24e62008-09-03 23:12:08 +00006915}